Skip to content
Verified contractExactUNLICENSED

PropAMMCreditLens

Address0x1ca72b2e02c0b842b9ee42be56746063dcd7299d
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.35

 

Same code

2 more contracts

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 100 runs
EVM version
cancun
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,396,623
Creation transaction
0x3374f22a76…3fc9210a69
Libraries
src/core/mm/MMRouterLib.sol:MMRouterLib0xa474…d2b4e5src/core/flamm/FLAMMLane.sol:FLAMMLane0x0988…d22e98src/core/flamm/FLAMMRoute.sol:FLAMMRoute0x312e…0fdaa9src/periphery/FLAMMMaxima.sol:FLAMMMaxima0x4a99…d6259csrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0x5d47…27cc62src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x0bfe…043753src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xd53f…ed5983src/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0x2577…4e3473src/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0xf0be…2b9555src/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x7a11…58517bsrc/core/mm/CTokenMarketLib.sol:CTokenMarketLib0x18c5…b2071csrc/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0xa6db…bdcbcbsrc/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x0b8d…2e7e5csrc/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0x02b4…731ccesrc/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0xa16d…a201e8src/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0x539e…a79737src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0xa4d3…d5ce2esrc/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0x7c55…d233dfsrc/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0xcda6…a4dcf7src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x8423…7adc96src/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0xa6b4…0c67f9src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0xb489…d3c7cbsrc/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xfaae…2511basrc/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x480f…4e0a81src/hooks/everlong/LeverageLib.sol:LeverageLib0x1b1d…40ad11src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0x9499…409cc2src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0x0775…d94cbesrc/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xabe4…7426f7

src/periphery/PropAMMCreditLens.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

import {IFLAMM} from "src/interfaces/core/flamm/IFLAMM.sol";
import {PropAMMStore} from "src/propamm/libraries/PropAMMStore.sol";
import {PropAMMWords as W} from "src/propamm/libraries/PropAMMWords.sol";

/// @notice The front's slot read, as the lens reads it.
interface IFrontSlots {
    /// @notice The words at `slots` of the front's storage, in order.
    function extSloads(bytes32[] calldata slots) external view returns (bytes32[] memory);
}

/// @notice A redeployable read over one PropAMM front: a listing's pool and what the pool's own swap pays (its credit
///         path: custody, then lent supply, then a borrow where a pair of the pool may), so a router finds that depth
///         on any pool, whatever its credit mode at the front (mode 0, the default, keeps the front's own entries to
///         custody). It reads the front's published slots (`PropAMMStore`) through `extSloads`.
contract PropAMMCreditLens {
    using W for uint256;

    /// @notice The front this lens reads.
    address public immutable FRONT;

    /// @param front The front this lens reads.
    constructor(address front) {
        FRONT = front;
    }

    /// @notice The pool of `listing`, a listing live on the tokens' pair, and its own preview of `amountIn`, all or
    ///         nothing: zero where the pool would not take the whole input, refuses, or the listing is not live on the
    ///         pair. Fill it at the pool's `swap` with this as the minimum. On a builder build the preview prices
    ///         through the listing's desk's word, which fills in its landing block, or carried where its pair, its
    ///         listing and the word allow. It answers whatever the pool's credit mode at the front, which steers the
    ///         front's own entries only.
    function creditQuote(address tokenIn, address tokenOut, uint256 amountIn, uint24 listing)
        external
        view
        returns (address pool, uint256 amountOut)
    {
        (address t0, address t1) = tokenIn < tokenOut ? (tokenIn, tokenOut) : (tokenOut, tokenIn);
        uint256 base = uint256(PropAMMStore.BASE);
        // `pairIdOf`: the pair id in its low 32 bits (above it an asset-module pair's asset word and the pair facts)
        uint256 pairId = _load(keccak256(abi.encode(keccak256(abi.encodePacked(t0, t1)), base + 16))) & W.M32;
        if (pairId == 0) return (address(0), 0);
        uint256 s0 = _load(keccak256(abi.encode(uint256(listing), base + PropAMMStore.POOLS_INDEX)));
        if (listing == 0 || s0 & W.F_LIVE == 0 || s0.sPairId() != pairId) return (address(0), 0);
        pool = address(uint160(s0));
        try IFLAMM(pool).previewSwap(tokenIn, tokenOut, amountIn) returns (uint256 used, uint256 out, uint256) {
            if (used == amountIn) amountOut = out;
        } catch {}
    }

    /// @dev The front's word at `slot`.
    function _load(bytes32 slot) private view returns (uint256) {
        bytes32[] memory s = new bytes32[](1);
        s[0] = slot;
        return uint256(IFrontSlots(FRONT).extSloads(s)[0]);
    }
}

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

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

pragma solidity ^0.8.0;

/**
 * @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 amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` 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 amount
    ) external returns (bool);
}

lib/openzeppelin-contracts-compat/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @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 up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (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; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 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.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            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 (rounding == Rounding.Up && 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 down.
     *
     * 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * 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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * 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 + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * 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 10, 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 + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}

src/interfaces/core/flamm/IFLAMM.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {PoolContext} from "src/interfaces/core/flamm/IFLAMMHooks.sol";
import {PairRequest} from "src/interfaces/core/flamm/IPairHook.sol";

/// @notice The external surface of a pool that periphery, the Router, the Factory and the tranches rely on, and the
///         entries `FLAMMFront` serves or routes (`swap`, `previewSwap`, `pairRequest`, `switches`, `paused`,
///         `tokenConfig`, `pairConfig`, `position`, `collateralReserve`, `pending`, `poke`, `recenter`). The pool lists
///         tokens: token 0 is `asset()`, the share and NAV unit, and token 1 is `loanAsset()`, the numeraire and the
///         hook pair's quote; its credit pairs each borrow a debt token against a collateral token. Entries no contract
///         calls through it (the hook-set ceremony and its view, the governance setters, the admissions,
///         `maintainCollateral`, `maintain`, `emergency`, `executePerformanceFee`) are declared and documented on
///         `FLAMM` alone, and those `FLAMM`'s fallback hands to `FLAMMFloatLib` (the cheap lane's settings,
///         `collectSpreadFee`, the float actions) on that library. The fences' entries are on `IFLAMMFence`, the
///         front's on `IFLAMMLane`.
/// @dev FLAMM stands for financed-leg automated market maker. Who calls whom:
///      - `FLAMMFactory` creates pools for anyone, is their beacon and constructs the one shared `MMRouter`.
///      - A pool is a `FLAMMProxy` over `FLAMMFront`, the Factory's implementation, which hands every entry it does
///        not serve to `FLAMM` and its libraries. The pool keeps the custody, the shares and the pool book.
///      - `MMRouter` (`IMMRouter`) keeps each pool's pairs and venues, takes each pool's calls for its own alone and
///        drives the pool's financing accounts. It never holds a token.
///      - A financing account (`IFinancingAccount`) carries a pool's legs at one lender, a venue kind being one
///        lender's code. The Router calls its normal path and its pool calls the emergency path.
///      - `PriceFeed` (`IPriceFeed`) serves the checked USD prices the pool reads; the Router reads no feed, but takes
///        each price from the pool's call (`usd`).
///      - `core()` (`IEverlongCore`: an `EverlongCore`, or a `DelayedAuthority`, which puts delays on its owner and
///        guardian) names the pool's roles.
///      - The swap hook (`hooks().hook`: `IPairHook`, `IRecenterHook`) prices every pair but a pair hook's; a pair hook
///        (the `setPairHook` slot) prices its own pairs; the controller (`hooks().controller`) holds a routing role.
///      - A PropAMM front (`IPropAMMFront`) is the swap hook of a pool with a cheap lane, for the pool's life, and
///        settles fills through `IFLAMMLane`. The doors in `src/periphery/door` take routers' fills to the front.
///
///      Terms:
///      - Hook pair: tokens 0 and 1, {asset} and {loanAsset}.
///      - Credit pair: a debt token borrowed against a collateral token at venues ({PairConfig}, `IMMRouter`).
///      - Cheap lane: a fill the front prices and the pool settles from tracked custody, never touching the lender
///        (`IFLAMMLane`), on a pool whose front opened it at birth and whose curator set `FEATURE_CHEAP_FILL`. A pool's
///        cheap lane is on from that birth for good (`SWAP_LANE`), whatever `FEATURE_CHEAP_FILL` says; that bit opens
///        and stops its fills.
///      - Credit path: the pool's own {swap} through the swap hook.
///      - The four legs of a token ({position}): held (custody, unlent), supplied (lent at a venue), posted (collateral
///        at a venue) and owed (borrowed from a venue).
///      - Curator: the owner of `core()`, the role `src/propamm` and `src/periphery/door` call the operator.
///      - Guardian: `core()`'s second key, which cancels scheduled changes, tightens settings and calls the emergency
///        path (`FLAMM`).
///      - Keeper: `core()`'s operations key, which moves dials and runs maintenance beside the curator (`FLAMM`).
///      - D: `governanceDelaySec`, the pool's delay, written once at birth ({switches}).
///      - `EverlongHook`: the canonical swap hook, bound to one pool, which carries the Everlong curve and the pool's
///        leverage quote.
///      - Venue fence and price fence are unrelated: core's fence sets a venue or a token's custody apart from the pool
///        (`IFLAMMFence`); the front's price fence holds a fill's levels within a one-sided limit taken from the price
///        its listing is fenced to, where the listing has one (`IPropAMMFront`).
interface IFLAMM is IERC20 {
    /// @notice The custody maintenance moves. DO NOT REORDER: the values are part of the ABI; a new member needs a
    ///         branch in `FLAMMMaintainLib.maintain`.
    enum MaintainKind {
        TopUp,
        Release,
        Refinance,
        MigrateSupply,
        /// `Refinance` with the caller lending what custody cannot bridge: the caller needs an allowance to the pool
        /// for this transaction, for at most the move, and is repaid in full in it (`FLAMMMaintainLib.maintain`).
        FundedRefinance
    }

    /// @notice The emergency path's moves. DO NOT REORDER: the values are part of the ABI; a new member needs a
    ///         branch in `FLAMMMaintainLib.emergency`.
    enum EmergencyKind {
        Repay,
        /// At a fenced venue the post is the curator's alone and pulls part of it from the caller in the venue's
        /// collateral token, within the caller's allowance to the pool (`FLAMMMaintainLib.emergency`).
        TopUp,
        WithdrawSupplied,
        WithdrawCollateral
    }

    /// @dev The pool's hooks: the swap hook, one contract in every pricing role (it prices every pair but a pair
    ///      hook's, and its own fee, and recenters the pool book it prices), and the optional controller.
    struct HookSet {
        address hook; // the swap hook (`IPairHook`), which prices every pair but a pair hook's
        address controller; // routing role (`setPriorities`, `maintain`, `recenter`, `unwindFence`); zero: none
    }

    /// @notice A venue of credit pair `pair` (the Router's pair index), as `FLAMM.addVenue` admits it.
    struct VenueInit {
        uint8 kind; // the venue kind, one lender
        uint8 pair; // the Router's pair index
        bytes venueParams; // the kind's parameters (`IMMRouter.addVenue`)
        bool borrowEnabled; // the venue's borrow switch
        bool supplyEnabled; // the venue's supply switch
        uint128 debtCap; // the venue's debt cap, debt-token base units; zero: none
        uint128 supplyCap; // the venue's supply cap, debt-token base units; zero: none
        uint64 maxBorrowRateWad; // the highest borrow rate a borrow there may leave, per second, WAD; zero: none
    }

    /// @notice One venue's leg of a pro-rata flow, in the venue's own tokens: `collateral` of its pair's collateral
    ///         token, `owed` and `supplied` of its debt token.
    struct VenueLeg {
        uint16 id; // the venue's slot at the Router
        uint8 pair; // its credit pair's index
        uint256 collateral; // base units
        uint256 owed; // base units
        uint256 supplied; // base units
    }

    /// @notice One listed token: its binding, its swap policy, its lending policy and its custody. `partner` is the
    ///         token whose collateral backs a debt in this one, the collateral of the credit pair `pairId` that owes
    ///         it (`255`: no live pair owes it; `254`: two or more do, `pairId` the first of them); `debtFree` its
    ///         proven debt-free flag. `pairId` means something only while `partner` is not `255`: it reads zero for a
    ///         token no pair ever owed, and keeps the retired pair's index after `FLAMMAdmitLib.retirePair`.
    struct TokenConfig {
        address token; // the token's address
        uint8 decimals; // at most 18
        uint64 swapPriceBandWad; // how far a fill may stray from the feed, WAD; token 1's is the market band
        uint64 feeFloorWad; // the least fee rate a swap of this token takes, WAD
        uint256 maxSwapNotional; // the most of it one swap takes or pays, base units; zero: none
        uint256 reserveTarget; // the custody a swap keeps unlent and a refill brings back, base units
        uint256 minSupplyBatch; // the least surplus over the target a swap lends, base units; `max`: it lends none
        uint256 held; // the custody tracked, the fee kept for the protocol included, base units
        uint8 partner; // see above
        uint8 pairId; // see above
        bool debtFree; // a position read showed no unfenced venue lending it to the pool; a draw clears it
    }

    /// @notice One credit pair, which borrows `debt` against `coll`: its two dials (the LTV, which is the Router's pin,
    ///         and the credit `phiWad` of incoming collateral when a borrow's room is sized), the room's shave, the
    ///         dials' write-once envelope, step, structural floor and cooldown, its last dial move, the pool's mirror
    ///         of its borrow switch and whether it is live (not retired). The credit is at most `1 / (1 + band)` of the
    ///         pair's tokens' tighter swap band, as a fill inside the band may bring an input worth as little as that
    ///         share of its output: the admission caps the dial there, a dial move inside the envelope stores at most
    ///         that as the band stands (never below the envelope's floor), and a draw's or a rotation's room credits no
    ///         more however the band moves since.
    struct PairConfig {
        uint8 coll; // the collateral token's index
        uint8 debt; // the debt token's index
        uint64 ltvWad; // the LTV dial, the Router's pin, WAD
        uint64 phiWad; // the credit dial, WAD
        uint64 roomEpsilonWad; // the share taken off the room once the credit has lifted it, WAD
        uint64 ltvMinWad; // the LTV dial's floor, WAD, write-once
        uint64 ltvMaxWad; // the LTV dial's ceiling, WAD, write-once
        uint64 phiMinWad; // the credit dial's floor, WAD, write-once
        uint64 phiMaxWad; // the credit dial's ceiling, WAD, write-once
        uint64 ltvMaxStepWad; // the most one raise moves the LTV dial, WAD
        uint64 minStructDistWad; // the least `1 - ltv / lltv` a raise of the LTV leaves, WAD
        uint32 ltvCooldownSec; // the seconds a dial move waits after the last one
        uint48 lastDialMoveTs; // when the dials last moved, unix seconds; the pair's admission counts as a move
        bool borrowOff; // the pool's mirror of the Router's borrow switch for the pair: true when it is off
        bool live; // false once retired, for good
    }

    /// @notice The pool's caps, guards and fee policy in one read.
    struct Limits {
        uint32 maxPriceAgeSec; // the oldest USD print a swap past the hook pair prices on, seconds; zero: none trades
        uint64 feeFloorWad; // the pool's fee floor, WAD; a swap takes the highest of this and its two tokens'
        uint64 feeCapWad; // the highest fee rate (`feeWad`) a hook's fill may report, WAD; not a bound on its `feeOut`
        /// @dev The curator's rate, charged on the gain over the high-water mark at the pre-mint share price, in
        ///      minted shares, so the receiver realises bp of the gain diluted by the mint; the rest stays with LPs,
        ///      never recharged. A rise waits `governanceDelaySec`, and none lands while the pool has no market band; a
        ///      cut applies at once.
        uint16 performanceFeeBp;
        /// @dev The high-water mark of the unrealised NAV per share (pool-asset base units per share, WAD), rounded
        ///      down from the pool's own fee mark, which it carries at 18 decimals of par whatever the pool asset.
        ///      Seeded at bootstrap and only ever raised, also while both rates are 0, so a fee armed later starts from
        ///      it. A charged gain is never refunded. On a pool whose cheap lane is on and whose deposit basket is set
        ///      (`basketTokens()`, every token's entry), it is instead the high-water mark of NAV per share against the
        ///      basket's value at the same prices, a WAD ratio (the pool carries it times the share scale, as it
        ///      carries every fee mark): each record of the basket restarts it at 1e18, and only gains above it raise
        ///      it.
        uint128 peakSharePriceWad;
        uint16 maxPerformanceFeeBp; // the curator rate's cap, bp, write-once
        /// @dev The protocol's rate, charged on the same gain beside the curator's, in shares minted to the Factory's
        ///      `protocolFeeReceiver`; the Factory sets it, a rise after the longer of its `UPGRADE_DELAY` and ten days
        ///      and, once the pool is seeded, only while it has a market band.
        uint16 protocolFeeBp;
        /// @dev The curator's scheduled rise and when anyone may execute it (`executePerformanceFee`); zero when none.
        uint16 pendingPerformanceFeeBp;
        uint48 performanceFeeExecutableAt; // unix seconds
        /// @dev The supply `FLAMM.mintProRata` may lift the pool to, in shares (zero closes that entry).
        uint256 mintProRataCap;
    }

    // identity
    /// @notice Token 0: the pool asset, the share and NAV unit.
    function asset() external view returns (address);
    /// @notice Token 1: the numeraire and the token every periphery binding uses.
    function loanAsset() external view returns (address);
    /// @notice The tokens the pool lists, the pool asset included.
    function tokenCount() external view returns (uint256);
    /// @notice The credit pairs the pool holds, retired ones included.
    function pairCount() external view returns (uint256);
    /// @notice Token `t`'s record ({TokenConfig}); reverts `BadTokenIndex` past the list.
    function tokenConfig(uint8 t) external view returns (TokenConfig memory);
    /// @notice Pair `p`'s record ({PairConfig}); reverts `BadPairIndex` past the list.
    function pairConfig(uint8 p) external view returns (PairConfig memory);
    /// @notice Token `t`'s collateral reserve rule (`FLAMMPolicyLib.setCollateralReserve`); `BadTokenIndex` past the list.
    /// @param t The token's index.
    /// @return venueId The venue the rule names, zero while it is off.
    /// @return reserve The custody a release refills up to, in token `t`'s base units, zero while the rule is off.
    function collateralReserve(uint8 t) external view returns (uint16 venueId, uint128 reserve);
    /// @notice When the pending table's entry `h` may execute, `h` being the keccak256 of the scheduled call (its
    ///         selector and arguments abi-encoded as one tuple): an admission (`FLAMM.addToken`, `addPair`,
    ///         `addVenue`), a fence's delayed call (`writeOff`, `abandonFence`, `liftFence`, `liftToken`), the pair
    ///         hook's installation, a fee floor's cut (`setFeeBounds`, `setTokenConfig`) on a pool whose cheap lane is
    ///         off, and a cap's raise on one whose lane is on. Zero when none, as once its window has lapsed
    ///         (past `dueAt` by `governanceDelaySec` or one day, whichever is longer): the identical call then schedules it again.
    function pending(bytes32 h) external view returns (uint48 dueAt);
    /// @notice The money-market Router (`IMMRouter`) that holds the pool's venues.
    function router() external view returns (address);
    /// @notice The USD price feed (`IPriceFeed`).
    function priceFeed() external view returns (address);
    /// @notice The pool's roles (`IEverlongCore`): its curator, guardian, keeper and fee receiver.
    function core() external view returns (address);
    /// @notice The allowlist that decides who may receive an entry's shares (`IDepositAllowlist`); zero: anyone.
    function depositAllowlist() external view returns (address);
    /// @notice The Factory, the pool's beacon.
    function factory() external view returns (address);
    /// @notice The pool's hooks ({HookSet}).
    function hooks() external view returns (HookSet memory);
    /// @notice Whether the pool is paused (`FLAMM.setPaused`).
    function paused() external view returns (bool);

    // facts
    /// @notice Token `t`'s four legs, as the Router's `book` recognizes them (a retired venue holds none, and a fenced
    ///         one's stay out of that `book`); reverts `BadTokenIndex` past the list.
    /// @dev `held` is less than {tokenConfig}'s `held` by the fee kept for the protocol, which that record counts.
    /// @param t The token's index.
    /// @return held The custody the pool owns, the fee kept for the protocol left out, in base units.
    /// @return supplied What the pool lends at its venues, in base units.
    /// @return posted What the pool posts as collateral at its venues, in base units.
    /// @return owed What the pool owes at its venues, in base units.
    function position(uint8 t) external view returns (uint256 held, uint256 supplied, uint256 posted, uint256 owed);
    /// @notice NAV in pool-asset base units at the pool's checked prices: every token's held, supplied and posted legs
    ///         less its owed one, the pool asset at par and every other token at its checked price, holdings rounded
    ///         down and debt up, never below zero.
    /// @dev Reverts:
    ///      - `PriceUnchecked` while a token with a position has an unchecked feed.
    ///      - `PriceUnchecked`, while a fee rate is on and the pool has a band, while the fee mark cannot read, held or
    ///        not: a cheap-lane pool's deposit basket needs token 1's price, and a pending record of what exits
    ///        forfeited at frozen venue marks needs its tokens' prices (so nothing priced at NAV trades a fee the skim
    ///        could not charge).
    ///      - `VenueFrozen` while a live venue holding a position allows no action, its kind one that can refuse one
    ///        (`CAP_ACTION_GATES`): such a kind answers a frozen venue mark while its protocol cannot be read
    ///        (`IFinancingAccount`). A lender that refuses every action while still readable reads the same way, which
    ///        is conservative. No flow enters at its figures (`VenueFrozen`), and an exit forfeits its slice of such a
    ///        venue that owes nothing ({redeemProRata}), which no skim counts as performance.
    function totalAssets() external view returns (uint256);
    /// @notice The pool-wide policy ({Limits}); per-token and per-pair policy live on {tokenConfig} and {pairConfig}.
    function limits() external view returns (Limits memory);
    /// @notice A cheap-lane pool's deposit basket per 1e18 shares: its first two entries, the pool asset's net legs and
    ///         token 1's (`FLAMMFloatLib.basket`); zero on any other pool. A basket holds every token's entry
    ///         ({basketTokens}), against whose whole value `Limits.peakSharePriceWad` is NAV per share.
    /// @return basketPool The pool asset's entry, in its base units.
    /// @return basketLoan Token 1's entry, in its base units.
    function basket() external view returns (uint128 basketPool, uint128 basketLoan);
    /// @notice A cheap-lane pool's deposit basket per 1e18 shares, one entry per listed token in its base units
    ///         (`FLAMMFloatLib.basketTokens`): where it is set, `Limits.peakSharePriceWad` is NAV per share against the
    ///         value of every entry; all zero on any other pool.
    function basketTokens() external view returns (uint256[] memory entries);
    /// @notice The venue slots the pool's walks skip, bit `i` for slot `i`: those it has retired, cleared when an
    ///         admission reuses the slot, and those it has fenced, cleared at the fence's lift (`IFLAMMFence`, whose
    ///         `fencedVenues` tells the fenced apart). No walk of the pool's venues calls the Router for one, as a
    ///         retired venue's lender may have stopped answering and a fenced one's takes no leg.
    function retiredVenues() external view returns (uint256);

    // ERC-4626 conversions at NAV, excluding fees as ERC-4626 asks: at the supply before a pending performance fee is
    // minted, which the pro-rata previews include. No synchronous ERC-4626 path: the pro-rata flows below are the entry
    // and exit. Both revert as `totalAssets` does: at an unchecked price or, while a fee rate and a band are on, an
    // unread fee mark (`PriceUnchecked`), and at a frozen venue mark (`VenueFrozen`).
    /// @notice The shares `assets` of the pool asset buy at NAV, rounded down.
    function convertToShares(uint256 assets) external view returns (uint256);
    /// @notice The pool-asset base units `shares` are worth at NAV, rounded down.
    function convertToAssets(uint256 shares) external view returns (uint256);

    // proportional flows: no hook or callback runs on an entry, an exit or a redemption
    /// @notice A pro-rata entry sized in the pool asset: exactly `poolAssets` of it, for that share of the pool asset
    ///         the pool holds, posts and lends, and the same share of every other token's legs, each netted per token:
    ///         `maxLoanAssetIn` and `minLoanAssetOut` bound tokens 1 onwards, and the entry returns token 1's net in
    ///         and out.
    /// @dev Reverts `BookOwesPoolAsset` while the pool owes its pool asset: such a pool book enters through
    ///      `mintProRata`.
    ///
    ///      Either entry refuses, as its preview does and its maximum reads zero:
    ///      - `CustodyMismatch` while a spread fee is owed past custody, which no call of the pool's leaves (a guard):
    ///        no venue draws it, so the entrant's slice would come out of the custody kept for it. The next inflow of
    ///        the token covers it again; where the token is owed, its debt takes that inflow first, so the entries stay
    ///        closed until the debt is repaid (with strict mode on, a cheap-lane pool's asks wait for that too).
    ///      - `BasketNotRecorded` on a pool whose cheap lane is on and whose curator's fee cap is nonzero, until the
    ///        curator's seed of token 1 records the deposit basket (`seedLeg`), the one basket the fee mark is measured
    ///        against.
    ///
    ///      Either entry also refuses `PriceUnchecked` while a fee rate is on, the pool has a band and the fee mark
    ///      cannot read ({totalAssets}: a cheap-lane pool's basket needs token 1's price, a pending forfeit record its
    ///      tokens' prices, held or not), as its skim would charge nothing and the next one the gain on the entrant's
    ///      shares too; its maximum reads zero there.
    ///
    ///      On a pool book that owes:
    ///      - A borrow leg refuses before the entry pulls anything (`PriceUnchecked` where its pair's price is
    ///        unchecked, `PegBroken` where one of its tokens is off its peg).
    ///      - The entry gate, the credit law read once the legs have moved, refuses `PriceUnchecked` where a debt its
    ///        token's holdings and supply do not cover has no checked price against its collateral, as a dust debt
    ///        whose slice is no borrow leg can: the maximum reads zero there, and an entrant short of its inputs meets
    ///        its own pull's error first.
    ///
    ///      Refused also `Expired`, `Paused`, `FeatureDisabled` with `FEATURE_DEPOSITS` off, `VenueFrozen` while a
    ///      fence holds a pool part, `DepositNotPermitted` for a receiver the allowlist refuses, `NotBootstrapped`,
    ///      `ZeroShares` and `Slippage`; a leg past its bound reverts `TokenInExceeded` or `TokenOutBelowMin`.
    /// @param poolAssets The pool asset paid in, in its base units, above zero (`InvalidAmount`).
    /// @param receiver The receiver of the shares; net outputs go to the caller.
    /// @param maxLoanAssetIn The most of each token paid in, token 1 first, `tokenCount - 1` long (`InvalidAmount`).
    /// @param minLoanAssetOut The least of each token paid out, token 1 first, `tokenCount - 1` long (`InvalidAmount`).
    /// @param minSharesOut The least shares minted.
    /// @param deadline The last unix second it executes.
    /// @return shares The shares minted, rounded down.
    /// @return loanAssetIn Token 1's net input, in its base units.
    /// @return loanAssetOut Token 1's net output, in its base units.
    function depositProRata(
        uint256 poolAssets,
        address receiver,
        uint256[] calldata maxLoanAssetIn,
        uint256[] calldata minLoanAssetOut,
        uint256 minSharesOut,
        uint256 deadline
    ) external returns (uint256 shares, uint256 loanAssetIn, uint256 loanAssetOut);
    /// @notice A pro-rata entry sized in shares, on any pool book: exactly `shares`, for that slice of every token's
    ///         legs, its holdings paid in rounded up and its debt borrowed for the entrant rounded down, netted per
    ///         token. The arrays are `tokenCount` long, token 0 first.
    /// @dev Either entry refuses, and the entry maxima read 0 there:
    ///      - `IMMRouter.Unhealthy` where its borrow leg would leave a venue past its pin in the collateral the pool
    ///        recognizes, as its preview does.
    ///      - `VenueFrozen` at a frozen venue mark ({totalAssets}), whose figures are no price to enter at and whose
    ///        thaw's first skim would charge the entrant for gains made before it entered.
    ///      - `PriceUnchecked` while a fee rate is on, the pool has a band and the fee mark cannot read, as
    ///        `depositProRata` does.
    ///
    ///      `mintProRata` also refuses:
    ///      - Under the same rates and band, `PriceUnchecked` where the share price is past the fee mark's range
    ///        (`type(uint128).max` at 18 decimals of par).
    ///      - An unchecked price or a broken peg at its borrow legs and its entry gate, as `depositProRata`'s do.
    ///      - `DepositCapExceeded` past `Limits.mintProRataCap` on the supply after it.
    ///      - `Expired`, `Paused`, `FeatureDisabled`, `DepositNotPermitted` and `NotBootstrapped` as `depositProRata`.
    ///      - `TokenInExceeded` or `TokenOutBelowMin` for a leg past its bound.
    /// @param shares The shares to mint, above zero (`InvalidAmount`).
    /// @param receiver The receiver of the shares; net outputs go to the caller.
    /// @param maxIn The most of each token paid in, in its base units.
    /// @param minOut The least of each token paid out, in its base units.
    /// @param deadline The last unix second it executes.
    /// @return tokenIn Each token's net input, in its base units, token 0 first.
    /// @return tokenOut Each token's net output, in its base units, token 0 first.
    function mintProRata(
        uint256 shares,
        address receiver,
        uint256[] calldata maxIn,
        uint256[] calldata minOut,
        uint256 deadline
    ) external returns (uint256[] memory tokenIn, uint256[] memory tokenOut);
    /// @notice A pro-rata exit, price-free and never paused: `shares` of `owner`'s for that slice of every token's
    ///         legs, its debt repaid by the caller rounded up and its holdings paid to `receiver` rounded down, netted
    ///         per token. The arrays are `tokenCount` long, token 0 first. A caller other than `owner` spends its
    ///         allowance. Refused also, past the cases below, `Expired`, `BelowMinimumShares` where the supply left
    ///         would pass under the dead shares, `TokenInExceeded` and `TokenOutBelowMin` past the bounds, and
    ///         `ExitWorsensLedger`.
    /// @dev A venue that takes less of its repay than asked (a minimum position, a lender's remainder past its market's
    ///      total borrows):
    ///      - It releases in proportion to what it took. The rest of the repay nets its debt in custody, which pays the
    ///        slice the venue keeps posted, or the exit refuses (`CustodyMismatch`) past the dust any exit can leave
    ///        where custody runs dry.
    ///      - That dust is the venue's last whole units, bounded at the larger of its pair's safety gap and 1 %, the
    ///        lenders' rounding and a share under one unit's assets and one, which it releases none of. It stays
    ///        posted, `minOut` bounds it and the fee mark counts it as forfeited.
    ///      - A repay that leaves the venue owing nothing holds nothing.
    ///      - The preview reads no such hold, so it can show an exit this refuses.
    ///      - The exit maximum reads the holds a kind reports (a minimum position, `IHeldRepay`; a lender's bound,
    ///        `IRepayable`, one per market, spent across the venues borrowing there in the exit's order), so no exit it
    ///        advertises refuses for one. At a venue past its threshold whose lender holds the repay of its whole debt
    ///        short, the remainder can keep the release in proportion past what the lender allows, and the maximum
    ///        reads zero.
    ///      - An exit the maximum advertises may pay short of its preview by the dust a held venue leaves: floors taken
    ///        from the preview, less that dust, hold.
    ///
    ///      Dust at a venue that still owes:
    ///      - It releases nothing under one unit's assets and one, which its kind would release by burning a whole
    ///        unit: a slice that small stays posted with the venue's last whole units, recorded as dust, whether or not
    ///        the venue held the repay.
    ///      - Where the venue held the repay, a share under one unit's assets and one of a larger slice releases none,
    ///        and custody pays that slice, what it cannot of that share staying posted beside the dust.
    ///
    ///      At a venue whose threshold equals its pair's LTV, which reads unhealthy once interest accrues, the maximum
    ///      reads zero below the size that clears the venue, though smaller exits may execute.
    ///
    ///      Haircuts: a slice at a venue whose lender cannot pay all of its face (`IFinancingAccount.haircut`) is paid
    ///      cut by that share, which stays in custody, so the exiter bears its share of the venue's loss, as NAV does,
    ///      and the holders who stay none of it. Where the haircut is a fee each redemption pays
    ///      (`CAP_REDEMPTION_FEE`), the slice leaves net of it instead, so the venue burns the exiter's units and no
    ///      more. This holds for a loss the venue's kind reports; the comptroller kind (`CTokenAccount`) reports only
    ///      its lender's redemption fee, as that lender records no bad debt, so there a slice leaves at face and the
    ///      holders who stay bear the exiter's share of a bad debt the lender has not covered.
    ///
    ///      At a frozen venue mark (a venue that allows no action and holds a position):
    ///      - The exit forfeits its slice of such a venue that owes nothing, or no more than the lenders' rounding
    ///        (`MMRouterLib.RELEASE_SLACK`, whose share it leaves behind), which stays posted for the holders who
    ///        remain.
    ///      - It refuses (`VenueFrozen`) where one owes more, as its debt slice cannot be repaid there.
    ///      - Its preview shows the smaller payout, and `minOut` bounds it.
    ///      - A forfeit is never performance: the pool records it, and the first skim that reads the fee mark again
    ///        raises the fee mark by its value per share before it charges either rate.
    ///
    ///      The collateral an exit leaves where the venue still owes after it, and a release in the kind's whole units
    ///      could take it past its threshold, is treated as a forfeit too:
    ///      - The slice is cut to keep that floor posted, bounded as the held dust is (one unit's assets and one times
    ///        `lltv / max(lltv - ltv, gap, 1 %)`), and by up to one unit's assets more where the venue holds less than
    ///        that floor and a unit, as a slice under one unit's assets and one stays posted whole
    ///        (`FLAMMGateLib.nearUnitsAt`). Only what it leaves is forfeited.
    ///      - Where that much posted would leave the venue past its threshold, its lender refuses the release and the
    ///        exit with it.
    ///      - No move of the pool's own (a dial move, `setDials`; an admission with borrowing on or a switch-on) leaves
    ///        a pin within that gap under its threshold.
    ///
    ///      A collateral slice a venue cannot release now is paid from the custody the pool owns, never the custody
    ///      kept for the protocol's spread fee: past it the exit refuses (`CustodyMismatch`).
    /// @param shares The shares to burn, above zero and at most `owner`'s (`InvalidAmount`).
    /// @param receiver The receiver of the holdings, neither zero nor the pool (`InvalidAmount`), who also takes the
    ///        shares' claims on a fence's part.
    /// @param owner The holder of the shares.
    /// @param maxIn The most of each token the caller repays, in its base units.
    /// @param minOut The least of each token paid out, in its base units.
    /// @param deadline The last unix second it executes.
    /// @return tokenIn Each token's net repay, in its base units, token 0 first.
    /// @return tokenOut Each token's net output, in its base units, token 0 first.
    function redeemProRata(
        uint256 shares,
        address receiver,
        address owner,
        uint256[] calldata maxIn,
        uint256[] calldata minOut,
        uint256 deadline
    ) external returns (uint256[] memory tokenIn, uint256[] memory tokenOut);
    /// @notice The legs and net amounts {depositProRata} of `poolAssets` would take now.
    /// @dev The previews price at the supply after the performance fee the flow crystallizes first, both parts. Each
    ///      quotes the legs, not whether the flow executes, but an entry's refuses (`IMMRouter.Unhealthy`) where a
    ///      borrow leg would leave its venue past its pin in the collateral the pool recognizes, and an exit's where a
    ///      frozen venue owes more than the lenders' rounding (`VenueFrozen`), as the flow does; an exit's legs carry
    ///      the flow's haircut cut and forfeit its slice of a frozen venue that owes no more. An exit's reads no hold
    ///      of its repay at a venue that takes it short, so the exit can refuse (`CustodyMismatch`) where custody
    ///      cannot pay the slice that venue keeps posted, or pay short of it by the dust (`redeemProRata`). `tokenIn`
    ///      and `tokenOut` are per token, token 0 first.
    /// @param poolAssets The pool asset paid in, in its base units.
    /// @return shares The shares it would mint.
    /// @return legs The flow's venue legs.
    /// @return tokenIn Each token's net input, in its base units.
    /// @return tokenOut Each token's net output, in its base units.
    function previewDepositProRata(uint256 poolAssets)
        external
        view
        returns (uint256 shares, VenueLeg[] memory legs, uint256[] memory tokenIn, uint256[] memory tokenOut);
    /// @notice The legs and net amounts {mintProRata} of `shares` would take now, as {previewDepositProRata}.
    /// @param shares The shares to mint.
    /// @return legs The flow's venue legs.
    /// @return tokenIn Each token's net input, in its base units.
    /// @return tokenOut Each token's net output, in its base units.
    function previewMintProRata(uint256 shares)
        external
        view
        returns (VenueLeg[] memory legs, uint256[] memory tokenIn, uint256[] memory tokenOut);
    /// @notice The legs and net amounts {redeemProRata} of `shares` would take now, as {previewDepositProRata}.
    /// @param shares The shares to burn.
    /// @return legs The flow's venue legs.
    /// @return tokenIn Each token's net repay, in its base units.
    /// @return tokenOut Each token's net output, in its base units.
    function previewRedeemProRata(uint256 shares)
        external
        view
        returns (VenueLeg[] memory legs, uint256[] memory tokenIn, uint256[] memory tokenOut);

    // swap
    /// @notice Exact input, any two listed tokens, the pool asset included: the hook that prices the pair (the swap
    ///         hook, or a pair hook on its pairs) prices the fill (`IPairHook.fillPair`), and core checks it (its fee
    ///         inside the bounds, its input, the caller's minimum, the ceiling the credit law and the notional caps
    ///         leave, the tighter band of the two tokens around their USD prices) and settles it through the Router:
    ///         the input repays what the pool owes of it first, the output pays from custody, collateral, one rotation
    ///         or a draw on its pair, the input's surplus is lent, and the credit law holds after. It runs no
    ///         observation.
    /// @dev It runs only for a pair in both trade masks (a hook prices it and the curator lets it trade,
    ///      `FLAMM.tradablePairs`; `PairNotTradable` otherwise), a sale of the pool asset under `FEATURE_SWAP_SELL` and
    ///      a buy of it under `FEATURE_SWAP_BUY` (`FeatureDisabled`); a pair past the hook pair needs both its USD
    ///      prints within `maxPriceAgeSec` (`StalePair`).
    ///
    ///      Refused also:
    ///      - `InvalidPair`: a token not listed, or one token twice.
    ///      - `Paused`: `FLAMM.setPaused` says which swaps run paused.
    ///      - `PriceUnchecked`: a pair with no checked price, or an owing pool with no band.
    ///      - `PegBroken`: a draw with a token off its peg.
    ///      - `RoomExhausted`: no room for an output some live pair owes, the input owing nothing.
    ///      - `CreditPathOff`: a pair a cheap-lane pool's front prices while its credit path is off.
    ///      - Past core's checks of the fill, `FeeOutOfBounds`, `FillInvalid`, `OutputAboveCeiling` and `PriceBand`.
    ///      - `InputUnused`: a fill of less than `amountIn` where the input was found (below).
    ///
    ///      The input is found or pulled at the settling step, after the fill is checked and before any venue moves
    ///      or anything is paid:
    ///      - Found: where the pool holds the whole `amountIn` past its tracked custody, nothing is pulled and exactly
    ///        `amountIn` is credited, and a fill of less reverts `InputUnused`. Input sent first therefore fills whole
    ///        or comes back with the revert. A found fill makes no call that moves the input, unless a venue takes it
    ///        in that fill (a repay, a post or a lend), so it fills where that token's transfers are paused or refuse
    ///        the caller, up to what lay past custody. That balance is read only while the pool's balance is at least
    ///        its tracked custody: under it the pull runs and custody refuses the fill (`CustodyMismatch`), except on
    ///        the full path (any fill past the custody-only branch) within what custody keeps of the fee in token 0 or
    ///        1 and, on a payout, the fill's part and share, which the reconcile does not read: there the swap fills
    ///        and the shortfall stays.
    ///      - Pulled: otherwise the pool pulls what the fill uses from the caller, and a fill of less keeps the rest
    ///        with the caller. A short delivery reverts `CustodyMismatch`.
    ///      - Any untracked `tokenIn` counts toward that test: a donation, an overpayment, a payment left by an
    ///        earlier transaction. The next caller it covers spends it, with no pull, and any allowance that caller
    ///        gave the pool stands; only what lies past `amountIn` stays untracked.
    ///      - A payer sends and calls in one transaction with no call between, and holds no allowance to the pool. A
    ///        send short of `amountIn` is left in the pool and the pull runs.
    ///      - What a payer leaves behind it can swap away itself at the pool's price only where the pair is open and
    ///        this entry runs: not on a custody-blind pool, nor, with the credit path off, on a pair the front prices.
    ///        A stray of the pool asset has no lift: it stays until a swap or a paid fill spends it.
    ///      - On a fee-on-transfer token a payer that declares what arrived fills where no venue moves the token; a
    ///        repay or a post of its cut reverts. One that declares the gross amount falls to the pull, unless
    ///        untracked balance covers the fee, which the swap then spends.
    ///      - A pool must not list two addresses of one ledger: each leg's custody reads as past the other's tracked
    ///        custody, so a fill found there is paid from the pool's own custody.
    ///      - A send sized by `previewSwap` takes the preview from the calling address, and it can still clip: its
    ///        `amountInUsed` may fill less when executed, and a found fill of less reverts.
    ///
    ///      The pool's `Swap` event reports the fill: the tokens' indices, the native amounts and fee, and the hook's
    ///      fee rate, spot after, gross output, coordinate after and the protocol's part of the fee, with
    ///      `amountInUsed` equal to `amountIn` on a found fill. Its `sender` is the caller, which need not be the
    ///      account that paid. From the swap `EverlongHook` emits `Levered` on a leverage fill and nothing on a curve
    ///      fill.
    ///
    ///      A swap that would draw at a pair with a venue that borrows, or rotate from a pair, where a venue reports a
    ///      loss of 1 bp or more on its collateral (`FLAMMKeptLib.lossAtFloor`), or takes a redemption fee of any size
    ///      on it, reverts `VenueReportsLoss`; the quote reverts the same, on the same check, where its plan draws or
    ///      rotates (it reads the releases the Router reports, so a venue that releases less than it reports can leave
    ///      the swap at a draw the quote did not see). A payout the pair's supply would pay is refused too, and a pair
    ///      whose only venue that borrows stands under a fee draws nothing until the fee ends.
    ///      The operator or the guardian ends it at once by switching that venue's borrowing off, or the pair's;
    ///      switching it back on waits the pool's delay where the cheap lane is on.
    ///
    ///      The selector is shared with another swap standard, but this returns two words and has none of its views.
    /// @param tokenIn The token paid in, found at the pool or pulled from the caller.
    /// @param tokenOut The token paid out.
    /// @param amountIn The most to pay in, in `tokenIn` base units, above zero (`InvalidAmount`): all of it where the
    ///        input is found.
    /// @param minAmountOut The least net output, in `tokenOut` base units (`Slippage`).
    /// @param to The receiver of the output, neither zero nor the pool (`InvalidAmount`).
    /// @param deadline The last unix second it executes (`Expired`).
    /// @return amountInUsed The input the hook used, in `tokenIn` base units, at most `amountIn`.
    /// @return amountOut The net output paid to `to`, in `tokenOut` base units.
    function swap(address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut, address to, uint256 deadline)
        external
        returns (uint256 amountInUsed, uint256 amountOut);
    /// @notice Quotes a swap of `amountIn` of `tokenIn` for `tokenOut` on the pool book as it stands: the swap's own
    ///         branch, plan and checks, the hook's quote of the swap's request (`IPairHook.quotePair`), re-asked at the
    ///         input it used, rounded to native units, so a swap of the quoted input, the quoted output its minimum,
    ///         fills the quote. A payout that draws past what the Router can fund for it now reverts as the swap would
    ///         (`IMMRouter.InsufficientLiquidity`), rather than quoting a smaller fill the swap would not make. No swap
    ///         fills under its quote, but at a venue that holds a minimum position a quoted payout can still revert by
    ///         the slice the swap's plan passes over, and a payout the quote refuses can fill (`IFinancingAccount`
    ///         ADMISSION).
    /// @param tokenIn The token paid in.
    /// @param tokenOut The token paid out.
    /// @param amountIn The most to pay in, in `tokenIn` base units.
    /// @return amountInUsed The input the fill uses, in `tokenIn` base units.
    /// @return amountOut The net output, in `tokenOut` base units.
    /// @return feeWad The fill's fee rate, WAD.
    function previewSwap(address tokenIn, address tokenOut, uint256 amountIn)
        external
        view
        returns (uint256 amountInUsed, uint256 amountOut, uint256 feeWad);
    /// @notice The pool context a recenter hands the swap hook now (`PoolContext`): every token's legs through the
    ///         Router and its custody, the rest at their unrounded USD cross, the hook pair's N36 from the feed's pair,
    ///         the band, the listed pairs and the features; a poke hands the same with every leg zero, as it reads no
    ///         pool book. Reverts where the observation could not price: a stale pair, the sequencer, an unchecked
    ///         price it needs. The hook's curve ceremony reads `priceN36` from it as the feed's print
    ///         (`EverlongOpsLib.curveGate`), so a pool that cannot price its observation refuses that ceremony too.
    function hookContext() external view returns (PoolContext memory);
    /// @notice The request a swap of `amountIn` (native units of `tokenIn`) hands the pair's hook now
    ///         (`PairRequest`), on the swap's branch and plan, `sender` the caller. Reverts where the swap
    ///         refuses before its fill: the pause or a feature bit, a payout without room, a payout off peg wherever
    ///         its payout pair may borrow, whatever the backing holds, a price it cannot read, a zero input.
    function pairRequest(address tokenIn, address tokenOut, uint256 amountIn) external view returns (PairRequest memory);

    // lifecycle (factory only)
    /// @notice The pool's first entry, the Factory's alone and once (`AlreadyBootstrapped`): pulls `assets` of the pool
    ///         asset into custody, mints at par, with `FLAMMStore.MINIMUM_SHARES` to a dead address that never burns
    ///         them, and sets the fee mark at par. `InvalidAmount` on a zero `assets` or `to`; `BelowMinimumShares`
    ///         unless the shares pass the dead ones.
    /// @param assets The pool asset, in its base units.
    /// @param to The receiver of the shares past the dead ones.
    /// @return shares The shares minted to `to`.
    function bootstrap(uint256 assets, address to) external returns (uint256 shares);
    /// @notice The protocol's performance fee, at most `FLAMMStore.MAX_PROTOCOL_FEE_BP`; it skims at the old rates
    ///         first, and a rise reverts `PriceUnchecked` while that skim cannot read the fee mark, as on a seeded pool
    ///         with no market band, or while a fence holds a pool part. A nonzero rate on a pool whose cheap lane is on
    ///         reverts `InvalidConfig`. The Factory applies a cut at once and a rise after the longer of its
    ///         `UPGRADE_DELAY` and ten days; no upgrade moves the Factory, so every implementation keeps this entry.
    /// @param feeBp The rate, bp.
    function setProtocolFeeBp(uint16 feeBp) external;
    /// @notice The protocol's rates (`FLAMMFloatLib.setSpreadFeeRates`), one word: in bits 0-15 the spread rate, at
    ///         most `FLAMMFloatLib.MAX_SPREAD_FEE_BP`, the share of a hook's fee the protocol takes in kind, of
    ///         each fill's edge against its fee price (the pull price, or where the listing reads none its desk's
    ///         word's mid) on a pool whose cheap lane is on; in bits 16-31 and 32-47 the notional rates of the pool's
    ///         other pairs and of its correlated pairs (two tokens of one peg group at the Factory), each at most
    ///         `FLAMMFloatLib.MAX_NOTIONAL_RATE`, in `FLAMMStore.NOTIONAL_SCALE` parts of a fill's notional leg, the
    ///         floor of the protocol's part of every hook-priced fill and every cheap fill. The Factory applies a cut
    ///         of a field at once and a rise after the longer of its `UPGRADE_DELAY` and ten days; no upgrade moves
    ///         the Factory, so every implementation keeps this entry.
    /// @param rates The word above.
    function setSpreadFeeRates(uint48 rates) external;

    // code (beacon proxy: the Factory is the beacon; a new implementation must report a higher code version)
    /// @notice The code version of the implementation behind the beacon.
    function poolCodeVersion() external pure returns (uint32);

    /// @notice The feature bitmap (`FLAMMStore.FEATURE_*`) and the governance delay.
    /// @return featureBits The bitmap.
    /// @return delaySec The governance delay, seconds, write-once.
    function switches() external view returns (uint256 featureBits, uint32 delaySec);

    /// @notice The committed ceilings (`FLAMMPolicyLib.setBandAndFeeCeilings`): the widest swap band any token may take and the
    ///         highest fee cap, each set at once under its ceiling, which starts at the widest band of the pool's
    ///         tokens and its cap at birth (a band ceiling of `type(uint64).max` admits no band at all); then the
    ///         scheduled raise, which waits `governanceDelaySec` (one of the band's at least ten days), and when the
    ///         curator may apply it, zero when none.
    /// @return bandWad The band ceiling, WAD.
    /// @return feeCapWad The fee cap's ceiling, WAD.
    /// @return pendingBandWad The scheduled band ceiling, WAD.
    /// @return pendingFeeCapWad The scheduled fee cap ceiling, WAD.
    /// @return executableAt When the raise may apply, unix seconds; zero when none.
    function ceilings()
        external
        view
        returns (uint64 bandWad, uint64 feeCapWad, uint64 pendingBandWad, uint64 pendingFeeCapWad, uint48 executableAt);

    // observation
    /// @notice Forwards the feed's print to the swap hook, which folds it; permissionless and refused while paused
    ///         (`Paused`), and on a pool with no band, which has no print to forward (`NoBand`). A
    ///         swap forwards none: the folds follow the feed as far as pokes and recenters forward it.
    function poke() external;
    /// @notice Forwards the feed's print (none on a pool with no band) to the swap hook's recenter, which may move its
    ///         anchor inside the caller's bounds (`AnchorOutOfBounds` otherwise); refused while paused (`Paused`). The
    ///         keeper, the curator or the controller hook calls it (`NotKeeperOrCurator`), so a recentering rule can
    ///         live in a controller, which only the genesis set or the delayed hook-set ceremony installs.
    /// @param minAnchorN36 The lowest anchor the caller takes, in the hook's N36 price scale.
    /// @param maxAnchorN36 The highest anchor the caller takes, in the same scale, at least `minAnchorN36`
    ///        (`InvalidConfig`).
    /// @param deadline The last unix second it executes (`Expired`).
    function recenter(uint256 minAnchorN36, uint256 maxAnchorN36, uint256 deadline) external;
    /// @notice Crystallizes the performance fee at the current fee mark, minting the curator's part to the core fee
    ///         receiver and the protocol's to the Factory's `protocolFeeReceiver`; permissionless. With both parts
    ///         off it still raises `peakSharePriceWad`, silently.
    function skimPerformanceFee() external;
}

/// @notice What a pool and the lens read of the Factory's protocol fee: the receiver of the protocol's part (never
///         zero on the Factory) and a pool's scheduled rise (`feeBp` zero: none).
interface IFLAMMProtocolFee {
    /// @notice The receiver of the protocol's part of every pool's fees.
    function protocolFeeReceiver() external view returns (address);
    /// @notice `pool`'s scheduled rise of its protocol performance fee.
    /// @param pool The pool.
    /// @return feeBp The scheduled rate, bp; zero: none, or one lapsed.
    /// @return executableAt When it may apply, unix seconds.
    function pendingProtocolFee(address pool) external view returns (uint16 feeBp, uint48 executableAt);
}

src/interfaces/core/flamm/IFLAMMHooks.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

/// @notice The pool state in a hook's observation (`ObservationContext`), which `FLAMMOpsLib.hookContext` also reads, built
///         by core from its custody, the Router's positions and one checked price. A fill's hook gets a `PairRequest`
///         instead. The pool lists tokens `t0, t1, ...`: `t0` is the pool asset (the share and NAV unit, the base),
///         `t1` the numeraire (the quote), the hook pair. Each holds four legs: held (custody, unlent), supplied
///         (lent at a venue), posted (collateral at a venue) and owed (borrowed from a venue). Base
///         fields are `t0` base units; quote fields are `t1` in N18 (its value at 18 decimals); the rest sum every
///         token from `t2` on in N18 at its USD cross with `t1`, holdings rounded down and debt up, leg by leg.
///         `priceN36` is `t1`'s value at 36 decimals per `t0` base unit (N18 scaled by 1e18), so a cheap 18-decimal
///         pool asset keeps its digits; every hook price below is in the same price scale. A pool with no market band
///         hands `priceN36` zero. A poke's observation reads no pool book: it carries the print, the band, the pairs
///         and the features, every leg zero (`IRecenterHook.observe`).
/// @dev Flat, so core copies it into a call in one move. `bookScale` is reserved and zero. `bandWad` is the hook
///      pair's live swap band (zero: none). `pairs` holds the `CONTEXT_PAIR_*` bits of the credit pairs the pool
///      lists; `features` the pool's `FEATURE_*` bits and, on a custody-blind pool, whose swap hook is its front for
///      life, the law's bit past them (`FLAMMStore.CUSTODY_BLIND`).
struct PoolContext {
    uint256 baseHeld; // `t0` held, base units
    uint256 baseSupplied; // `t0` supplied, base units
    uint256 basePosted; // `t0` posted, base units
    uint256 baseOwed; // `t0` owed, base units
    uint256 quoteHeld; // `t1` held, N18
    uint256 quoteSupplied; // `t1` supplied, N18
    uint256 quotePosted; // `t1` posted, N18
    uint256 quoteOwed; // `t1` owed, N18
    uint256 restHeldN18; // the held, supplied and posted legs of every token from `t2` on, N18, rounded down
    uint256 restOwedN18; // the owed legs of every token from `t2` on, N18, rounded up
    uint256 priceN36; // `t1` per `t0` base unit, N36; zero with no market band
    uint256 bookScale; // reserved, zero
    uint64 bandWad; // the hook pair's live swap band, WAD; zero: none
    uint32 pairs; // `CONTEXT_PAIR_*` bits
    uint32 features; // the pool's `FEATURE_*` bits, and `FLAMMStore.CUSTODY_BLIND` past them
}

/// @notice `EverlongHook`'s own form of a fill of the hook pair, which it builds from the pair request
///         (`PairRequest`): the pool context, the side, the input and the ceiling in its units (token 1 in N18), and
///         the pool's fee bounds. Core hands no hook this struct.
struct SwapContext {
    PoolContext pool; // the pool book as the request carries it
    bool poolAssetIn; // the input is the pool asset: the pool buys it
    uint256 amountIn; // `t0` base units where `poolAssetIn`, else `t1` in N18
    uint256 maxAmountOut; // `t1` in N18 where `poolAssetIn`, a ceiling past a word read as none, else `t0` base units
    uint64 feeFloorWad; // the least fee rate, WAD
    uint64 feeCapWad; // the most fee rate, WAD
}

/// @notice `EverlongHook`'s own fill in its units (`t0` in base units, `t1` leg N18): input used, the curve's gross
///         output, the fee kept from it, the fee rate, the spot after the fill and the curve coordinate after it
///         (`xAfter`, WAD). The hook converts it to the pair fill core settles (`PairFill`).
struct FillResult {
    uint256 amountInUsed; // in `SwapContext.amountIn`'s units
    uint256 grossOut; // in `SwapContext.maxAmountOut`'s units
    uint256 feeOut; // in `SwapContext.maxAmountOut`'s units
    uint256 feeWad; // WAD
    uint256 spotAfterN36; // N36
    uint256 xAfter; // WAD
}

/// @notice One checked reference print and its source timestamp. `poke` and `recenter` forward the feed's current
///         print, which may repeat an `observedAt` already forwarded, even with a moved `referenceN36` (a cross carries
///         its older leg's stamp). A hook MUST treat `observedAt` as non-monotonic, clamp its own elapsed-time step and
///         decline a value it has already folded. A swap forwards none: its request carries the two prices, which a
///         hook may fold itself. A recenter's `pool` is the pool book at that print; a poke's carries the hook pair's
///         N36, the band, the pairs and the features with every leg zero, as core reads no pool book for it. A pool
///         with no market band reads no price: its `poke` refuses (`NoBand`), and its recenter hands a zero reference
///         and stamp.
struct ObservationContext {
    PoolContext pool; // the pool book, or the terms beside it, as above
    uint256 referenceN36; // the hook pair's print, `t1` per `t0` base unit, N36
    uint48 observedAt; // the print's source timestamp, unix seconds; the older leg's
}

/// @notice The swap hook's spot, for readers outside the pool: core reads none, as every swap hook only folds on a
///         poke (`HOOK_CAP_FOLD_ONLY`). The swap hook prices its fills and its own fee through `IPairHook`.
interface IInvariantHook {
    /// @notice The hook's marginal price, in `PoolContext.priceN36`'s price scale.
    /// @param ctx The pool state. A hook may ignore it, as `EverlongHook` does.
    /// @return spotN36 The spot, N36. A hook that holds no curve answers zero.
    function spot(PoolContext calldata ctx) external view returns (uint256 spotN36);
}

/// @notice The observation and anchor policy: fold one observation, or fold it and move the anchor. Core runs
///         `observe` on `poke`, and `recenter` on the pool's `recenter` (the keeper's, the curator's or the controller
///         hook's), whose anchor bounds core checks on the anchor the hook returns.
interface IRecenterHook {
    /// @notice Folds the print, moving nothing `spot` reads (`HOOK_CAP_FOLD_ONLY`). Core calls it on `IFLAMM.poke`,
    ///         which anyone may run. A revert reverts the poke.
    /// @param ctx The print, with every leg of its context zero.
    function observe(ObservationContext calldata ctx) external;
    /// @notice Folds the print and moves the anchor where the hook's policy says so. Core calls it on
    ///         `IFLAMM.recenter`.
    /// @param ctx The print and the pool book at it.
    /// @return moved Whether the anchor moved; core checks `anchorN36` only then (`AnchorOutOfBounds`).
    /// @return anchorN36 The anchor after the call, N36.
    function recenter(ObservationContext calldata ctx) external returns (bool moved, uint256 anchorN36);
}

/// @notice A hook's identity, which core checks at installation (`FLAMMOpsLib.checkIdentity`). Every hook must hold
///         code. A hook that prices (the swap hook and a pair hook) must answer both and name its pool; the
///         controller may stay silent, but a nonzero `boundPool` must name the pool and a declared version must match.
interface IHookIdentity {
    /// @notice The hook interface version the hook implements, `HOOK_INTERFACE_VERSION`.
    function hookInterfaceVersion() external view returns (uint16);
    /// @notice The pool the hook serves. A hook shared by many pools answers the pool asking.
    function boundPool() external view returns (address);
}

/// @dev The one hook interface version core accepts (`IHookIdentity.hookInterfaceVersion`).
uint16 constant HOOK_INTERFACE_VERSION = 3;

// `PoolContext.pairs`: the credit pairs the pool lists (live, not retired) and whether each borrows.
/// @dev The forward pair, `t1` borrowed against `t0`, is listed.
uint32 constant CONTEXT_PAIR_FORWARD = 1 << 0;
/// @dev The forward pair's borrowing is on.
uint32 constant CONTEXT_PAIR_FORWARD_BORROWS = 1 << 1;
/// @dev The reverse pair, `t0` borrowed against `t1`, is listed.
uint32 constant CONTEXT_PAIR_REVERSE = 1 << 2;
/// @dev The reverse pair's borrowing is on.
uint32 constant CONTEXT_PAIR_REVERSE_BORROWS = 1 << 3;
/// @dev Another pair that owes `t0` or posts a token other than `t0` is listed.
uint32 constant CONTEXT_PAIR_OTHER = 1 << 4;

src/interfaces/core/flamm/IPairHook.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

/// @notice One exact-input fill request for any two of the pool's tokens, in native units: every pair, the pool asset
///         included, and every mode (cover, borrow, rotation, custody only). Flat, so core writes it into a call in a
///         few moves. `sender` is the swap's caller. `mode` holds the `PAIR_MODE_*` bits of the plan, `features` the
///         pool's `FEATURE_*` bits, `protocolFeeBp` the pool's protocol spread rate (zero where none is set).
///         `IFLAMM.pairRequest` reads the request a swap would send now.
/// @dev Core refuses:
///      - a fill whose `feeWad` is under `feeFloorWad` or over `feeCapWad` (`FeeOutOfBounds`);
///      - one whose net output's value at `usdOut` is outside `bandWad` around the input's value at `usdIn`
///        (`PriceBand`; both prices zero on a pool with no band, which checks none);
///      - one whose `protocolFeeOut` passes `feeOut` or `net * protocolFeeBp / (1e4 - protocolFeeBp)`, where `net` is
///        `grossOut - feeOut` (`FeeOutOfBounds`).
///
///      The amounts:
///      - `amountIn` is at most the input's notional cap.
///      - `maxAmountOut` is core's ceiling for this request, not the pool's depth (where the band's top for the input
///        is under custody it counts the output's supply whole, as no fill the band passes reaches it), less, at a
///        notional rate, the room the protocol's floor needs beside a payout under it: the payout's ceiling times
///        `1e7 / (1e7 + extension)`, rounded down.
///      - Each token's legs are held, supplied, posted and owed, native, as the plan read them.
///      - `restHeldN18` and `restOwedN18` are the USD values (WAD) of every other token's held, supplied and posted
///        legs and of its owed leg, at the feed, so a hook that values the whole pool book (`EverlongHook`'s leverage)
///        sees the tokens outside the pair.
struct PairRequest {
    address sender; // the swap's caller
    address tokenIn; // the token the pool takes
    address tokenOut; // the token the pool pays
    uint8 indexIn; // `tokenIn`'s index in the pool
    uint8 indexOut; // `tokenOut`'s index in the pool
    uint16 mode; // `PAIR_MODE_*` bits
    uint16 features; // the pool's `FEATURE_*` bits
    uint16 protocolFeeBp; // the pool's protocol spread rate, bp
    uint64 feeFloorWad; // the least `PairFill.feeWad`, WAD
    uint64 feeCapWad; // the most `PairFill.feeWad`, WAD
    uint64 bandWad; // the tighter of the two tokens' swap bands, WAD
    uint256 usdIn; // `tokenIn`'s USD per whole token, WAD
    uint256 usdOut; // `tokenOut`'s USD per whole token, WAD
    uint256 amountIn; // the input, `tokenIn` base units
    uint256 maxAmountOut; // core's ceiling on the net output, `tokenOut` base units
    uint256 heldIn; // `tokenIn` held, base units
    uint256 suppliedIn; // `tokenIn` supplied, base units
    uint256 postedIn; // `tokenIn` posted, base units
    uint256 owedIn; // `tokenIn` owed, base units
    uint256 heldOut; // `tokenOut` held, base units
    uint256 suppliedOut; // `tokenOut` supplied, base units
    uint256 postedOut; // `tokenOut` posted, base units
    uint256 owedOut; // `tokenOut` owed, base units
    uint256 restHeldN18; // every other token's held, supplied and posted legs, USD, WAD
    uint256 restOwedN18; // every other token's owed leg, USD, WAD
    /// @dev In bits 0-15 the pair's notional rate, parts per 1e7 of the net payout, by the pair's kind
    ///      (`FLAMMStore.rateOf`; zero where none is set): the floor of the protocol's part, which core books whatever
    ///      `protocolFeeOut` reports ({PairFill}). In bits 16-31, where `features` carry `FLAMMStore.OPERATOR_SHARE`,
    ///      the operator's share's rate, bp, which core books beside the part but on a cover ({PairFill}); zero
    ///      otherwise. A later core may widen this word without changing this interface's selectors; a hook must not
    ///      read more into it than that.
    uint256 extension;
}

/// @notice A hook's fill, native units: input used (at most `amountIn`), gross output, the fee kept from it, the
///         fee rate the fill was computed at, two words the pool only reports, and the protocol's share of this fill's
///         spread in the output token (`protocolFeeOut`), which the pool never mints. `spotAfterN36` is the hook's
///         marginal price after the fill (a fill the hook absorbs without moving its price, such as EverlongHook's
///         leverage fills, reports it unchanged); `xAfter` is a coordinate the hook defines.
/// @dev Core pays `grossOut - feeOut`, never alters a committed fill, and asks the hook once per swap. Only the hook
///      that prices the pair sets a swap's amounts, and no hook runs on a deposit's exit or a redemption.
///
///      The protocol's part core books is its own, in kind, out of the pool's custody in the token paid, after
///      `fillPair` returns: `max(min(protocolFeeOut, bound), net * rate / 1e7)`, where `rate` is the notional rate
///      (`extension`'s bits 0-15) and `bound` is `net * band * protocolFeeBp / (1e18 * 1e4)` (`band` the wider of
///      `bandWad` and core's least fee band), cut to the room the net leaves under the request's ceiling
///      (`maxAmountOut * rate / 1e7 + maxAmountOut - net`).
///      It can be more or less than `protocolFeeOut`, and more than `feeOut`; the pool's `Swap` log reports it. A hook
///      that keeps its own reserves must take out the part core booked, not its own report, or re-read its legs from
///      each request.
///
///      Where the pool sets an operator's share (`FLAMMFloatLib.setOperatorShareBp`, rate `share` in bp; the request's
///      `features` carry `FLAMMStore.OPERATOR_SHARE` then), core books it beside the part, the same way and in the same
///      token: at most `min((base - part) * share / 1e4, room - part)` where `base`, the fee read at most at the fill's
///      own rate (`min(feeOut, net * feeWad / (1e18 - feeWad))`, none at a rate of 1e18), passes the part; `room` is
///      the part's. A cover (`PAIR_MODE_COVER`) pays no share: its fee past the part stays with the LPs. Core cuts it
///      further, never past that bound: where a live pair owes the token paid, `room` counts at `1 - ltv * phiWad`, the
///      highest of those pairs', as a payout room may credit the input and the share brings none; on a rotation, to
///      what the output's custody leaves past the rotation's keep, the net and the part; to the room left in the
///      operator's counter of the token paid and to what fits beside the part under 2^128; and at its booking to what
///      custody holds beside the fee owed and the part (`FLAMMLane.post`). No log reports it per fill. A hook that
///      keeps its own reserves must take it out too: the bound is at least what core books. A hook whose spread is in
///      its price reports no fee but its protocol's part; with the share on it may report the spread it earned as
///      `feeOut` instead, and that spread's rate of the gross as `feeWad`, within the request's fee floor and cap (the
///      PropAMM front reports the desk's edge, capped at the band of the quote leg), so the share is of that spread.
struct PairFill {
    uint256 amountInUsed; // the input used, base units; zero or past `PairRequest.amountIn` refuses (`FillInvalid`)
    uint256 grossOut; // the gross output, base units
    uint256 feeOut; // the fee kept from `grossOut`, base units; a zero net refuses (`FillInvalid`)
    uint256 feeWad; // the rate the fill was computed at, WAD
    uint256 spotAfterN36; // reported only
    uint256 xAfter; // reported only
    uint256 protocolFeeOut; // the hook's report of the protocol's share, `tokenOut` base units
}

/// @notice The one pricing interface, of the swap hook and of a pair hook, for every pool and pair: the quote, a view,
///         and the committed fill. Equal requests get equal answers, and the request never lets the sender set the
///         price. A hook must not price from the pool's balances: a fill sent first shows it the input, a quote and a
///         pulled fill do not.
interface IPairHook {
    /// @notice The fill `r` would get now, with nothing written: the one `fillPair` commits on the same state. The
    ///         pool's `previewSwap` reads it by a static call and runs the swap's checks on the answer, asking again at
    ///         the input the hook used while that is under the one asked. A revert bubbles up through the preview; an
    ///         answer under seven words reverts empty.
    /// @param r The request.
    /// @return The fill, native units.
    function quotePair(PairRequest calldata r) external view returns (PairFill memory);
    /// @notice The committed fill of `r`. The pool's swap calls it once, before any token of the fill moves, then runs
    ///         its checks on the answer ({PairRequest}, {PairFill}) and settles it. A revert bubbles up through the
    ///         swap, a failed check reverts the hook's writes with it, and an answer under seven words reverts empty.
    /// @param r The request.
    /// @return The fill, native units.
    function fillPair(PairRequest calldata r) external returns (PairFill memory);
    /// @notice Whether this hook prices fills of `tokenIn` for `tokenOut` on `pool`. Core asks it for every ordered
    ///         pair of the pool's listed tokens when the hook is installed and when a token is listed, and caches the
    ///         answers in one word: a pair the hook does not price never trades, whatever the curator's trade mask
    ///         says. A cheap-lane pool asks its front again at the listings' resync (`IFLAMMLane.syncListings`) and at
    ///         a pair hook's removal, and at a pair hook's schedule and installation of the pairs that hook would
    ///         price, which the front must not: there a front's revert reads as a pair it prices, and the hook's as one
    ///         it does not. A view that never reverts: equal arguments, equal answer; on a cheap-lane pool a sync reads
    ///         an answer not given (a revert, or a word that is not a bool) as no change to that pair.
    /// @param pool The pool asked of.
    /// @param tokenIn The token the pool would take.
    /// @param tokenOut The token the pool would pay.
    /// @return Whether the hook prices that ordered pair on `pool`.
    function pricesPair(address pool, address tokenIn, address tokenOut) external view returns (bool);
}

/// @notice A pool's second hook, for named pairs (`FLAMMFloatLib.setPairHook`): the hook and the unordered pairs it
///         prices, bit `160 + hi * (hi - 1) / 2 + lo` of `mask` for tokens `lo < hi`; zero when none. The curator
///         installs or replaces it after D, the pool's own delay (`governanceDelaySec`), the curator's choice and risk;
///         a removal, the curator's or the guardian's, applies at once.
interface IPairHookSlot {
    /// @notice Installs, replaces or removes the pair hook. A nonzero `hook` is the curator's: the first call schedules
    ///         it, the identical call applies it from D on and for one more D (`HookSetNotReady` sooner), and the
    ///         curator or the guardian cancels it (`FLAMMAdmitLib.cancel`). A zero `hook` with a zero `mask` removes the hook
    ///         at once and closes its pairs. `NotGuardianOrCurator` for any other caller, `GuardianMayOnlyTighten` for
    ///         a guardian naming a hook, `HookInvalid` for a hook that fails its identity or capability checks, and
    ///         `InvalidConfig` for a removal with a mask or with no hook set, a pool whose credit law is custody-blind,
    ///         a mask empty or naming a pair outside its tokens or the hook pair, or a pair the hook does not price
    ///         both ways or, on a cheap-lane pool, one the front prices. The full rules are on
    ///         `FLAMMFloatLib.setPairHook`.
    /// @param hook The hook; zero removes the one set.
    /// @param mask The unordered pairs it prices, in the layout above.
    function setPairHook(address hook, uint256 mask) external;
    /// @notice The pair hook and its pairs; both zero when none.
    /// @return hook The pair hook.
    /// @return mask The unordered pairs it prices, in the layout above.
    function pairHook() external view returns (address hook, uint256 mask);
}

/// @dev The hook prices fills whose payout may move a debt the output backs onto the input (`PAIR_MODE_ROTATE`); core
///      plans no rotation unless the swap hook declares it and, while one is set, the pair hook too. Its sibling
///      `HOOK_CAP_*` bits are in IHookCapabilities.sol.
uint256 constant HOOK_CAP_ROTATE = 1 << 3;

// `PairRequest.mode`
/// @dev The input is owed: the settlement repays it first and draws nothing.
uint16 constant PAIR_MODE_COVER = 1 << 0;
/// @dev A payout past custody and free collateral may draw the output on its pair.
uint16 constant PAIR_MODE_BORROW = 1 << 1;
/// @dev A payout may move a debt the output backs onto the input.
uint16 constant PAIR_MODE_ROTATE = 1 << 2;
/// @dev The pool is paused: the fill runs only where it draws nothing and lends nothing.
uint16 constant PAIR_MODE_PAUSED = 1 << 3;
/// @dev The venue legs were not read (a fill from custody alone): the supplied, posted and owed legs are zero.
uint16 constant PAIR_MODE_HELD_ONLY = 1 << 4;
/// @dev The input repays all of one debt and the output is borrowed on another pair (a crossing).
uint16 constant PAIR_MODE_CROSS = 1 << 5;
/// @dev Some fence holds a pool part (`FLAMMStore.parted`): a fenced venue's position or a fenced token's custody that
///      the pool still owns a part of is out of the book, so the request's legs and its rest of the book leave it out
///      until the part returns or is given up. A hook that marks the whole book from them reads one short of that part.
///      A custody-only request (`PAIR_MODE_HELD_ONLY`) does not carry it: its venue legs read zero either way.
uint16 constant PAIR_MODE_PARTED = 1 << 6;

src/libraries/Constants.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

// The protocol's shared units and delay values, each written once. A contract that names one of its own (a public
// getter, or a constant other files read through it) declares it as this file's value, at its own type, so a change
// of a value here reaches every rule that shares it, and a rule that must differ changes its own line alone. The
// pool's own delay names keep their literal values, as a constant read through another can compile to other code:
// `DelayLib.GRACE`, `PriceFeed.REPLACE_DELAY`, `FLAMMFactory.MIN_FEE_DELAY_SEC` and the pool store's three
// `MIN_*_DELAY_SEC`. The shared-constants test holds each of them to its value here.

// ---------------------------------------------------------------- units
/// @dev One in 18 decimals: the unit of every `*Wad` ratio, of LTVs, bands, rates and USD prices.
uint256 constant WAD = 1e18;
/// @dev Parts per million: the unit of a rate, a rung's offset and a word's skew.
uint256 constant PPM = 1e6;
/// @dev The first amount past 128 bits: an output cap, and the first amount past a door's grid.
uint256 constant CAP_128 = 1 << 128;

// ---------------------------------------------------------------- delays
/// @dev The least delay a pool may take for its operator's own changes: a pool's `governanceDelaySec` at birth, a
///      launched pool's delay, its authority's delay, and the least a listing's change reads as the pool's own.
uint32 constant POOL_DELAY_FLOOR_SEC = 1 hours;
/// @dev What a protocol-level loosening waits: the front's timelock, a feed's replacement, a protocol fee's rise, a
///      band ceiling's raise, the beacon delay a cheap lane asks for, a credit door's config, and a listing's change
///      where its pool's own delay cannot be read.
uint32 constant PROTOCOL_DELAY_SEC = 10 days;
/// @dev How long a due change stays applicable outside the pool, whose own window is its delay or a day, whichever
///      is longer: past it the change has lapsed.
uint32 constant CHANGE_WINDOW_SEC = 7 days;

src/propamm/libraries/PropAMMLaneLib.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {PPM as ONE_PPM} from "src/libraries/Constants.sol";

/// @notice The cheap lane's shared arithmetic, compiled into the front and the pool alike so both sides of a fill
///         compute it one way: the protocol's spread fee (measured against the fill's fee price, rounded toward the
///         pool's LPs) and the 24-bit amounts of the cheap lane's config word and the front's settings and
///         controls.
library PropAMMLaneLib {
    /// @dev Parts per million, the rate's unit.
    uint256 internal constant PPM = ONE_PPM;

    /// @notice The protocol's spread fee on a fill, in the pair's quote token's base units: `ratePpm` of the fill's
    ///         edge against `p36` (the fee price in the price36 scale: the print, or a WORD or NONE listing's word's
    ///         mid), floored at zero, rounded down. A bid (`poolAssetIn`: the pool buys the base, the pool asset on the
    ///         hook pair): edge = ⌊amountIn × P / 1e36⌋ − amountOut. An ask (the pool sells it): edge =
    ///         amountIn − ⌈amountOut × P / 1e36⌉. A fill with no fee price (`p36` zero) accrues nothing: P = 0 would
    ///         read the whole ask input as edge.
    function spreadFee(bool poolAssetIn, uint256 amountIn, uint256 amountOut, uint256 p36, uint256 ratePpm)
        internal
        pure
        returns (uint256)
    {
        if (p36 == 0 || ratePpm == 0) return 0;
        uint256 edge;
        if (poolAssetIn) {
            uint256 value = Math.mulDiv(amountIn, p36, 1e36);
            if (value <= amountOut) return 0;
            edge = value - amountOut;
        } else {
            uint256 cost = Math.mulDiv(amountOut, p36, 1e36, Math.Rounding.Up);
            if (amountIn <= cost) return 0;
            edge = amountIn - cost;
        }
        return Math.mulDiv(edge, ratePpm, PPM);
    }

    /// @notice A 24-bit amount: an 18-bit mantissa (low bits) times 10 to a 6-bit exponent.
    function amount24(uint256 v) internal pure returns (uint256 r) {
        assembly ("memory-safe") {
            r := mul(and(v, 0x3ffff), exp(10, and(shr(18, v), 0x3f)))
        }
    }
}

src/propamm/libraries/PropAMMStore.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

/// @notice The front's storage: one ERC-7201 namespace (`propamm.front`) that the hot implementation, the landing
///         part and the admin module share. Append only; the published formulas below are frozen with the layout,
///         because off-chain code (state overrides, Base validity predicates, monitoring, the lens through
///         `extSloads`) reads raw slots.
/// @dev The published formulas:
///      - the namespace base `BASE`, each field of `Layout` at `BASE + n` with `n` the slot its comment gives
///        (`relayKeys` takes slots 5 and 6; slot 7 is reserved);
///      - a listing's record at `keccak256(abi.encode(uint256(poolId), BASE + POOLS_INDEX))`, its word `w` at that slot
///        plus `w` (the `Pool` struct's field order);
///      - a pair record at `keccak256(abi.encode(uint256(pairId), BASE + PAIRS_INDEX))`: `cfg`, `token0`, `token1`,
///        `asset`;
///      - a price source's entry at `keccak256(abi.encode(uint256(id), BASE + SOURCES_INDEX))`, `id` its global id;
///      - a pair's `pairIdOf` word at `keccak256(abi.encode(keccak256(abi.encodePacked(token0, token1)), BASE + 16))`,
///        the pair id in its low 32 bits, an asset-module pair's `asset` word above them and the pair word's facts
///        from bit 196 (`PropAMMWords`, a pair's `pairIdOf` word), on every build. This layout suits a fresh front: a
///        word written by a build without the facts copy reads as an empty pair word, so an in-place upgrade from such
///        a build must back-fill every pair first;
///      - a listing's replay word at `keccak256(abi.encode(listing << 8 | target % 16, BASE + RING_INDEX))`, the target
///        a block, or a unix second on a storage build;
///      - a desk's record at `keccak256(abi.encode(uint256(desk), BASE + DESKS_INDEX))`, its word `w` at that slot plus
///        `w` (the `Desk` struct's field order);
///      - an ANY taker's word at `keccak256(abi.encode(taker, keccak256(abi.encode(keyEpoch << 56 | desk << 24 |
///        listing, BASE + ANY_INDEX))))`, the nested mapping's formula.
///
///      Every hot word carries a nonzero version from its first write, so no fill writes a zero slot. Reserved fields
///      stay declared, each marked below (relay keys, the Data Streams checker, the pool template, the operator list,
///      the feed registry, P-256 and session keys, the unused slots, record word 12), so every index above holds.
///
///      A pool id names a listing: one pool's place on one pair, with its own record, maker key and epoch, settings,
///      depth, controls, board state and word. A pool's first listing is its hook pair's (`poolIdOf`, low
///      24 bits); a pool may hold further listings, one per further pair (`listingOf`, keyed by `listingKey`), whose P0
///      bits 248-255 carry the pair's token indices in the pool, and then `poolIdOf` bit 255 (`LISTINGS_FLAG`) is set:
///      readers mask a pool id to 24 bits.
library PropAMMStore {
    /// @dev keccak256(abi.encode(uint256(keccak256("propamm.front")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 internal constant BASE = 0xca023b73b2185d1ba92ba3c09f7870c56c9bdadd91407b68ebb408947da60b00;
    /// @dev `Layout.sources`' slot offset from `BASE`.
    uint256 internal constant SOURCES_INDEX = 15;
    /// @dev `Layout.pairs`' slot offset from `BASE`.
    uint256 internal constant PAIRS_INDEX = 17;
    /// @dev `Layout.pools`' slot offset from `BASE`.
    uint256 internal constant POOLS_INDEX = 18;
    /// @dev `Layout.replayRing`'s slot offset from `BASE`.
    uint256 internal constant RING_INDEX = 42;
    /// @dev `Layout.desks`' slot offset from `BASE`.
    uint256 internal constant DESKS_INDEX = 43;
    /// @dev `Layout.anyTakers`' slot offset from `BASE`.
    uint256 internal constant ANY_INDEX = 45;

    // Transient: the full-word reentrancy lock at `BASE`.

    /// @dev Transient: the pool whose own swap a fill is calling (its credit route), bits 0-159, and the listing that
    ///      fill's plan named, from bit 160: the pool's one `fillPair` call back, which the front admits under that
    ///      fill's lock, fills that listing.
    bytes32 internal constant CREDIT_SLOT = bytes32(uint256(BASE) + 1);
    // Transient: that fill's plan, carried to the pool's call back in the six words after `CREDIT_SLOT`
    // (`PropAMMFront._carry`), written with it and cleared as the call back reads them, so no other call finds them:
    // [+1] the request's key, keccak256(tokenIn, tokenOut, amountIn); [+2] the planned output (bits 0-135), the word's
    // age, ms (136-183), the pair (184-215) and the side (216: a bid); [+3] the fee price; [+4] the side's board word
    // after the fill; [+5] `PoolFill`'s board tag; [+6] the word's anchor.

    /// @dev A pair record (`PAIRS_INDEX`).
    struct Pair {
        uint256 cfg; // the hot configuration word (PropAMMWords, pair word)
        address token0; // the lower token address
        address token1; // the higher token address
        // an asset-module pair's module (0-159) and its base's family (160-163), bound at `addPair` for good where the
        // protocol's asset module claims the base (`familyOf`); zero on any other pair, and on one whose module the
        // protocol owner removed (`removeAssetModule`). On every build the pair's `pairIdOf` word carries a copy for
        // the fills, which the same two calls write
        uint256 asset;
    }

    /// @dev A listing's record (`POOLS_INDEX`); field order is the published word offset.
    struct Pool {
        uint256 p0; // 0: status (pool, pair id, flags, key epoch, word index, listing token indices)
        // 1: Settings (0-191 and the confidence multiplier, 232-239), the desk binding, the credit mode, the tip cap
        uint256 p1;
        // 2: the live source's hot copy (`PropAMMWords`, P2), the one word a fill reads for its source: on a builder
        // build its id and the listing's lease, on a storage build its price lane and two slots; its window, and
        // whether the listing reads its backup or is dark. Zero while the listing has no source
        uint256 price;
        uint256 depthBid0; // 3
        uint256 depthBid1; // 4
        uint256 depthAsk0; // 5
        uint256 depthAsk1; // 6
        uint256 controls; // 7
        uint256 boardBid; // 8
        uint256 boardAsk; // 9
        // 10: the bound source ids (`setSource`): the primary (0-31) and the backup (32-63, 0 none), the rest 0; zero
        // while the listing has no source, exactly where word 2 is. Read on cold paths alone
        uint256 sourceIds;
        uint256 stockPolicy; // 11: the listing's own asset module (0-159), read while P0's `F_ASSET` is set
        // 12: the copy of the listing's word its asset module keeps (`IAssetFront.setAssetWord`), written only by the
        // module the listing resolves to; the named-door fill runs the stock rules on it for a listing of its pair's
        // module (`PropAMMStockRules`); zero until that module first writes it
        uint256 stockState;
    }

    /// @dev A desk's record (`DESKS_INDEX`), never transferred: word 0 [0-159] its cold key, the operator that opened
    ///      it | [160-190] its epoch | [192] stopped | [193-224] the block of its last stop; word 1 its stop key, never
    ///      zero; word 2 its word key, a mirror of its cell's slot 3 (zero for none), which the binding reads.
    struct Desk {
        uint256 w0;
        address stopKey;
        address wordKey;
    }

    /// @dev A per-token feed record, reserved: `Layout.feeds` is never written.
    struct FeedRecord {
        uint256 w; // reserved
        bytes32 dsFeedId; // reserved: the high-security tier
        bytes32 dsSuccessorId; // reserved
    }

    /// @dev The front's storage at `BASE`: each field's comment opens with its slot's offset.
    struct Layout {
        address owner; // 0: the front's timelock, the protocol owner acting after its delay (`owner()`)
        address safe; // 1: the protocol owner's instant key, a multisig (`instantOwner()`)
        address protocolGuardian; // 2: the protocol guardian, who stops but never loosens (`protocolGuardian()`)
        // 3: the launcher, the one caller of `reservePool`, `confirmPool`, `reserveListing`, `confirmListing`,
        // `addListing` and `bindAtBirth`
        address launcher;
        // 4: the registry (0-159; zero on a storage build) | paused all (160) | every lease cut (161) | reserved, 0
        // (162) | desks may open (163, `openDesks`)
        uint256 g0;
        address[2] relayKeys; // 5, 6 (reserved: relay co-signing)
        address reserved7a; // 7 (reserved: unused; no vendor's state sits in the front)
        uint48 reserved7b; // 7 (reserved: unused)
        address dataStreamsChecker; // 8 (reserved: the high-security tier)
        bytes32 poolCodehash; // 9 (reserved: the pool template pin)
        address familyPriceFeed; // 10 (reserved)
        // 11: next pair id (0-31) | next pool id (32-55; it stops at 2^24 - 1, short of bit 56) | the last desk id
        // given (56-87) | the last source id given (88-119, `registerSource`) | code frozen for good (254) |
        // initialized (255)
        uint256 ids;
        uint256 pendingRegistry; // 12: registry (0-159) | due at, unix s (160-223)
        mapping(address => bool) curatorAllowed; // 13 (reserved: the launcher keeps no operator list)
        mapping(address => FeedRecord) feeds; // 14 (reserved: a per-token feed registry; feeds sit in the pair word)
        // 15: the price sources, keyed by a global id (1 to 2^32 - 1, given in order, the last in `ids`; 0 is never
        // written), each registered by anyone (`registerSource`), written once and never edited (`PropAMMWords`, source
        // entry): [0-159] the source contract (a builder build's pull check, the CREATE3 child of the front at salt
        // `bytes32(id)`; a storage build's stored price lane) | [160-191] a stored price lane's base and quote slots |
        // [192-223] the floor, millionths of a quote token | [240-243] the window | [246] an equity base slot | [254] a stored
        // price lane. A listing binds one and a backup (`setSource`, its record's words 2 and 10)
        mapping(uint256 => uint256) sources;
        // 16: keccak256(abi.encodePacked(token0, token1)) => pair id (0-31) | an asset-module pair's `asset` word
        // (32-195: its module and its base's family; 0 on any other pair, and once removed) | the pair word's facts
        // (196-251, `PropAMMWords.entryFacts`) | 0 (252-255), on every build, written by `addPair` and
        // `removeAssetModule` alone and cleared whole by `retirePair`. Readers of the id mask it, and readers of the
        // asset word mask it to its 164 bits. This layout suits a fresh front: a word written by a build without the
        // facts copy reads as an empty pair word, so an in-place upgrade from such a build must back-fill every pair
        // first
        mapping(bytes32 => uint256) pairIdOf;
        mapping(uint256 => Pair) pairs; // 17
        mapping(uint256 => Pool) pools; // 18
        mapping(uint256 => uint256) reserved19; // 19 (reserved, never written: a pair keeps no list of its listings)
        // 20: the pool's first listing (0-23) | the block its launch reserved it, the one it went live (24-71,
        // `PropAMMDue.born`) | has held a further listing (255)
        mapping(address => uint256) poolIdOf;
        mapping(uint256 => uint256) makerKeys; // 21: (poolId << 32 | epoch) => key type (160-167) | key
        mapping(uint256 => bytes32[2]) p256Keys; // 22 (reserved: P-256 keys)
        mapping(uint256 => mapping(address => uint256)) sessionKeys; // 23 (reserved: session keys)
        // 24: change id (keccak256(abi.encode(poolId, kind))) => the scheduled value's tag (0-191: keccak256 of the
        // value, top 192 bits) | due at, unix s (192-255)
        mapping(bytes32 => uint256) pending;
        // 25: `listingKey(pool, pairId)` => the pool's further listing on that pair, live or reserved, or a retired one
        // the protocol owner delisted (kept until its `relistListing`)
        mapping(uint256 => uint256) listingOf;
        // 26: the protocol's asset module, set at `initialize` for good (zero for none): `addPair` asks it which bases
        // it claims (`familyOf`), refuses a quote it claims and adds no pair while it has no code
        address assetModule;
        mapping(address => mapping(address => bool)) pairHookOk; // 27 (reserved: unused; pair hooks are the operator's)
        uint256[14] reserved28; // 28-41 (reserved, never written)
        // 42: the ticket door's replay words, a ring of 16 targets a listing (blocks, or unix seconds on a storage
        // build): (listing << 8 | target % 16) => [0-63] the target + 1 | [64-255] one bit a replay index 0-191, so a
        // listing fills at most 192 guarded quotes a target
        mapping(uint256 => uint256) replayRing;
        mapping(uint256 => Desk) desks; // 43: the desks, by id (assigned in order from 1, `ids` bits 56-87)
        uint256 reserved44; // 44 (reserved, never written)
        // 45: the ANY takers' words, by keyEpoch << 56 | desk << 24 | listing, then by taker: [0-15] the taker's
        // heartbeat H (1-256), 0 unlisted, under the listing's full key epoch at its listing, so a new key epoch
        // empties the list
        mapping(uint256 => mapping(address => uint256)) anyTakers;
        // 46: the chain's quote assets, by token (`uint160`): its rank, 1 the first; 0 none. `addPair` reads it alone,
        // so a change rules only the pairs added after it (`setQuoteAsset`)
        mapping(uint256 => uint256) quoteRank;
    }

    /// @dev `poolIdOf` bit 255: set when the pool first reserves a listing on a further pair and never cleared, a hint
    ///      to read `listingOf` (whose entries an operator's retirement clears), not a count of listings held.
    uint256 internal constant LISTINGS_FLAG = 1 << 255;

    /// @dev `listingOf`'s key: uint160(pool) << 32 | pairId.
    function listingKey(address pool, uint256 pairId) internal pure returns (uint256) {
        return (uint256(uint160(pool)) << 32) | pairId;
    }

    /// @dev The front's storage, in the namespace at `BASE`.
    function state() internal pure returns (Layout storage $) {
        assembly ("memory-safe") {
            $.slot := BASE
        }
    }

    // ---------------------------------------------------------------- transient
    /// @dev Whether a fill holds the front's lock.
    function locked() internal view returns (bool l) {
        assembly ("memory-safe") {
            l := iszero(iszero(tload(BASE)))
        }
    }

    /// @dev Takes the front's lock, reverting `Locked` where a fill holds it.
    function lock() internal {
        assembly ("memory-safe") {
            if tload(BASE) {
                mstore(0, 0x0f2e5b6c) // Locked()
                revert(0x1c, 4)
            }
            tstore(BASE, 1)
        }
    }

    /// @dev Releases the front's lock.
    function unlock() internal {
        assembly ("memory-safe") {
            tstore(BASE, 0)
        }
    }
}

src/propamm/libraries/PropAMMWords.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

import {PropAMMLaneLib} from "src/propamm/libraries/PropAMMLaneLib.sol";
import {PPM} from "src/libraries/Constants.sol";

/// @notice The front's word formats, LSB first. Maker-signed words (pool word, depth, controls) freeze with the maker
///         format; the front's own words (pair word, listing status, board word) freeze with the storage layout. Every
///         word carries a nonzero version. Reserved fields stay in the formats.
/// @dev A side's board is its maker-signed ladder, the two depth words, plus the front's memory of the fills against
///      that ladder, the side's board word: the maker signs the first, and the front alone writes the second. A new
///      depth nonce or a word's refill restarts the memory. A board unit is 10^`boardExp` base units of the side's
///      input token: the fill memory counts in it, and a rung's size in 10^`dExp` of it.
library PropAMMWords {
    uint256 internal constant M8 = 0xff;
    uint256 internal constant M16 = 0xffff;
    uint256 internal constant M20 = 0xfffff;
    uint256 internal constant M24 = 0xffffff;
    uint256 internal constant M32 = 0xffffffff;
    uint256 internal constant M40 = 0xffffffffff;
    uint256 internal constant M48 = 0xffffffffffff;
    uint256 internal constant M64 = 0xffffffffffffffff;
    uint256 internal constant M80 = 0xffffffffffffffffffff;
    uint256 internal constant M96 = 0xffffffffffffffffffffffff;
    uint256 internal constant M160 = (1 << 160) - 1;


    // ---------------------------------------------------------------- pool word (maker-signed)
    /// @dev [0-7] kind and version | [8-71] price mantissa | [72-119] maker time ms | [120-135] life s |
    ///      [136-151] bid skew ppm | [152-167] ask skew ppm | [168-199] max block, the last valid block, inclusive (0
    ///      none; no fill reads it, as a desk's cell writes these bits itself) | [200-207] key epoch, low 8 bits |
    ///      [208-231] the listing's pool id | [232-255] refill with acknowledgement: [232] bid, [233] ask, [234-244]
    ///      bid fill sequence, [245-255] ask fill sequence (each the low 11 bits of the side's board sequence). A word
    ///      refills a side once (`refills`): a maker stamps a refill word at the later of its own clock and the side's
    ///      last fill time plus 1 ms, and 1 ms later again where its time's low 9 bits match the side board's bits
    ///      247-255.
    uint256 internal constant KIND_QUOTE = 0x01;

    function kind(uint256 w) internal pure returns (uint256) {
        return w & M8;
    }

    function mantissa(uint256 w) internal pure returns (uint256) {
        return (w >> 8) & M64;
    }

    function makerTs(uint256 w) internal pure returns (uint256) {
        return (w >> 72) & M48;
    }

    function ttl(uint256 w) internal pure returns (uint256) {
        return (w >> 120) & M16;
    }

    function skew(uint256 w, bool bid) internal pure returns (uint256) {
        return (w >> (bid ? 136 : 152)) & M16;
    }

    function epoch8(uint256 w) internal pure returns (uint256) {
        return (w >> 200) & M8;
    }

    function poolId(uint256 w) internal pure returns (uint256) {
        return (w >> 208) & M24;
    }

    /// @dev Whether the word asks to refill `bid`'s side, and the 11-bit fill sequence it acknowledges.
    function refill(uint256 w, bool bid) internal pure returns (bool on, uint256 ack) {
        if (bid) return (((w >> 232) & 1) != 0, (w >> 234) & 0x7ff);
        return (((w >> 233) & 1) != 0, (w >> 245) & 0x7ff);
    }

    /// @dev Whether pool word `w` refills `bid`'s side, whose board word is `b`: it asks it and acknowledges the side's
    ///      sequence, it was signed after the side's last fill (strictly: every fill of a block shares one clock), and
    ///      it is not the word that refilled the side last (its maker time's low 9 bits against board bits 247-255,
    ///      which the refilling fill writes), so a word stamped ahead of the fill clock still refills once only.
    function refills(uint256 w, bool bid, uint256 b) internal pure returns (bool) {
        (bool on, uint256 ack) = refill(w, bid);
        uint256 ts = makerTs(w);
        return on && ack == bSeq(b) && ts > bTime(b) && ts & 0x1ff != b >> 247;
    }

    // ---------------------------------------------------------------- depth (maker-signed)
    /// @dev Word 0: [0-3] version | [4-11] key epoch | [12-59] nonce ms | [60-91] expires at s | [92-111] drift
    ///      ppm/s | [112-117] size exponent | [118] word 1 present | [119] 0 | [120-227] rungs 0-2 | [228-255] 0.
    ///      Word 1: rungs 3-9 in [0-251] | version in [252-255]. A rung: cumulative size (16, low) | offset ppm (20).
    function dVersion(uint256 d) internal pure returns (uint256) {
        return d & 0xf;
    }

    function dEpoch8(uint256 d) internal pure returns (uint256) {
        return (d >> 4) & M8;
    }

    function dNonce(uint256 d) internal pure returns (uint256) {
        return (d >> 12) & M48;
    }

    function dExpires(uint256 d) internal pure returns (uint256) {
        return (d >> 60) & M32;
    }

    function dDrift(uint256 d) internal pure returns (uint256) {
        return (d >> 92) & M20;
    }

    function dExp(uint256 d) internal pure returns (uint256) {
        return (d >> 112) & 0x3f;
    }

    function dHasW1(uint256 d) internal pure returns (bool) {
        return ((d >> 118) & 1) != 0;
    }

    /// @dev Rung `j` (0-9) of a side: its 36 bits.
    function rung(uint256 w0, uint256 w1, uint256 j) internal pure returns (uint256) {
        return j < 3 ? (w0 >> (120 + 36 * j)) & 0xfffffffff : (w1 >> (36 * (j - 3))) & 0xfffffffff;
    }

    // ---------------------------------------------------------------- controls (maker-signed)
    /// @dev [0-7] version | [8-15] key epoch | [16-63] nonce ms | [64-71] flags (bit 0 self-pause, bit 2 refill with
    ///      acknowledgement allowed; bit 1, the session gate, reserved) | [72-76] session mask (reserved, 0) |
    ///      [77-79] 0 | [80-103] bid rate cap | [104-127] ask rate cap | [128-135] burst s | [136-155] widening
    ///      ppm/sqrt(s) | [156-175] premium ppm | [176-191] premium window ms | [192-207] widening grace ms |
    ///      [208-255] multiplier fingerprint (reserved, 0).
    uint256 internal constant CTL_SELF_PAUSE = 1 << 64;
    uint256 internal constant CTL_REFILL = 1 << 66;
    uint256 internal constant CTL_FLAGS_KNOWN = 0x5;

    function cNonce(uint256 c) internal pure returns (uint256) {
        return (c >> 16) & M48;
    }

    function cRate(uint256 c, bool bid) internal pure returns (uint256) {
        return PropAMMLaneLib.amount24((c >> (bid ? 80 : 104)) & M24);
    }

    function cBurstSec(uint256 c) internal pure returns (uint256) {
        return (c >> 128) & M8;
    }

    function cWiden(uint256 c) internal pure returns (uint256) {
        return (c >> 136) & M20;
    }

    function cPremium(uint256 c) internal pure returns (uint256) {
        return (c >> 156) & M20;
    }

    function cPremiumWindow(uint256 c) internal pure returns (uint256) {
        return (c >> 176) & M16;
    }

    function cGrace(uint256 c) internal pure returns (uint256) {
        return (c >> 192) & M16;
    }

    // ---------------------------------------------------------------- board state (the front's own)
    /// @dev [0-3] version | [4-51] depth tag | [52-91] filled, board units | [92-187] bucket level, quote base units
    ///      | [188-235] bucket time ms | [236-246] fill sequence (11 bits, wraps) | [247-255] the low 9 bits of the
    ///      maker time of the pool word that refilled the side last (0 before its first refill).
    function board(uint256 tag, uint256 filled, uint256 level, uint256 timeMs, uint256 seq, uint256 refilledBy)
        internal
        pure
        returns (uint256)
    {
        return 1 | (tag << 4) | (filled << 52) | (level << 92) | (timeMs << 188) | ((seq & 0x7ff) << 236)
            | (refilledBy << 247);
    }

    function bTag(uint256 b) internal pure returns (uint256) {
        return (b >> 4) & M48;
    }

    function bFilled(uint256 b) internal pure returns (uint256) {
        return (b >> 52) & M40;
    }

    function bLevel(uint256 b) internal pure returns (uint256) {
        return (b >> 92) & M96;
    }

    function bTime(uint256 b) internal pure returns (uint256) {
        return (b >> 188) & M48;
    }

    function bSeq(uint256 b) internal pure returns (uint256) {
        return (b >> 236) & 0x7ff;
    }

    // ---------------------------------------------------------------- pair word (the front's own)
    /// @dev [0-7] version | [8] base is token0 | [9] high-security (reserved, 0) | [10] the quote is a listed quote
    ///      asset as the list stood at `addPair` (`PAIR_QUOTE_ASSET`) | [11-13] reserved, 0 | [14] paused (reserved) |
    ///      [15] an asset-module pair (`PAIR_ASSET`) | [16-23] reserved, 1 | [24-31] reserved, 1 | [32-95] reserved,
    ///      0 | [96-103] price-unit exponent u, 24 + quote decimals - base decimals, so the cross's scale k is 12 |
    ///      [104-111] reserved, 0 | [112-119] bid board exponent, base decimals - 6 | [120-127] ask board exponent,
    ///      quote decimals - 2 where bit 10 is set, else quote decimals - 6, each at least 0 | [128-175] reserved, 0 |
    ///      [176-183] base decimals | [184-191] quote decimals | [192-255] reserved, 0. `addPair` derives every field
    ///      from the two tokens and the lists as they stand, so a pair's facts are the same whoever adds it: the quote
    ///      is the listed quote asset where one token is one, the lower rank where both are, else the token the asset
    ///      module does not claim (token1 where it claims neither). A price source and a lease are each
    ///      listing's own (record words 2 and 10), never the pair's. Every pair is of one kind: any number of
    ///      listings, each reached by its id, and no list or count of them. The word is written once and is the
    ///      record; the pair's `pairIdOf` word carries a copy of its facts, which fills and quotes read (`entryFacts`).
    uint256 internal constant PAIR_BASE_IS_T0 = 1 << 8;
    /// @dev The pair's quote was a listed quote asset at `addPair` (`quoteRank`), which sets the ask board's exponent.
    uint256 internal constant PAIR_QUOTE_ASSET = 1 << 10;
    /// @dev An asset-module pair: the protocol's asset module claimed its base at `addPair` (`familyOf`), and every
    ///      quote and fill of it asks the module.
    uint256 internal constant PAIR_ASSET = 1 << 15;

    function unitExp(uint256 p) internal pure returns (uint256) {
        return (p >> 96) & M8;
    }

    /// @dev The board unit exponent of the side whose input it counts: the base token's on a bid, the quote's on an
    ///      ask.
    function boardExp(uint256 p, bool bid) internal pure returns (uint256) {
        return (p >> (bid ? 112 : 120)) & M8;
    }

    function decBase(uint256 p) internal pure returns (uint256) {
        return (p >> 176) & M8;
    }

    function decQuote(uint256 p) internal pure returns (uint256) {
        return (p >> 184) & M8;
    }

    /// @dev k = 36 + decQuote - decBase - u: the cross's scale, P̂ = pa * 10^k / pb (12 on each pair `addPair` writes).
    function crossExp(uint256 p) internal pure returns (uint256) {
        return 36 + decQuote(p) - decBase(p) - unitExp(p);
    }

    // ---------------------------------------------------------------- a pair's `pairIdOf` word (the front's own)
    /// @dev [0-31] the pair id | [32-195] an asset-module pair's asset word (`PropAMMStore.Pair.asset`), 0 on any
    ///      other pair | [196-251] the pair word's facts, the copy every fill and quote reads in place of the pair
    ///      word: its bits 0-15 (version and flags) at 196-211, 96-103 (u) at 212-219, 112-127 (the board exponents)
    ///      at 220-235 and 176-191 (the decimals) at 236-251 | [252-255] 0. Every other pair-word bit is a constant
    ///      of `addPair`'s (`PAIR_FIXED` set, the rest 0), so the copy gives the word back whole (`entryWord`).
    ///      `addPair` writes the copy with the pair word, `removeAssetModule` writes it again, and nothing else
    ///      writes either; a retired pair's word is cleared whole (`retirePair`).
    uint256 internal constant ENTRY_FACTS = 196;
    /// @dev The pair-word bits `addPair` sets outside the copy: reserved bits 16 and 24.
    uint256 internal constant PAIR_FIXED = (1 << 16) | (1 << 24);

    /// @dev The asset word a `pairIdOf` word `e` carries (bits 32-195).
    function entryAsset(uint256 e) internal pure returns (uint256) {
        return (e >> 32) & ((uint256(1) << 164) - 1);
    }

    /// @dev Pair word `p`'s facts, at their place in the pair's `pairIdOf` word.
    function entryFacts(uint256 p) internal pure returns (uint256) {
        return ((p & M16) | (((p >> 96) & M8) << 16) | (((p >> 112) & M16) << 24) | (((p >> 176) & M16) << 40))
            << ENTRY_FACTS;
    }

    /// @dev The pair word whose facts the `pairIdOf` word `e` copies.
    function entryWord(uint256 e) internal pure returns (uint256) {
        uint256 f = e >> ENTRY_FACTS;
        return (f & M16) | PAIR_FIXED | (((f >> 16) & M8) << 96) | (((f >> 24) & M16) << 112)
            | (((f >> 40) & M16) << 176);
    }

    // ---------------------------------------------------------------- listing status P0 (the front's own)
    /// @dev [0-159] the pool | [160-191] pair id | [192-199] flags | [200-231] key epoch | [232-239] the listing's word
    ///      index: its standing word in its desk's cell (0 at reservation; written by the desk binding alone) |
    ///      [240-247] reserved, 0 (a listing's sources sit in its record's words 2 and 10) | [248-255] the listing's
    ///      token indices in its pool, base (248-251) and quote (252-255); 0 on the pool's hook pair (base token 0, the
    ///      pool asset; quote token 1). The cheap lane hands the pool this byte as its pair bits. Flag bits: 192
    ///      (`F_LIVE`) set while the listing is live, 193 to 195 the three below, 196-198 reserved, 199 (`F_ASSET`) set
    ///      while an asset-module listing asks its own module (word 11 of the listing's record) in place of its pair's.
    uint256 internal constant F_LIVE = 1 << 192;
    /// @dev Reserved: nothing sets it. A fill reads it through `F_DARK`, and `unpause` clears it.
    uint256 internal constant F_PAUSED = 1 << 193;
    /// @dev The listing is frozen (`freeze`): its pool's guardian or its operator lifts it (`unfreeze`).
    uint256 internal constant F_FROZEN = 1 << 194;
    /// @dev The maker key paused the listing (`pauseMaker`); only the operator's `unpause` lifts it.
    uint256 internal constant F_MAKER_PAUSED = 1 << 195;
    /// @dev Every flag that darkens a listing at fill.
    uint256 internal constant F_DARK = F_PAUSED | F_FROZEN | F_MAKER_PAUSED;
    /// @dev The listing asks its own asset module (`setAssetModule`), not its pair's.
    uint256 internal constant F_ASSET = 1 << 199;

    function sPairId(uint256 s) internal pure returns (uint256) {
        return (s >> 160) & M32;
    }

    function sEpoch(uint256 s) internal pure returns (uint256) {
        return (s >> 200) & M32;
    }

    /// @dev The listing's token indices, P0's top byte: base (low 4 bits) and quote (high 4 bits); 0 on the hook pair.
    function sIndices(uint256 s) internal pure returns (uint256) {
        return s >> 248;
    }

    /// @dev The listing's word index, P0 bits 232-239: the standing word its desk's cell keeps for it (slot 16 +
    ///      index).
    function sWordIndex(uint256 s) internal pure returns (uint256) {
        return (s >> 232) & M8;
    }

    // ---------------------------------------------------------------- settings P1
    /// @dev `Settings` packed in declaration order: fences (0, 16) and the ceiling (32), each ppm / 10 (one unit 0.1
    ///      bp, at most 65,535 units, 655,350 ppm), max age (48), rate ceilings (64, 88), burst ceilings (112, 136),
    ///      minimum fill (160), split depth (184), the confidence multiplier (232); [192-223] the listing's desk, a
    ///      uint32 (0 unbound) | [224] reserved | [225-226] the credit mode (`CREDIT_*`) | [227] ANY allowed |
    ///      [228-229] the fence kind (`FENCE_*`; 3 refused) | [230-231] the carry life L in blocks, 0 or 1 (more
    ///      refused) | [232-239] the confidence multiplier k, tenths, at most 30 | [240-255] the taker tip cap: a
    ///      12-bit mantissa (240-251) and a 4-bit exponent of 10 (252-255), wei per gas, 0 off. Zero is safe in every
    ///      field: a zeroed fence kind reads PRINT, the most fenced; a zeroed cap is off; desk 0 is unbound. The
    ///      admin's setters write their own bits and keep the rest; the desk bits (192-223, 227-231 and P0's word
    ///      index) are the desk binding's alone.
    uint256 internal constant SETTINGS_BITS = ((1 << 192) - 1) | (M8 << 232);
    uint256 internal constant DESK_SHIFT = 192;
    uint256 internal constant CREDIT_SHIFT = 225;
    uint256 internal constant ANY_SHIFT = 227;
    uint256 internal constant FENCE_SHIFT = 228;
    uint256 internal constant CARRY_SHIFT = 230;
    uint256 internal constant CONF_MUL_SHIFT = 232;
    uint256 internal constant TIP_SHIFT = 240;
    /// @dev The fence kinds (P1 bits 228-229): the vendor print (0, a kept print or one the taker carries), the
    ///      landed word signed by the desk's word key (1), or none (2, caps alone on the ticket door).
    uint256 internal constant FENCE_PRINT = 0;
    uint256 internal constant FENCE_WORD = 1;
    uint256 internal constant FENCE_NONE = 2;

    /// @dev The listing's desk, P1 bits 192-223: 0 unbound.
    function desk(uint256 s) internal pure returns (uint256) {
        return (s >> DESK_SHIFT) & M32;
    }

    /// @dev Whether the listing's desk may fill ANY quotes there (P1 bit 227).
    function anyOn(uint256 s) internal pure returns (bool) {
        return (s >> ANY_SHIFT) & 1 != 0;
    }

    /// @dev The listing's fence kind, P1 bits 228-229 (`FENCE_*`).
    function fenceKind(uint256 s) internal pure returns (uint256) {
        return (s >> FENCE_SHIFT) & 3;
    }

    /// @dev The listing's carry life L in blocks, P1 bits 230-231: whether a word of the listing's own may still fill a
    ///      named fill in the block after its landing (L 1, and the word's own carry life nonzero); never later, so
    ///      the binding refuses more and the named door reads more as one.
    function carry(uint256 s) internal pure returns (uint256) {
        return (s >> CARRY_SHIFT) & 3;
    }

    /// @dev The listing's taker tip cap, P1 bits 240-255, as stored: 0 off.
    function tipCap(uint256 s) internal pure returns (uint256) {
        return s >> TIP_SHIFT;
    }

    /// @dev A tip cap's value, wei per gas: its 12-bit mantissa times 10 to its 4-bit exponent.
    function tipWei(uint256 c) internal pure returns (uint256) {
        return (c & 0xfff) * pow10((c >> 12) & 15);
    }

    // ---------------------------------------------------------------- the desk's words (its cell's storage)
    /// @dev The ticket, a cell's slot 0: [0-31] stamp, the block number's low 32 bits when the cell wrote it (on a
    ///      storage build the low 32 bits of its push's maker time, never 0) | [32-62] desk epoch | [63] stopped |
    ///      [64-127] the desk word: [64-111] twelve 4-bit latch counts, desk book b and side s at 64 + 4(2b + s) (s 1
    ///      for the pool's bid) | [112-126] version, 15 bits | [127] the registry mark, set on a copy of a builder
    ///      lane | [128-223] six 16-bit desk book indexes, book 0 lowest | [224-255] the desk floor. What the books,
    ///      indexes, latches and floor mean: `PropAMMLandingDesk.FirmQuote`.
    function tStamp(uint256 t) internal pure returns (uint256) {
        return t & M32;
    }

    function tEpoch(uint256 t) internal pure returns (uint256) {
        return (t >> 32) & 0x7fffffff;
    }

    function tStopped(uint256 t) internal pure returns (bool) {
        return (t >> 63) & 1 != 0;
    }

    /// @dev Desk book `b`'s latch count for one side, the pool's bid where `bid`.
    function tLatch(uint256 t, uint256 b, bool bid) internal pure returns (uint256) {
        return (t >> (64 + 8 * b + (bid ? 4 : 0))) & 15;
    }

    function tVersion(uint256 t) internal pure returns (uint256) {
        return (t >> 112) & 0x7fff;
    }

    /// @dev Desk book `b`'s landed index.
    function tIndex(uint256 t, uint256 b) internal pure returns (uint256) {
        return (t >> (128 + 16 * b)) & M16;
    }

    function tFloor(uint256 t) internal pure returns (uint256) {
        return t >> 224;
    }

    /// @dev A standing word as a cell's read answers it (index 0-7: its slot 16 + i; 8 and up: an entry of a packed
    ///      group, expanded, whose life is at most 511 s), in the pool word's format but for: [0-3] kind (1 quote, 2
    ///      off) | [4-7] the word's carry: 0 none; any nonzero value lets it fill only in the block after its landing
    ///      (the front reads no more) | [168-199] its write stamp (the cell's): the low 32 bits of the block the cell
    ///      wrote it in (builder) or that block's unix second (storage), never its maker time, which freshness reads
    ///      from bits 72-119 | [200-207] the desk epoch's low 8 bits (the cell's) | [208] signed by the desk's word key
    ///      (the cell's) | [209] reference only (the named door refuses it) | [210-224] the version of the landing
    ///      that wrote it (the cell's): at a packed index on both families, at 0-7 on a storage build (reserved, as
    ///      pushed, at 0-7 on a builder build) | [225-231] reserved, 0, ignored. The front reshapes it into a pool
    ///      word for the walk: bits 4-7 and 168-231 cleared, the listing's key epoch at 200-207 and the listing at
    ///      208-231.
    function wKind(uint256 w) internal pure returns (uint256) {
        return w & 15;
    }

    function wCarry(uint256 w) internal pure returns (uint256) {
        return (w >> 4) & 15;
    }

    function wStamp(uint256 w) internal pure returns (uint256) {
        return (w >> 168) & M32;
    }

    function wSigned(uint256 w) internal pure returns (bool) {
        return (w >> 208) & 1 != 0;
    }

    function wRefOnly(uint256 w) internal pure returns (bool) {
        return (w >> 209) & 1 != 0;
    }

    /// @dev A storage build's standing word: the version of the push that wrote it.
    function wVersion(uint256 w) internal pure returns (uint256) {
        return (w >> 210) & 0x7fff;
    }

    // ---------------------------------------------------------------- the ticket door's quote (kind 1)
    /// @dev `FirmQuote.terms`: [0-23] listing | [24] bid (the taker sells base) | [25] partial fills | [26] the taker
    ///      is `tx.origin` (TICKET only) | [27-31] 0 | [32-39] listing key epoch, low 8 bits | [40-87] signed at, ms |
    ///      [88-119] target, a block (a unix second on a storage build) | [120-127] extra targets K | [128-135] desk
    ///      epoch, low 8 bits | [136-143] replay index | [144-147] kind 1 | [148-179] generation | [180-183] 0 | [184]
    ///      TICKET (else ANY) | [185-187] desk book | [188-203] the book's index it was priced at | [204-211] cap, 0.1
    ///      bp ticks | [212-214] reprice mode | [215-218] the side's latch count at signing | [219] skip the latch |
    ///      [220-255] 0. What the desk fields mean, and how a move of the ticket voids or reprices the quote:
    ///      `PropAMMLandingDesk.FirmQuote`.
    function qSigned(uint256 t) internal pure returns (uint256) {
        return (t >> 40) & M48;
    }

    function qTarget(uint256 t) internal pure returns (uint256) {
        return (t >> 88) & M32;
    }

    function qExtra(uint256 t) internal pure returns (uint256) {
        return (t >> 120) & M8;
    }

    function qReplay(uint256 t) internal pure returns (uint256) {
        return (t >> 136) & M8;
    }

    function qGeneration(uint256 t) internal pure returns (uint256) {
        return (t >> 148) & M32;
    }

    function qTicket(uint256 t) internal pure returns (bool) {
        return (t >> 184) & 1 != 0;
    }

    function qBook(uint256 t) internal pure returns (uint256) {
        return (t >> 185) & 7;
    }

    function qMode(uint256 t) internal pure returns (uint256) {
        return (t >> 212) & 7;
    }
    /// @dev The credit modes, each looser than the one before: the front fills from custody alone (0);
    ///      where custody cuts a fill short it routes it to the pool's own swap if no pair of the pool may borrow the
    ///      output token (1), or whether or not one may (2); it routes every fill to the pool's own swap (3).
    uint256 internal constant CREDIT_CHEAP = 0;
    uint256 internal constant CREDIT_SUPPLY = 1;
    uint256 internal constant CREDIT_BORROW = 2;
    uint256 internal constant CREDIT_ALWAYS = 3;

    /// @dev The listing's confidence multiplier, P1 bits 232-239: tenths.
    function confMul(uint256 s) internal pure returns (uint256) {
        return (s >> CONF_MUL_SHIFT) & M8;
    }

    function creditMode(uint256 s) internal pure returns (uint256) {
        return (s >> CREDIT_SHIFT) & 3;
    }

    /// @dev The side's price fence B, ppm (its field x 10).
    function fence(uint256 s, bool bid) internal pure returns (uint256) {
        return ((s >> (bid ? 0 : 16)) & M16) * 10;
    }

    /// @dev The listing's ceiling R, ppm (its field x 10): the most its band's fence and refusal reach.
    function ceil(uint256 s) internal pure returns (uint256) {
        return ((s >> 32) & M16) * 10;
    }

    function maxAgeMs(uint256 s) internal pure returns (uint256) {
        return (s >> 48) & M16;
    }

    function rateCeil(uint256 s, bool bid) internal pure returns (uint256) {
        return PropAMMLaneLib.amount24((s >> (bid ? 64 : 88)) & M24);
    }

    function burstCeil(uint256 s, bool bid) internal pure returns (uint256) {
        return PropAMMLaneLib.amount24((s >> (bid ? 112 : 136)) & M24);
    }

    function minFill(uint256 s) internal pure returns (uint256) {
        return PropAMMLaneLib.amount24((s >> 160) & M24);
    }

    function splitDepth(uint256 s) internal pure returns (uint256) {
        return (s >> 184) & M8;
    }

    // ---------------------------------------------------------------- P2, record word 2 (`price`, the front's own)
    // The live source's hot copy, which a fill reads alone for its source (`PropAMMShared._srcOf`); zero while the
    // listing has no source. A builder build: [0-31] the live source's id, its pull check the CREATE3 child of the
    // front at salt `bytes32(id)` | [32-199] reserved, 0 | [200-231] the listing's lease, unix s: until then its source
    // may honour its cached trust (`refreshLease`; a new binding starts with none) | [232-239] reserved, 0. A storage
    // build: [0-159] the live source's stored price lane | [160-175] its base slot | [176-191] its quote slot |
    // [192-239] reserved, 0. Both: [240-243] the live source's window, 500 ms steps | [244] `P2_ON_BACKUP` | [245]
    // `P2_DARK` | [246-255] reserved, 0. Word 10 (`sourceIds`) names the bound ids: [0-31] the primary | [32-63] the
    // backup (0 none) | [64-255] reserved, 0; zero exactly where this word is.
    /// @dev The listing reads its backup: its primary was darkened (`darkenSource`).
    uint256 internal constant P2_ON_BACKUP = 1 << 244;
    /// @dev The listing reads no source: darkened with no backup to fall to, every other bit 0, so a PRINT fill finds
    ///      none (`SourceDark`).
    uint256 internal constant P2_DARK = 1 << 245;

    // ---------------------------------------------------------------- source entry (the front's own)
    // `PropAMMStore.Layout.sources`, keyed by a global id (1 to 2^32 - 1, given in order by `registerSource` to
    // anyone), written once and never edited; `sources[0]` is never written. A builder build: [0-159] the pull check,
    // the CREATE3 child of the front at salt `bytes32(id)` | [160-191] reserved, 0. A storage build: [0-159] the stored
    // price lane | [160-175] the base slot (1-65,535) | [176-191] the quote slot (1-65,535, never the base's). Both:
    // [192-223] the floor, millionths of a whole quote token (0 none) | [224-239] reserved, 0 | [240-243] the window (1-15), 500 ms
    // steps | [244-245] reserved, 0 | [246] `E_EQUITY` | [247-253] reserved, 0 | [254] `E_LANE` | [255] reserved, 0.
    /// @dev A storage build's source whose base slot is an equity feed (its lane's `jumpsOf` nonzero): an asset-module
    ///      pair's listing binds only such a source, and any other listing never one.
    uint256 internal constant E_EQUITY = 1 << 246;
    /// @dev A stored price lane's entry: set on every storage build's entry, on no builder build's.
    uint256 internal constant E_LANE = 1 << 254;

    /// @dev The source's floor, millionths of a whole quote token: a PRINT listing reading it fills at least that much
    ///      (`PropAMMShared._srcFloor`), on any pair; 0 none.
    function eFloor(uint256 e) internal pure returns (uint256) {
        return (e >> 192) & M32;
    }

    // ---------------------------------------------------------------- a fill's log
    /// @dev `PoolFill`'s `feeAge`: [0-191] the spread fee | [192-239] the quote's age, ms | [240-254] 0 | [255] the
    ///      side, 1 a bid (the taker sells the pair's base). The fee is under 2^150 and the age under 2^48 on every
    ///      path, so neither reaches the field above it.
    function feeAge(uint256 fee, uint256 ageMs, bool bid) internal pure returns (uint256) {
        return fee | (ageMs << 192) | (bid ? uint256(1) << 255 : 0);
    }

    // ---------------------------------------------------------------- amounts
    /// @dev 10^e for e at most 77 (callers pass at most 63), by the EXP opcode.
    function pow10(uint256 e) internal pure returns (uint256 r) {
        assembly ("memory-safe") {
            r := exp(10, e)
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {
    "src/core/mm/MMRouterLib.sol": {
      "MMRouterLib": "0xA4749766934833DfBeaF4Fc0d79c150A1Dd2B4E5"
    },
    "src/core/flamm/FLAMMLane.sol": {
      "FLAMMLane": "0x0988077AB06F1efd8cFa3f08FC60CAf3e6d22e98"
    },
    "src/core/flamm/FLAMMRoute.sol": {
      "FLAMMRoute": "0x312ee92ecd113F925dD513d450b062C8740fDaA9"
    },
    "src/periphery/FLAMMMaxima.sol": {
      "FLAMMMaxima": "0x4A997343D91c981BF63274fc222AA96D32d6259c"
    },
    "src/core/flamm/FLAMMLawLib.sol": {
      "FLAMMLawLib": "0x5D473B15E032756Cd81fc66B8F1e9BE2f427cc62"
    },
    "src/core/flamm/FLAMMOpsLib.sol": {
      "FLAMMOpsLib": "0x0BFe60fB1f5223F1A2b7B02Ef18f5C33fb043753"
    },
    "src/core/mm/AaveV3ReadsLib.sol": {
      "AaveV3ReadsLib": "0xD53F6170226A74D453e84414Ffc2FFcE5ded5983"
    },
    "src/core/flamm/FLAMMFlowLib.sol": {
      "FLAMMFlowLib": "0x2577D707D41209489b2EF53101a4f6baDd4E3473"
    },
    "src/core/flamm/FLAMMGateLib.sol": {
      "FLAMMGateLib": "0xF0BE115A2D6F27274F2e9EE50B89Ed42db2B9555"
    },
    "src/core/flamm/FLAMMKeptLib.sol": {
      "FLAMMKeptLib": "0x7a11899232dd9F17c28bF062Ec2ee2267158517b"
    },
    "src/core/mm/CTokenMarketLib.sol": {
      "CTokenMarketLib": "0x18c53F2aCAbcDEEdb575A136f49fa4C43EB2071c"
    },
    "src/core/flamm/FLAMMAdmitLib.sol": {
      "FLAMMAdmitLib": "0xA6dBD8cD5Cd10F8a5857cbeD54a28405ffbDcBCb"
    },
    "src/core/flamm/FLAMMBlindLib.sol": {
      "FLAMMBlindLib": "0x0b8d436F1a7AE25C5d16955ed4CDa781E42e7E5C"
    },
    "src/core/flamm/FLAMMClaimLib.sol": {
      "FLAMMClaimLib": "0x02b4354a56630ab165A880B1198a603E62731cCE"
    },
    "src/core/flamm/FLAMMFenceLib.sol": {
      "FLAMMFenceLib": "0xA16ddA83f47a42F875f141b6954595D584a201e8"
    },
    "src/core/flamm/FLAMMFloatLib.sol": {
      "FLAMMFloatLib": "0x539EfC2b17cF0fdF254AAaB925b3A7c360A79737"
    },
    "src/core/flamm/FLAMMQuoteLib.sol": {
      "FLAMMQuoteLib": "0xa4D34f4882a529574840881e755BCFae2bd5ce2e"
    },
    "src/core/flamm/FLAMMTopUpLib.sol": {
      "FLAMMTopUpLib": "0x7C55a535Ce298b1e5e6d00F645088F777ad233DF"
    },
    "src/core/mm/CTokenRewardsLib.sol": {
      "CTokenRewardsLib": "0xcda63d7eCCF838F2732Bff676706BDE5abA4DcF7"
    },
    "src/core/mm/MMRouterAdminLib.sol": {
      "MMRouterAdminLib": "0x8423744b3F304ED0B43043d7ad4E7d8A247aDc96"
    },
    "src/core/flamm/FLAMMPolicyLib.sol": {
      "FLAMMPolicyLib": "0xa6B495B2BdcDcf4F327844d9aaA0eD4C550c67F9"
    },
    "src/core/flamm/FLAMMSettleLib.sol": {
      "FLAMMSettleLib": "0xB4890a27205505BDAA05717B6c3aB38b2dd3C7Cb"
    },
    "src/core/flamm/FLAMMSharedLib.sol": {
      "FLAMMSharedLib": "0xFaAEd38962aEb6c282Ac36E0cdE9313AbA2511ba"
    },
    "src/periphery/FLAMMExitMaxima.sol": {
      "FLAMMExitMaxima": "0x480f51866554e92649c9d3502bA31AA4234e0a81"
    },
    "src/hooks/everlong/LeverageLib.sol": {
      "LeverageLib": "0x1B1D1C42d26c169dB59D8681d0FD4C9a2840Ad11"
    },
    "src/core/flamm/FLAMMMaintainLib.sol": {
      "FLAMMMaintainLib": "0x94998f13fc5d5D2271c90b835c6a805dad409cC2"
    },
    "src/core/flamm/FLAMMPairQuoteLib.sol": {
      "FLAMMPairQuoteLib": "0x077523D1427aE408105fe8592F907ECDa0D94cbE"
    },
    "src/hooks/everlong/EverlongOpsLib.sol": {
      "EverlongOpsLib": "0xAbe4447C954E3C7a405f8E75116BF9f5787426F7"
    }
  },
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
    "solady/=lib/solady/src/",
    "forge-std/=lib/forge-std/src/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.