Skip to content
Verified contractExactUNLICENSED

FLAMMGateLib

Address0x2291f5e012b0740468e2e2e9aea37f7fea64f98c
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

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,446,202
Creation transaction
0x97e145bc7a…9f0c975341
Libraries
src/core/mm/MMRouterLib.sol:MMRouterLib0xa474…d2b4e5src/core/flamm/FLAMMLane.sol:FLAMMLane0x82a0…7f67dfsrc/core/flamm/FLAMMRoute.sol:FLAMMRoute0x312e…0fdaa9src/periphery/FLAMMMaxima.sol:FLAMMMaxima0x4a99…d6259csrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0x5d47…27cc62src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x3bd2…f79a69src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xd53f…ed5983src/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0xac61…6a909dsrc/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0x2291…64f98csrc/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x7a11…58517bsrc/core/mm/CTokenMarketLib.sol:CTokenMarketLib0xfd87…6df060src/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0x4aac…e1aed6src/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x9e50…7eeb41src/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0xc6c9…da2afesrc/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0x739d…5a629fsrc/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0xf128…b16b70src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0xf284…efd526src/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0xd561…60c5a5src/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0xcda6…a4dcf7src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x8423…7adc96src/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0x6fe6…678097src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0x1834…56e060src/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xfaae…2511basrc/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x480f…4e0a81src/hooks/everlong/LeverageLib.sol:LeverageLib0x1b1d…40ad11src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0x5691…f4d380src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0xa0c8…50c3e3src/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xabe4…7426f7

52 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/core/flamm/FLAMMGateLib.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 {
    FLAMMStore, LedgerBoundBreached, DialOutOfEnvelope, LtvStepTooLarge, DialCooldown, LtvLltvGap, LtvFloorBreached,
    PriceUnchecked, InvalidConfig, HookInvalid, VenueFrozen, CustodyOverflow, BasketSet, BasketTokenSet, WAD
} from "src/core/flamm/FLAMMStore.sol";
import {FLAMMLawLib} from "src/core/flamm/FLAMMLawLib.sol";
import {FLAMMKeptLib} from "src/core/flamm/FLAMMKeptLib.sol";
import {
    IHookCapabilities, HOOK_CAP_UNPRICED, HOOK_CAP_TWO_SIDED
} from "src/interfaces/core/flamm/IHookCapabilities.sol";
import {PriceFeed} from "src/core/PriceFeed.sol";
import {IPriceFeed} from "src/interfaces/core/IPriceFeed.sol";
import {IMMRouter, NO_VENUE_LLTV} from "src/interfaces/core/mm/IMMRouter.sol";
import {IHeldRepay} from "src/interfaces/core/mm/IHeldRepay.sol";
import {MMRouterLib} from "src/core/mm/MMRouterLib.sol";
import {
    IFinancingAccount,
    IActionsOf,
    CAN_REPAY,
    CAN_WITHDRAW_SUPPLY,
    CAN_POST_COLLATERAL,
    CAP_ACCRUING_COLLATERAL
} from "src/interfaces/core/mm/IFinancingAccount.sol";

/// @notice The pool's book, its prices and its value. The book is every listed token's four legs: held (the custody
///         the pool owns), supplied, posted and owed, and the spread fee the pool owes the protocol in it past what
///         custody keeps for it. NAV counts the pool asset at par and every other token at its checked price. Every
///         price is a pair's price scale ({frame}), derived from the two tokens' USD prices and never inverted; hooks
///         are never read. The credit law over the book is `FLAMMLawLib`'s.
library FLAMMGateLib {
    /// @dev {custodyBook}'s bit past the pool's eight (`FLAMMStore.S.poolBits`, all taken): the cheap lane is on
    ///      (`FLAMMStore.SWAP_LANE`, from the swap's bits, read in the same word as the token count).
    uint256 private constant BOOK_LANE = uint256(FLAMMStore.SWAP_LANE) << 8;
    /// @notice One token's position and price. `scale` lifts its base units to 18 decimals; `price36` is the pool
    ///         asset's price scale against it, `t` base units per pool-asset base unit scaled by 1e36 (zero: unchecked,
    ///         and zero for the pool asset itself). `partner` is the collateral token of the one live pair that owes
    ///         this token and `pair` that pair (`FLAMMStore.NO_PARTNER`: no live pair owes it; `FLAMMStore.MANY`: two
    ///         or more do, as the per-pair read found them owing).
    /// @dev The spread fee the pool owes the protocol in the token (`FLAMMStore.feeOwed`) is not the pool's: custody
    ///      keeps what it can of it, which `held` leaves out, so the credit law, the room, the plans, the settlement
    ///      and the pro-rata legs never count, spend, lend or post it. `fee` packs it, so a leg keeps its shape
    ///      wherever a book crosses a library:
    ///      - its low 128 bits are the part custody does not hold, a debt NAV and the pro-rata legs net ({feeOf});
    ///      - bits 128-254 the custody kept for the rest (tracked custody is `held` plus it, which a swap writes back,
    ///        {tracked});
    ///      - bit 255 marks, on the pool asset's leg, a book whose custody keeps a fee ({keeps}) and, on token 1's, a
    ///        pool whose cheap lane is on ({laneOn}).
    ///
    ///      A fee may be owed in any token (`FLAMMSwapLib.validate`, the cheap lane's routes): the custody word keeps
    ///      its two tokens', every other token's record its own.
    struct Leg {
        uint256 held;
        uint256 supplied;
        uint256 posted;
        uint256 owed;
        uint256 scale;
        uint256 price36;
        uint8 partner;
        uint8 pair;
        uint256 fee;
    }

    /// @notice Every token's leg, the pool asset first; `usd`, the tokens' checked USD prices as this book was priced
    ///         (zero: unchecked), which is the Router's price vector; `empty`, the venues the position read found
    ///         holding nothing. Where some token has two or more live pairs (`FLAMMStore.POOL_MULTI`), the per-pair
    ///         read (`FLAMMLawLib.splitRead`) adds each such pair's debt (`pairOwed`, by pair index, zero elsewhere),
    ///         the tokens owed at two or more pairs (`many`) and the collateral tokens of those tokens' indebted pairs
    ///         (`backs`, bits 0-15), and from bit `SPLIT_SHIFT` of `backs` the tokens with two or more live pairs
    ///         whatever owes ({split}).
    struct Book {
        Leg[] legs;
        uint256[] usd;
        uint64 empty;
        uint256[] pairOwed;
        uint256 many;
        uint256 backs;
    }

    /// @dev {_budget}'s figures per venue id: the reserves' rooms (`R`), and at each reserve's first venue what its
    ///      releases count (`sum`), its kind number (`kind`) and what the pool lends there (`lent`).
    struct Budget {
        uint256[] R;
        uint256[] sum;
        uint256[] kind;
        uint256[] lent;
    }

    /// @dev `Leg.fee`'s fields: the fee custody does not hold, the custody kept for the rest, and the top bit ({Leg}).
    uint256 internal constant FEE_MASK = (1 << 128) - 1;
    uint256 internal constant KEPT_MASK = (1 << 127) - 1;
    uint256 internal constant LANE_MARK = 1 << 255;

    /// @notice The spread fee owed in a leg's token past what custody holds: a debt of the pool's.
    function feeOf(Leg memory L) internal pure returns (uint256) {
        return L.fee & FEE_MASK;
    }

    /// @notice What custody keeps of the spread fee owed in a leg's token (`fee`'s bits 128-254): never the pool's to
    ///         pay out, post, lend or repay.
    function keptOf(Leg memory L) internal pure returns (uint256) {
        return (L.fee >> 128) & KEPT_MASK;
    }

    /// @notice A leg's tracked custody: what the book reads as the pool's own and what custody keeps of the spread fee
    ///         owed in it (`fee`'s bits 128-254).
    function tracked(Leg memory L) internal pure returns (uint256 h) {
        assembly ("memory-safe") {
            h := add(mload(L), and(shr(128, mload(add(L, 0x100))), 0x7fffffffffffffffffffffffffffffff))
        }
    }

    /// @notice Whether the pool's cheap lane is on, as the book read it (`FLAMMStore.SWAP_LANE`): the top bit of token
    ///         1's `fee`, the book's second leg's ninth word (every pool lists two tokens at least).
    function laneOn(Book memory b) internal pure returns (bool on) {
        assembly ("memory-safe") {
            on := shr(255, mload(add(mload(add(mload(b), 0x40)), 0x100)))
        }
    }

    /// @notice Whether the book kept a spread fee out of some token's custody (its fee pass ran): the top bit of the
    ///         pool asset's `fee`, the book's first leg's ninth word.
    function keeps(Book memory b) internal pure returns (bool on) {
        assembly ("memory-safe") {
            on := shr(255, mload(add(mload(add(mload(b), 0x20)), 0x100)))
        }
    }

    // ------------------------------------------------------------------ price scales and pure laws
    /// @notice A pair's price scale from its tokens' USD prices and scales: base units of the second token per base
    ///         unit of the first, scaled by 1e36, rounded down; zero, an unchecked price, where either price is zero or
    ///         the result would not fit a word. Equal to `pairPrice36` of the two tokens bit for bit, as
    ///         `10^(36 + decimals_b - decimals_a)` is `scaleA * (1e36 / scaleB)`.
    function frame(uint256 usdA, uint256 usdB, uint256 scaleA, uint256 scaleB) internal pure returns (uint256) {
        if (usdA == 0 || usdB == 0) return 0;
        uint256 m = scaleA * (1e36 / scaleB);
        if (usdA / usdB >= type(uint256).max / m) return 0;
        return Math.mulDiv(usdA, m, usdB);
    }

    /// @notice The price scale of pair (`a` -> `c`) at `b`'s prices; the pool asset's against a token is its leg's
    ///         `price36`.
    function frameOf(Book memory b, uint256 a, uint256 c) internal pure returns (uint256) {
        if (a == 0) return b.legs[c].price36;
        return frame(b.usd[a], b.usd[c], b.legs[a].scale, b.legs[c].scale);
    }

    /// @notice A token's net debt `U`: what it owes over what it holds and supplies, its base units; zero for a
    ///         surplus. Posted holdings of a debt token never net its debt.
    function netDebt(Leg memory L) internal pure returns (uint256) {
        uint256 h = L.held + L.supplied;
        return L.owed > h ? L.owed - h : 0;
    }

    /// @notice A token's backing `G`: what it holds and posts. Its supply is not backing: withdrawing it waits for the
    ///         lender's cash.
    function backing(Leg memory L) internal pure returns (uint256) {
        return L.held + L.posted;
    }

    /// @notice Distance to liquidation at the borrow pin, `1 - ltv/lltv`, the quotient rounded up.
    function structuralDistWad(uint256 ltvWad, uint256 lltvWad) internal pure returns (uint256) {
        if (lltvWad == 0 || ltvWad >= lltvWad) return 0;
        return WAD - Math.mulDiv(ltvWad, WAD, lltvWad, Math.Rounding.Up);
    }

    /// @notice The posting law: collateral for `grossDebt` of a debt token at its pair's `ltvWad` and price scale
    ///         `price36`, base units of the collateral token, rounded up.
    function requiredPosted(uint256 grossDebt, uint256 ltvWad, uint256 price36) internal pure returns (uint256) {
        if (grossDebt == 0) return 0;
        return Math.ceilDiv(Math.mulDiv(grossDebt, 1e54, price36, Math.Rounding.Up), ltvWad);
    }

    /// @notice NAV in pool-asset base units: the pool asset's legs at par and every other token's at its `price36`,
    ///         holdings rounded down and debt up, the spread fee owed to the protocol a debt, saturating at zero.
    ///         Reverts `PriceUnchecked` where a token with any leg is unchecked; an idle token needs no price.
    function navAt(Book memory b) internal pure returns (uint256) {
        Leg memory L = b.legs[0];
        uint256 plus = L.held + L.supplied + L.posted;
        uint256 minus = L.owed + feeOf(L);
        for (uint256 t = 1; t < b.legs.length; ++t) {
            L = b.legs[t];
            uint256 pos = L.held + L.supplied + L.posted;
            uint256 neg = L.owed + feeOf(L);
            if (L.price36 == 0) {
                if ((pos | neg) != 0) revert PriceUnchecked();
                continue;
            }
            plus += Math.mulDiv(pos, 1e36, L.price36);
            minus += Math.mulDiv(neg, 1e36, L.price36, Math.Rounding.Up);
        }
        return plus > minus ? plus - minus : 0;
    }

    /// @notice Whether `navAt(b)` reads: no token past the pool asset holds a leg at an unchecked price, the spread fee
    ///         past custody included.
    function checkedAt(Book memory b) internal pure returns (bool) {
        for (uint256 t = 1; t < b.legs.length; ++t) {
            Leg memory L = b.legs[t];
            if (L.price36 == 0 && (L.held | L.supplied | L.posted | L.owed | feeOf(L)) != 0) return false;
        }
        return true;
    }

    /// @notice Whether the curator's fee mark reads at `b`, as {tryMarkedTotalAssets} reads it: NAV reads
    ///         ({checkedAt}); on a pool whose cheap lane is on and whose deposit basket is set, the prices of the
    ///         tokens the basket holds are checked ({_inBasket}: token 1, its entry nonzero or not, and each later
    ///         token whose entry is nonzero), which its value needs even where a token holds nothing; and while a
    ///         forfeit record is pending, every token it holds units of is priced, held or not (the record is read only
    ///         then). One pass over the tokens checks both. An entry while a fee rate is on needs it, and so does NAV
    ///         ({totalAssets}): a skim that reads no fee mark leaves a gain unpaid, which the next one would charge on
    ///         the entrant's shares too.
    function markedAt(FLAMMStore.S storage $, Book memory b) internal view returns (bool) {
        if (!checkedAt(b)) return false;
        bool basket = laneOn(b) && $.basketPool != 0;
        bool forfeit = $.poolBits & FLAMMStore.POOL_FORFEIT != 0;
        if (!basket && !forfeit) return true;
        for (uint256 t = 1; t < b.legs.length; ++t) {
            if (b.legs[t].price36 != 0) continue;
            if (basket && (t == 1 || $.basketTok[t] != 0)) return false;
            if (forfeit && $.forfeited[t] != 0) return false;
        }
        return true;
    }

    /// @notice Whether any token is owed.
    function owes(Book memory b) internal pure returns (bool) {
        if (b.legs.length == 2) return (b.legs[0].owed | b.legs[1].owed) != 0;
        for (uint256 t; t < b.legs.length; ++t) {
            if (b.legs[t].owed != 0) return true;
        }
        return false;
    }

    /// @dev `Book.backs`' first bit of the tokens with two or more live pairs ({split}).
    uint256 internal constant SPLIT_SHIFT = 128;

    /// @notice Whether token `t` has two or more live pairs (`FLAMMStore.TokenCfg.partner` is `MANY`), as the per-pair
    ///         read records it: a token owed at one of them reads as that pair's, yet its custody may be what another
    ///         live pair pays its sellers from. False on a book read whole, where no token has two.
    function split(Book memory b, uint256 t) internal pure returns (bool) {
        return (b.backs >> (SPLIT_SHIFT + t)) & 1 != 0;
    }

    /// @notice Whether token `a` backs a debt: some token owed at a pair whose collateral is `a`. Of two tokens only
    ///         the other can be.
    function backsDebt(Book memory b, uint256 a) internal pure returns (bool) {
        if (b.legs.length == 2) {
            Leg memory O = b.legs[1 - a];
            return O.partner == a && O.owed != 0;
        }
        if ((b.backs >> a) & 1 != 0) return true;
        for (uint256 t; t < b.legs.length; ++t) {
            Leg memory L = b.legs[t];
            if (L.partner == a && L.owed != 0) return true;
        }
        return false;
    }

    /// @notice Whether token `a` backs a debt of a token other than `x`: some token but `x` owed at a pair whose
    ///         collateral is `a`.
    function backsBesides(FLAMMStore.S storage $, Book memory b, uint256 a, uint256 x) internal view returns (bool) {
        uint256 n = b.legs.length;
        for (uint256 t; t < n; ++t) {
            Leg memory L = b.legs[t];
            if (t != x && L.partner == a && L.owed != 0) return true;
        }
        for (uint256 r; r < b.pairOwed.length; ++r) {
            if (b.pairOwed[r] == 0) continue;
            FLAMMStore.PairCfg storage pc = $.pairs[r];
            if (pc.coll == a && pc.debt != x) return true;
        }
        return false;
    }

    // ------------------------------------------------------------------ the room
    /// @notice {roomOf}'s `band` where the input is not the pair's collateral: so wide that the input is credited
    ///         nothing (`1e36 / (WAD + UNCREDITED)` is zero).
    uint256 internal constant UNCREDITED = 1 << 255;

    /// @notice The units a lender can read a new borrow back high at one venue: its debt shares rounded up, then their
    ///         assets rounded up again. Aave from 3.4 on reads up to `ceil(index)` units high, its borrow index in
    ///         units of one: two while the index is under 2 RAY, which no reserve the pool may list nears for years; a
    ///         Compound-style market or Morpho up to one. Past it, a payout at the room's edge reads a unit over and
    ///         the swap's law withdraws lent backing or reverts (`LedgerBoundBreached`): the quote may fill where the
    ///         swap reverts, the law is never breached. The entry maxima allow it per borrow leg after the first at one
    ///         pair's venues (`FLAMMMaxima`, periphery): past 2 RAY, an entry sized at its maximum with two legs at
    ///         such a reserve can be refused at the pair's debt cap (`DebtCapExceeded`), never let past it.
    uint256 internal constant READ_BACK_UNITS = 2;

    /// @notice What the pool can pay of `y` borrowing it at pair `p` (`x` -> `y`), native units of `y`, shaved by the
    ///         pair's epsilon.
    /// @dev - The head left at `x` over the other debts it backs (each FLEX pair there at its gross, each at its own
    ///        LTV scaled to this pair's), less `y`'s debt at `p` over what it holds and supplies or plus its surplus,
    ///        lifted by the incoming collateral's credit, at the pair's price scale.
    ///      - That credit is the pair's `phi`, at most `1 / (1 + band)`, as a fill inside the swap's band (`band`,
    ///        `FLAMMSwapLib.validate`) may bring an input worth as little as that share of its output, which the law
    ///        after the draw counts at its worth (zero caps nothing; {UNCREDITED}, where the input is not `x`, credits
    ///        nothing).
    ///      - `lent` of `x`'s supply counts beside what it holds and posts: a borrow withdraws what the pin needs of it
    ///        and posts it first; the law itself never counts supply.
    ///      - `cleared`, a crossing's input (`type(uint256).max`: none), has its whole debt repaid before the draw:
    ///        where it is `x` that debt comes off the head one for one, the input repaying it before what is left of it
    ///        backs the draw; where it is another token `x` backs, that debt leaves those `x` backs.
    ///      - Where `y` owes at another pair (so it owes at two or more once it borrows at `p`), its supply counts only
    ///        as far as its lenders can return it now, and every pair it owes at must be within its cap with `y`
    ///        charged at its gross; else the room is that cash less those pairs' excess, which passes any cash where
    ///        the other debts alone overload a backing token of `y`'s pairs, or, on a token owed at two or more pairs
    ///        whose cash covers all it owes, that cash over all it owes.
    ///      - Where the other debts overload `x`, the room is at least the cash `y` holds and supplies over all it
    ///        owes.
    ///      - Where `x` holds nothing and backs no debt, there is no head, and the room, `y`'s own surplus, reads no
    ///        price: an unpriced `x` refuses (`PriceUnchecked`) only where it holds or backs.
    function roomOf(
        FLAMMStore.S storage $,
        Book memory b,
        uint256 p,
        uint256 band,
        uint256 lent,
        uint256 cleared
    ) internal view returns (uint256) {
        FLAMMStore.PairCfg storage pc = $.pairs[p];
        (uint256 x, uint256 y) = (pc.coll, pc.debt);
        Leg memory Ly = b.legs[y];
        (uint256 ltv, uint256 phi, uint256 eps) = (pc.ltvWad, pc.phiWad, pc.roomEpsilonWad);
        // a token's band, a `uint64`, or {UNCREDITED}: the sum cannot overflow
        unchecked {
            uint256 c = 1e36 / (WAD + band);
            if (c < phi) phi = c;
        }
        uint256 price = frameOf(b, x, y);
        if (price == 0) {
            // no head: the room is `y`'s own surplus, which cancels the price scale
            Leg memory Lx = b.legs[x];
            if ((Lx.held | Lx.supplied | Lx.posted) != 0 || backsDebt(b, x)) revert PriceUnchecked();
            price = 1e36;
        }
        uint256 h = Ly.held + Ly.supplied;
        uint256 dp = Ly.owed;
        // `y` owes at a pair other than `p`: it owes at two or more once it borrows here
        if (dp != 0 && (Ly.partner == FLAMMStore.MANY || Ly.pair != p)) {
            dp = Ly.partner == FLAMMStore.MANY ? b.pairOwed[p] : 0;
            // the supply it nets counts only as far as its lenders can return it now: the draw's funding withdraws
            // that first, and the law sizes the other FLEX pairs at `x` against the rest
            uint256 e;
            (e, h) = FLAMMLawLib.excessAfter($, b, y);
            if (e != 0) {
                if (Ly.partner == FLAMMStore.MANY && Ly.owed <= h) return h - Ly.owed;
                return h > e ? h - e : 0;
            }
        }
        uint256 head = (backing(b.legs[x]) + lent) * ltv;
        // the other debts `x` backs, each at its pair's price scale, rounded up, and at this pair's LTV
        uint256 other = cleared == x ? b.legs[x].owed * ltv : 0;
        for (uint256 t; t < b.legs.length; ++t) {
            Leg memory L = b.legs[t];
            if (t == y || t == cleared || L.partner != x) continue;
            uint256 u = netDebt(L);
            if (u == 0) continue;
            other += scaled(b, x, t, u, $.pairs[L.pair].ltvWad, ltv);
        }
        if (b.many != 0) other += FLAMMLawLib.flexAt($, b, x, y, ltv);
        // past the head, the other debts first net `y`'s surplus; never on two tokens without a crossing
        uint256 deficit = other > head ? other - head : 0;
        head = deficit != 0 ? 0 : head - other;
        if (dp > h) {
            uint256 ny = Math.mulDiv(dp - h, 1e54, price, Math.Rounding.Up);
            head = head > ny ? head - ny : 0;
        } else if (h > dp) {
            uint256 sy = Math.mulDiv(h - dp, 1e54, price);
            head = sy > deficit ? head + sy - deficit : 0;
        }
        uint256 raw = Math.mulDiv(head, price, 1e54 / Ly.scale);
        uint256 cut;
        unchecked {
            // lifted: the incoming collateral is credited at `phi`, and the envelope holds `ltv < 1` and `phi <= 1`, so
            // `ltv * phi` is under one; then shaved by the epsilon, under `MAX_ROOM_EPSILON_WAD` where it is set
            raw = Math.mulDiv(raw, WAD, WAD - Math.mulDiv(ltv, phi, WAD));
            cut = Math.mulDiv(raw, eps, WAD);
            raw -= cut;
        }
        uint256 room = raw / Ly.scale;
        // A borrow reads back up to `READ_BACK_UNITS` high at each venue it draws at (the lender's share rounding):
        // where the epsilon's shave is under that per venue of the pair, that per venue comes off instead.
        uint256 k;
        for (uint256 m = pc.venues; m != 0; m &= m - 1) k += READ_BACK_UNITS;
        if (cut < k * Ly.scale) room = room > k ? room - k : 0;
        // the cash `y` holds and supplies over all it owes pays out with no new debt
        if (deficit != 0 && h > Ly.owed && room < h - Ly.owed) room = h - Ly.owed;
        return room;
    }

    /// @notice `ceil(u * 1e54 / P(x -> t))` at LTV `lt`, rescaled to `ltv`, rounded up: a debt `u` of token `t` in the
    ///         room's head units at backing token `x`.
    function scaled(Book memory b, uint256 x, uint256 t, uint256 u, uint256 lt, uint256 ltv) internal pure returns (uint256) {
        uint256 pt = frameOf(b, x, t);
        if (pt == 0) revert PriceUnchecked();
        uint256 d = Math.mulDiv(u, 1e54, pt, Math.Rounding.Up);
        return lt == ltv ? d : Math.mulDiv(d, ltv, lt, Math.Rounding.Up);
    }

    // ------------------------------------------------------------------ the book
    /// @notice The pool's positions, price-free: its custody, and the Router's book in one read (none, and not read,
    ///         with no live venue), skipping the idle venues. Where some token has two or more live pairs
    ///         (`FLAMMStore.POOL_MULTI`), the per-pair read instead (`FLAMMLawLib.splitRead`), each such pair's debt
    ///         apart.
    function bookOf(FLAMMStore.S storage $) internal view returns (Book memory b) {
        b = custodyBook($);
        if ($.noLiveVenue) return b;
        if ($.poolBits & FLAMMStore.POOL_MULTI != 0) _adopt(b, FLAMMLawLib.splitRead());
        else bookRead($, b, $.idleVenues, false, new uint256[](0), 0);
    }

    /// @notice {bookOf} as a library entry, for a caller that holds no room for its code (the flows).
    function book(FLAMMStore.S storage $) public view returns (Book memory) {
        return bookOf($);
    }

    /// @dev The per-pair read's words (`FLAMMLawLib.splitRead`) into `b`: each token's venue legs, partner and pair,
    ///      the empty venues, the `MANY` tokens and their backs, and each pair's debt, which `b` takes in place.
    function _adopt(Book memory b, uint256[] memory w) private pure {
        uint256 n = b.legs.length;
        for (uint256 t; t < n; ++t) {
            Leg memory L = b.legs[t];
            uint256 k = 5 * t;
            (L.supplied, L.posted, L.owed, L.partner, L.pair) = (w[k], w[k + 1], w[k + 2], uint8(w[k + 3]), uint8(w[k + 4]));
        }
        uint256 j = 5 * n;
        (b.empty, b.many, b.backs) = (uint64(w[j]), w[j + 1], w[j + 2]);
        // the words past them are the pairs' debts: their array takes the word before them as its length
        uint256[] memory pairOwed;
        uint256 m = w.length - j - 3;
        assembly ("memory-safe") {
            pairOwed := add(w, shl(5, add(j, 3)))
            mstore(pairOwed, m)
        }
        b.pairOwed = pairOwed;
    }

    /// @notice {bookOf} before its venue read: each token's custody, scale and credit line, and the spread fee the pool
    ///         owes the protocol in it (`FLAMMStore.feeOwed`'s rule), which custody keeps as far as it holds it. The
    ///         pool asset's credit line is read only while a pair that can owe it is listed, and the fees only while
    ///         some fee is owed or the cheap lane is on.
    function custodyBook(FLAMMStore.S storage $) internal view returns (Book memory b) {
        uint256 n = $.tokenCount;
        b.legs = new Leg[](n);
        b.usd = new uint256[](n);
        (uint256 held0, uint256 held1) = ($.held0, $.held1);
        // the pool's bits, and past their eight the cheap lane's birth bit (`BOOK_LANE`), which the swap's bits hold
        uint256 bits = uint256($.poolBits) | (uint256($.swapBits & FLAMMStore.SWAP_LANE) << 8);
        for (uint256 t; t < n; ++t) {
            Leg memory L = b.legs[t];
            if (t == 0) {
                (L.held, L.scale, L.partner) = (held0, $.shareScale, FLAMMStore.NO_PARTNER);
                // only a pair outside the pool asset's own (0 -> t) pairs can owe the pool asset
                if (bits & FLAMMStore.POOL_TWO_SIDED != 0) {
                    FLAMMStore.TokenCfg storage c0 = $.tokens[0];
                    (L.partner, L.pair) = (c0.partner, c0.pairId);
                }
            } else {
                FLAMMStore.TokenCfg storage c = $.tokens[t];
                (L.partner, L.pair, L.scale) = (c.partner, c.pairId, c.scale);
                L.held = t == 1 ? held1 : c.heldRest;
            }
        }
        if (bits & (FLAMMStore.POOL_SPREAD_OWED | BOOK_LANE) != 0) _keepFees($, b, bits);
    }

    /// @dev {custodyBook}'s fee pass, where a fee may be owed: each token's fee (`FLAMMStore.feeOwed`'s rule), the
    ///      pool asset's and token 1's always and a later token's while some fee is recorded, kept out of its `held` as
    ///      far as custody holds it, into its `fee` ({Leg}); the top bits. On a book of three or more tokens with some
    ///      fee recorded, every read reads each later token's record too, a cold word a token in each flow.
    function _keepFees(FLAMMStore.S storage $, Book memory b, uint256 bits) private view {
        bool lane = bits & BOOK_LANE != 0;
        bool owed = bits & FLAMMStore.POOL_SPREAD_OWED != 0;
        uint256 n = owed ? b.legs.length : 2;
        for (uint256 t; t < n; ++t) {
            Leg memory L = b.legs[t];
            uint256 f;
            if (owed) f = $.spreadFeeOwed[t];
            if (t == 1 && lane) f += $.laneWord & FLAMMStore.LANE_ACCRUED_MASK;
            uint256 k = f < L.held ? f : L.held;
            if (k > KEPT_MASK || f - k > FEE_MASK) revert CustodyOverflow();
            (L.held, L.fee) = (L.held - k, (f - k) | (k << 128));
        }
        b.legs[0].fee |= LANE_MARK;
        if (lane) b.legs[1].fee |= LANE_MARK;
    }

    /// @notice `IMMRouter.book(address(this), skip)`, called as the high-level call is (all gas, the Router's revert
    ///         bubbled) and read in place, without the decoder's three array copies: the answer must hold its head and
    ///         three arrays of `n` words, one per leg of `b` (one per listed token), else it reverts empty. Copies each
    ///         token's supplied, posted and owed words into its leg, or adds them to it with `adding`; the owed array
    ///         into `owed` from word `from` (none where `owed` is empty); the empty-venue mask into `b` (or-ed in with
    ///         `adding`). The answer is read past the free memory pointer, which it leaves where it was, as nothing
    ///         reads it after. The pool's one reader of the Router's book: the per-pair read takes it too
    ///         (`FLAMMLawLib.splitRead`).
    function bookRead(
        FLAMMStore.S storage $,
        Book memory b,
        uint256 skip,
        bool adding,
        uint256[] memory owed,
        uint256 from
    ) internal view {
        address router = address($.router);
        bytes4 sel = IMMRouter.book.selector;
        assembly ("memory-safe") {
            let legs := mload(b)
            let n := mload(legs)
            let m := mload(0x40)
            mstore(m, sel)
            mstore(add(m, 0x04), address())
            mstore(add(m, 0x24), skip)
            if iszero(staticcall(gas(), router, m, 0x44, 0, 0)) {
                returndatacopy(m, 0, returndatasize())
                revert(m, returndatasize())
            }
            let size := returndatasize()
            // the head (three offsets and the empty mask), then each array: its length and its words
            let span := shl(5, add(n, 1))
            if lt(size, add(0x80, mul(3, span))) { revert(0, 0) }
            returndatacopy(m, 0, size)
            let a := mload(m)
            let s := mload(add(m, 0x20))
            let o := mload(add(m, 0x40))
            let e := mload(add(m, 0x60))
            let last := sub(size, span)
            if or(or(or(gt(a, last), gt(s, last)), gt(o, last)), gt(e, 0xffffffffffffffff)) { revert(0, 0) }
            a := add(m, a)
            s := add(m, s)
            o := add(m, o)
            if iszero(and(and(eq(mload(a), n), eq(mload(s), n)), eq(mload(o), n))) { revert(0, 0) }
            // token `t`'s word sits `k = 32 * (t + 1)` past each array's length word, as its leg's pointer in `legs`
            // `adding` is 0 or 1: each word is the read, or the read added to what the leg holds
            for { let k := 0x20 } lt(k, span) { k := add(k, 0x20) } {
                let L := mload(add(legs, k))
                mstore(add(L, 0x20), add(mul(adding, mload(add(L, 0x20))), mload(add(s, k)))) // supplied
                mstore(add(L, 0x40), add(mul(adding, mload(add(L, 0x40))), mload(add(a, k)))) // posted
                mstore(add(L, 0x60), add(mul(adding, mload(add(L, 0x60))), mload(add(o, k)))) // owed
            }
            mstore(add(b, 0x40), or(mul(adding, mload(add(b, 0x40))), e)) // empty
            if mload(owed) { mcopy(add(add(owed, 0x20), shl(5, from)), add(o, 0x20), shl(5, n)) }
        }
    }

    /// @notice Refreshes `b`'s venue legs with a new read of the Router's book, its custody and prices as they stand:
    ///         a flow's moves at the Router, read once after them. Returns the idle record the read skipped, read
    ///         whether or not a venue is live, for {markIdleFrom}.
    /// @dev Keeping `b`'s prices assumes no price moves inside a flow: Chainlink transmits are permissioned, the
    ///      sequencer flag moves at a block's start, and `PriceFeed.executeOracle`, external with no caller check, is
    ///      called by no code of the pool's. That holds while listed tokens carry no transfer callback and the hooks a
    ///      swap calls make no such call (its committed fill, `IPairHook.fillPair`, is a call, not a static one):
    ///      either could run it between a flow's read and its settlement.
    function reread(FLAMMStore.S storage $, Book memory b) internal view returns (uint32 idle) {
        idle = $.idleVenues;
        if ($.noLiveVenue) return idle;
        if ($.poolBits & FLAMMStore.POOL_MULTI == 0) bookRead($, b, idle, false, new uint256[](0), 0);
        else _adopt(b, FLAMMLawLib.splitRead());
    }

    /// @notice Records the venues in `empty`, which a read found holding nothing, as idle (`FLAMMStore.S.idleVenues`),
    ///         from `idle`: the idle record as last read, which nothing has written since. Later reads skip them:
    ///         nothing but the pool's own call opens a position the Router recognizes there.
    function markIdleFrom(FLAMMStore.S storage $, uint32 idle, uint64 empty) internal {
        uint32 next = idle | uint32(empty);
        if (next != idle) $.idleVenues = next;
    }

    /// @notice Clears the idle bits of the venues in `mask` before a call that can open a position at one of them.
    function wake(FLAMMStore.S storage $, uint256 mask) internal {
        uint32 idle = $.idleVenues;
        if (idle & mask != 0) $.idleVenues = idle & ~uint32(mask);
    }

    /// @notice Sets token `t`'s debt-free flag (`FLAMMStore.TokenCfg.debtFree`) where `b`, a read taken after a flow,
    ///         shows it owes nothing; never clears it. Kept only for a token some live pair owes. A read leaves a
    ///         fenced venue out, so a flag set during a fence can stand on that venue's debt: the fence's lift clears
    ///         it where the venue owes (`FLAMMFenceLib.liftFence`).
    function markDebtFreeOf(FLAMMStore.S storage $, Book memory b, uint256 t) internal {
        Leg memory L = b.legs[t];
        if (L.partner == FLAMMStore.NO_PARTNER || L.owed != 0) return;
        FLAMMStore.TokenCfg storage c = $.tokens[t];
        if (!c.debtFree) c.debtFree = true;
    }

    /// @notice What `b`, a read taken after a flow, proves: {markDebtFreeOf} for every token, then the venues it found
    ///         holding nothing recorded as idle ({markIdleFrom}), so later reads skip them.
    function markRead(FLAMMStore.S storage $, Book memory b) internal {
        for (uint256 t; t < b.legs.length; ++t) {
            markDebtFreeOf($, b, t);
        }
        markIdleFrom($, $.idleVenues, b.empty);
    }

    /// @notice Clears pair `p`'s proof (`FLAMMStore.S.pairsFree`) for a draw at it, on a pool whose cheap lane is on,
    ///         before the pool's lock lifts: only a fresh position read, anyone's, sets it again
    ///         (`FLAMMLane.proveDebtFree`).
    function drawAt(FLAMMStore.S storage $, uint256 p) internal {
        uint32 free = $.pairsFree;
        if ((free >> p) & 1 != 0) $.pairsFree = free & ~uint32(1 << p);
    }

    /// @notice `FLAMM.proveDebtFree`: {markRead} of a fresh position read. A pool whose cheap lane is on proves its
    ///         pairs too, through `FLAMMLane.proveDebtFree`.
    function proveDebtFree(FLAMMStore.S storage $) public {
        markRead($, bookOf($));
    }

    /// @notice Token `t`'s four legs: custody and the Router's book (`IFLAMM.position`).
    function positionOf(FLAMMStore.S storage $, uint8 t)
        public
        view
        returns (uint256 held, uint256 supplied, uint256 posted, uint256 owed)
    {
        FLAMMStore.checkToken($, t);
        Leg memory L = bookOf($).legs[t];
        return (L.held, L.supplied, L.posted, L.owed);
    }

    // ------------------------------------------------------------------ prices
    /// @notice Prices `b` with no reverting read: the pool asset and token 1 from one read of their pair, every other
    ///         token from its own; an unchecked token reads zero, which only fails a caller that needs it (a position,
    ///         a draw, NAV). Where the pair does not answer and a token past it is listed, the pool asset is read
    ///         alone. A pool with no band reads no price: its book stays unpriced, so its NAV is unchecked wherever it
    ///         holds a token past the pool asset, and no fee charges.
    function priceIn(FLAMMStore.S storage $, Book memory b) internal view {
        if (FLAMMStore.bandOff($)) return;
        IPriceFeed feed = $.priceFeed;
        (bool ok, uint256 u0, uint256 u1,) = feed.peekPair($.poolAsset, $.tokens[1].token);
        if (ok) (b.usd[0], b.usd[1]) = (u0, u1);
        _priceRest($, b, false, !ok);
        frameAll(b);
    }

    /// @notice `priceIn` at the hook pair's two prices as the caller read them with the reverting `pair`: every token
    ///         priced, or with `skipIdle` every one holding a leg. An observation's read, which also takes the pair's
    ///         stamp.
    function priceInAt(FLAMMStore.S storage $, Book memory b, uint256 u0, uint256 u1, bool skipIdle) internal view {
        (b.usd[0], b.usd[1]) = (u0, u1);
        _priceRest($, b, skipIdle, false);
        frameAll(b);
    }

    /// @dev Each token past the hook pair from its own non-reverting read (`skipIdle`: only one holding a leg, as the
    ///      main swap moves none of them); with `poolAssetToo`, the pool asset's alone first, where the hook pair did
    ///      not answer and a token past it is read.
    function _priceRest(FLAMMStore.S storage $, Book memory b, bool skipIdle, bool poolAssetToo) private view {
        uint256 n = b.legs.length;
        if (n <= 2) return;
        IPriceFeed feed = $.priceFeed;
        if (poolAssetToo) {
            (bool ok0, uint256 v0,) = feed.peekUsd($.poolAsset);
            if (ok0) b.usd[0] = v0;
        }
        for (uint256 t = 2; t < n; ++t) {
            Leg memory L = b.legs[t];
            if (skipIdle && (L.held | L.supplied | L.posted | L.owed) == 0) continue;
            (bool ok, uint256 v,) = feed.peekUsd($.tokens[t].token);
            if (ok) b.usd[t] = v;
        }
    }

    /// @notice Every token's `price36`, the pool asset's price scale against it, from the book's USD prices.
    function frameAll(Book memory b) internal pure {
        (uint256 s0, uint256 u0) = (b.legs[0].scale, b.usd[0]);
        for (uint256 t = 1; t < b.legs.length; ++t) {
            Leg memory L = b.legs[t];
            L.price36 = frame(u0, b.usd[t], s0, L.scale);
        }
    }

    /// @notice `IPriceFeed.pair`, read as the high-level call reads it, without the decoder's copies: the feed's revert
    ///         bubbles up, and an answer shorter than three words or a stamp past uint48 reverts empty.
    function pairRead(address feed, address base, address quote)
        internal
        view
        returns (uint256 baseUsd, uint256 quoteUsd, uint256 observedAt)
    {
        bytes4 sel = IPriceFeed.pair.selector;
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, sel)
            mstore(add(m, 0x04), base)
            mstore(add(m, 0x24), quote)
            if iszero(staticcall(gas(), feed, m, 0x44, m, 0x60)) {
                returndatacopy(m, 0x00, returndatasize())
                revert(m, returndatasize())
            }
            observedAt := mload(add(m, 0x40))
            if or(lt(returndatasize(), 0x60), gt(observedAt, 0xffffffffffff)) { revert(0x00, 0x00) }
            baseUsd := mload(m)
            quoteUsd := mload(add(m, 0x20))
        }
    }

    /// @notice Whether `usd`, a checked price of `token`, sits within its peg band: `PriceFeed.pegOk`'s rule at a price
    ///         already read, `pegBandWad == 0 || |usd - 1e18| <= pegBandWad`, the band read as the high-level call
    ///         reads it (the feed's revert bubbles up; an answer under a word reverts empty).
    function onPeg(FLAMMStore.S storage $, address token, uint256 usd) internal view returns (bool) {
        uint256 band;
        bytes4 sel = IPriceFeed.pegBandWad.selector;
        address feed = address($.priceFeed);
        assembly ("memory-safe") {
            mstore(0x00, sel)
            mstore(0x04, token)
            if iszero(staticcall(gas(), feed, 0x00, 0x24, 0x00, 0x20)) {
                let m := mload(0x40)
                returndatacopy(m, 0x00, returndatasize())
                revert(m, returndatasize())
            }
            if lt(returndatasize(), 0x20) { revert(0x00, 0x00) }
            band := mload(0x00)
        }
        return band == 0 || (usd > WAD ? usd - WAD : WAD - usd) <= band;
    }

    /// @notice The live pair (`a` -> `c`): `c`'s one pair where the book reads its partner as `a`; from the pair masks
    ///         where some token has two or more pairs; else `FLAMMStore.NO_PAIR`.
    function pairOf(FLAMMStore.S storage $, Book memory b, uint256 a, uint256 c) internal view returns (uint8) {
        Leg memory Lc = b.legs[c];
        if (Lc.partner == a) return Lc.pair;
        if ($.poolBits & FLAMMStore.POOL_MULTI == 0) return FLAMMStore.NO_PAIR;
        (uint256 owing,) = FLAMMStore.lanes($, c);
        (, uint256 posting) = FLAMMStore.lanes($, a);
        uint256 m = owing & posting;
        return m == 0 ? FLAMMStore.NO_PAIR : uint8(Math.log2(m & (~m + 1)));
    }

    /// @notice The priced book: positions plus every token's price.
    function priced(FLAMMStore.S storage $) public view returns (Book memory b) {
        b = bookOf($);
        priceIn($, b);
    }

    /// @notice The Router's price vector for pair `p` alone, from one read of its two tokens: their USD prices, zero
    ///         elsewhere. Reverts `PriceUnchecked` where the pair's price is unchecked.
    function pairUsd(FLAMMStore.S storage $, uint8 p) public view returns (uint256[] memory usd) {
        (uint8 a, uint8 c) = ($.pairs[p].coll, $.pairs[p].debt);
        usd = new uint256[]($.tokenCount);
        (bool ok, uint256 ua, uint256 uc,) = $.priceFeed.peekPair(FLAMMStore.tokenOf($, a), FLAMMStore.tokenOf($, c));
        if (!ok || frame(ua, uc, _scale($, a), _scale($, c)) == 0) revert PriceUnchecked();
        (usd[a], usd[c]) = (ua, uc);
    }

    /// @dev Token `t`'s scale: the pool asset's from the first word.
    function _scale(FLAMMStore.S storage $, uint256 t) private view returns (uint256) {
        return t == 0 ? $.shareScale : $.tokens[t].scale;
    }

    /// @notice What the venues lending token `a` can return of the pool's supply of it now, at most `cap`: the
    ///         withdraw phase of a plan on `a`'s own pair at no price, which borrows nothing
    ///         (`IMMRouter.fundingCeiling`). A swap's plan bounds a draw's lent backing and a payout's supply by it,
    ///         so no fill counts what the lenders cannot return.
    function withdrawable(FLAMMStore.S storage $, uint256 a, uint256 cap) internal view returns (uint256) {
        FLAMMStore.TokenCfg storage c = $.tokens[a];
        if (c.partner == FLAMMStore.NO_PARTNER) return 0;
        // the withdraw phase reads every venue lending `a`, whichever live pair of `a`'s names it
        return $.router.fundingCeiling(address(this), c.pairId, cap, 0, new uint256[]($.tokenCount), 0);
    }

    /// @notice Whether venue `id` refuses a repay now (a cleared `CAN_REPAY`): only a kind that can refuse an action is
    ///         asked (`FLAMMStore.S.gatedVenues`), and for its actions alone (`IMMRouter.venueActions`, its capacity's
    ///         `actions` in the same state). The Router's cascade passes such a venue over, and so does every repay the
    ///         pool sends to one venue, and every count of what those repays free; but at the Aave V3 kind while only
    ///         the collateral reserve's configuration word cannot be read, the cascade's gate reads the repay alone and
    ///         repays there (`IActionsOf`).
    function repayRefused(FLAMMStore.S storage $, uint256 id) internal view returns (bool) {
        return ($.gatedVenues >> id) & 1 != 0 && $.router.venueActions(address(this), uint16(id)) & CAN_REPAY == 0;
    }

    /// @notice The debt at the first venue that owes token `x` and refuses repays now ({repayRefused}), zero where
    ///         none: a swap whose input clears its debt clears none there, as its repay passes such a venue over.
    function refusedDebt(FLAMMStore.S storage $, uint256 x) public view returns (uint256 d) {
        uint256 gated = $.gatedVenues & ~uint256($.retiredVenues);
        if (gated == 0) return 0;
        for (uint256 q; q < $.pairCount; ++q) {
            FLAMMStore.PairCfg storage c = $.pairs[q];
            if (c.debt != x) continue;
            uint256 mask = c.venues & gated;
            for (uint256 i; mask >> i != 0; ++i) {
                if ((mask >> i) & 1 == 0 || !repayRefused($, i)) continue;
                (,,,, d) = $.router.venuePosition(address(this), uint16(i));
                if (d != 0) return d;
            }
        }
    }

    /// @notice What token `y`'s live venues can release now of the collateral the Router recognizes there
    ///         ({releasableOf}), those sharing one reserve's cash within the cash they leave for releases there: what
    ///         a crossing's repay frees of it where `y` backs no other debt. The shared venues count as their reserves'
    ///         fit ({sharedFit}), which reads each one's release as {releasableOf} does (every kind that shares a
    ///         reserve can refuse an action, and one that cannot reports all its collateral releasable), so only the
    ///         others are walked.
    function postedReleasable(FLAMMStore.S storage $, uint256 y) public view returns (uint256 sum) {
        (sum,,) = sharedFit($, y, 0);
        uint256 live = ~uint256($.retiredVenues | $.sharedVenues);
        for (uint256 q; q < $.pairCount; ++q) {
            FLAMMStore.PairCfg storage c = $.pairs[q];
            if (c.coll != y) continue;
            uint256 mask = c.venues & live;
            for (uint256 i; mask >> i != 0; ++i) {
                if ((mask >> i) & 1 == 0) continue;
                (, uint256 rec,,,) = $.router.venuePosition(address(this), uint16(i));
                sum += releasableOf($, i, rec);
            }
        }
    }

    /// @notice What a cover's repay of `left` frees of token `y` for the swap's reclaim and release, as the swap sizes
    ///         it, for the quote (`FLAMMPairQuoteLib`), counted up to `cap`.
    /// @dev - At cover pair `pair`'s venues (`FLAMMStore.NO_PAIR`: none): all a venue there that owes nothing can
    ///        release (the swap's reclaim releases it), and at the indebted ones what the repay frees: the repay (all
    ///        the custody of the input with it, the input alone where the input is owed at two or more pairs, `many`)
    ///        walked as the swap sends it, the pair's venues in index order with `many`, else the Router's repay order,
    ///        a venue that refuses repays passed over ({repayRefused}).
    ///      - Each venue takes up to its debt, one the repay clears releases all of it (the swap's reclaim, which reads
    ///        it owing nothing) and one healthy at its own oracle releases in proportion
    ///        (`FLAMMSettleLib.releaseRepaid`'s surplus), within what it can release now ({releasableOf}).
    ///      - A venue past its threshold that the repay leaves owing keeps its collateral: a release in proportion to
    ///        the repay leaves its ratio where it was, and the market refuses it; nor does a partial repay count as
    ///        freeing any where the venue may hold it short ({holdsRepay}: it would leave the debt under the venue's
    ///        minimum position), though what it may release there still comes off a shared reserve's cash.
    ///      - At the other pairs' venues posting `y` that owe nothing, all each can release now, whatever their debt
    ///        token owes elsewhere.
    ///      - The venues sharing one reserve's cash count within the cash they leave for releases there ({_budget}).
    function coverReleases(FLAMMStore.S storage $, uint256 y, uint8 pair, bool many, uint256 left, uint256 cap)
        public
        view
        returns (uint256 freed)
    {
        uint256[] memory B = _budget($, y).R;
        if (pair != FLAMMStore.NO_PAIR) freed = _coverPairReleases($, pair, many, left, B);
        IMMRouter r = $.router;
        for (uint256 q; q < $.pairCount && freed < cap; ++q) {
            FLAMMStore.PairCfg storage c = $.pairs[q];
            if (!c.live || c.coll != y || q == pair) continue;
            uint256 mask = c.venues & ~uint256($.retiredVenues);
            for (uint256 i; mask >> i != 0 && freed < cap; ++i) {
                if ((mask >> i) & 1 == 0) continue;
                (, uint256 rec,,, uint256 d) = r.venuePosition(address(this), uint16(i));
                // a venue that owes nothing releases all it can, whatever its pair's debt token owes elsewhere
                if (d != 0) continue;
                freed += budgeted(B, i, releasableOf($, i, rec));
            }
        }
    }

    /// @dev {coverReleases} at the cover pair's venues, out of line: what each releases of what the repay `left` frees
    ///      there, within its reserve's room in `B`, which it spends.
    function _coverPairReleases(FLAMMStore.S storage $, uint8 pair, bool many, uint256 left, uint256[] memory B)
        private
        view
        returns (uint256 freed)
    {
        IMMRouter r = $.router;
        uint256 mask = $.pairs[pair].venues & ~uint256($.retiredVenues);
        uint16[] memory order;
        uint256 k;
        if (many) {
            while (mask >> k != 0) ++k;
        } else {
            (,,, order) = r.priorities(address(this));
            k = order.length;
        }
        for (uint256 j; j < k; ++j) {
            uint256 i = many ? j : order[j];
            if ((mask >> i) & 1 == 0) continue;
            (uint256 c, uint256 rec,,, uint256 d) = r.venuePosition(address(this), uint16(i));
            rec = releasableOf($, i, rec);
            if (d != 0) {
                if (left == 0 || repayRefused($, i)) continue;
                uint256 rp = left < d ? left : d;
                left -= rp;
                if (rp < d && !r.venueHealthy(address(this), uint16(i))) continue;
                uint256 take = c - Math.mulDiv(d - rp, c, d, Math.Rounding.Up);
                if (take < rec) rec = take;
                if (rp < d && holdsRepay($, i, d - rp)) {
                    // counted as freeing nothing, while what it may release still draws on its reserve's cash
                    budgeted(B, i, rec);
                    continue;
                }
            }
            freed += budgeted(B, i, rec);
        }
    }

    /// @notice Whether venue `id`'s kind can hold a partial repay short (`CAP_HELD_REPAY`, as admitted:
    ///         `FLAMMStore.S.heldRepayVenues`) and may hold one that leaves `rest` owing: its minimum position
    ///         (`IHeldRepay.minimumDebt`) cannot be read, or `rest` falls under it within the lenders' rounding
    ///         (`MMRouterLib.RELEASE_SLACK`). No release such a repay frees is counted before it is made; above the
    ///         minimum the venue takes the repay whole.
    function holdsRepay(FLAMMStore.S storage $, uint256 id, uint256 rest) internal view returns (bool) {
        if (($.heldRepayVenues >> id) & 1 == 0) return false;
        IMMRouter.VenueView memory v = $.router.venue(address(this), uint16(id));
        (bool ok, bytes memory ret) = v.account.staticcall(abi.encodeCall(IHeldRepay.minimumDebt, (v.id)));
        if (!ok || ret.length < 64) return true;
        (uint256 known, uint256 floor) = abi.decode(ret, (uint256, uint256));
        return known == 0 || rest < floor || rest - floor < MMRouterLib.RELEASE_SLACK;
    }

    /// @notice What venue `id` can release now of `rec`, its recognized collateral: all of it, but at a kind that can
    ///         refuse an action (`FLAMMStore.S.gatedVenues`; every kind that lends collateral is one), at most its
    ///         `collateralReleasable`, read alone from its account as the Router reads it to cap every release; none,
    ///         at no read, where it holds none.
    function releasableOf(FLAMMStore.S storage $, uint256 id, uint256 rec) internal view returns (uint256) {
        if (rec == 0 || ($.gatedVenues >> id) & 1 == 0) return rec;
        IMMRouter.VenueView memory v = $.router.venue(address(this), uint16(id));
        uint256 c = IFinancingAccount(v.account).collateralReleasable(v.id);
        return c < rec ? c : rec;
    }

    /// @notice Token `t`'s cash budget at the venues whose kind shares one reserve's cash
    ///         (`FLAMMStore.S.sharedVenues`), one per reserve: the venues of one kind number share one, as each kind's
    ///         deployer binds one lender (one Aave Pool, one comptroller) and a lender is listed under one kind number.
    ///         Per venue id `i`, the high 128 bits of `B.R[i]` are one past the id of the first venue (the lowest id)
    ///         of its reserve that holds a leg in `t` (zero: it holds none), and the low 128 bits of that first venue's
    ///         word are the reserve's room: the cash its venues leave for their releases of `t`, the least figure any
    ///         of them holding a leg in `t` reports for it, what it can return of its supply where it lends `t` and
    ///         what it can release where it posts `t` (such a kind reports the reserve's whole cash), less what the
    ///         pool lends of `t` there, which a payout's funding withdraws from the same cash. At a first venue `g`,
    ///         `B.sum[g]` is what its reserve's releases of `t` count venue by venue, `B.kind[g]` its kind number and
    ///         `B.lent[g]` what the pool lends of `t` there. Empty where no live venue shares a reserve. The maxima's
    ///         netting (`FLAMMMaxima`, periphery) and a rotation's room (`FLAMMSharedLib.releaseRoom`) stay keyed by
    ///         token, so a maximum and a rotation err low where such venues sit on different reserves of one token.
    function _budget(FLAMMStore.S storage $, uint256 t) private view returns (Budget memory B) {
        uint256 m = $.sharedVenues & ~uint256($.retiredVenues);
        if (m == 0) return B;
        // the venues that post `t` and those that lend it
        (uint256 posts, uint256 lends) = (0, 0);
        for (uint256 q; q < $.pairCount; ++q) {
            FLAMMStore.PairCfg storage c = $.pairs[q];
            if (c.coll == t) posts |= c.venues & m;
            else if (c.debt == t) lends |= c.venues & m;
        }
        IMMRouter r = $.router;
        uint256 n = r.venueCount(address(this));
        (B.R, B.sum, B.kind, B.lent) = (new uint256[](n), new uint256[](n), new uint256[](n), new uint256[](n));
        // every venue holding a leg in `t`, read in id order
        lends |= posts;
        for (uint256 i; lends >> i != 0; ++i) {
            if ((lends >> i) & 1 != 0) _budgetAt(r, B, i, (posts >> i) & 1 != 0);
        }
        uint256[] memory R = B.R;
        for (uint256 g; g < n; ++g) {
            if (R[g] >> 128 != g + 1) continue;
            (uint256 room, uint256 l) = (uint128(R[g]), B.lent[g]);
            R[g] = ((g + 1) << 128) | (room > l ? room - l : 0);
        }
    }

    /// @dev {_budget}'s read of venue `i`, which posts its token where `posts`, else lends it: where it holds a leg,
    ///      its reserve's first venue (of its kind number, the lowest id) found or recorded, the room cut to its figure
    ///      and what it counts added there.
    function _budgetAt(IMMRouter r, Budget memory B, uint256 i, bool posts) private view {
        (, uint256 rec,, uint256 sup,) = r.venuePosition(address(this), uint16(i));
        if (posts ? rec == 0 : sup == 0) return;
        uint256[] memory R = B.R;
        IMMRouter.VenueView memory v = r.venue(address(this), uint16(i));
        uint256 k = v.kind;
        uint256 g = i;
        for (uint256 j; j < i; ++j) {
            if (R[j] >> 128 == j + 1 && B.kind[j] == k) {
                g = j;
                break;
            }
        }
        if (g == i) (R[i], B.kind[i]) = (((i + 1) << 128) | type(uint128).max, k);
        else R[i] = (g + 1) << 128;
        // the one field of its capacity it needs, from its account, as the Router reads it
        IFinancingAccount a = IFinancingAccount(v.account);
        uint256 f = posts ? a.collateralReleasable(v.id) : a.supplyWithdrawable(v.id);
        if (f < uint128(R[g])) R[g] = ((g + 1) << 128) | f;
        if (posts) B.sum[g] += f < rec ? f : rec;
        else B.lent[g] += sup;
    }

    /// @notice A release `v` venue `id` counts, within what its reserve has left of its room in `R` ({_budget}'s
    ///         `B.R`), which it spends: all of `v`, spending nothing, where the venue holds no leg in a shared one.
    function budgeted(uint256[] memory R, uint256 id, uint256 v) internal pure returns (uint256) {
        if (id >= R.length || R[id] >> 128 == 0) return v;
        uint256 g = (R[id] >> 128) - 1;
        uint256 room = uint128(R[g]);
        if (v > room) v = room;
        R[g] -= v;
        return v;
    }

    /// @notice What token `t`'s releases at the venues sharing one reserve's cash count, each reserve's within its room
    ///         (`fit`) and before (`sum`), and `fit`'s part at the reserves of `mask`'s venues that share one (their
    ///         kind numbers'): what a draw at `mask`'s venues loses of its reserve's cash to those releases (`mine`).
    function sharedFit(FLAMMStore.S storage $, uint256 t, uint256 mask)
        public
        view
        returns (uint256 fit, uint256 sum, uint256 mine)
    {
        Budget memory B = _budget($, t);
        (uint256[] memory R, uint256[] memory s, uint256[] memory kind) = (B.R, B.sum, B.kind);
        mask &= $.sharedVenues;
        IMMRouter r = $.router;
        uint256 kinds;
        for (uint256 i; mask >> i != 0; ++i) {
            if ((mask >> i) & 1 != 0) kinds |= uint256(1) << r.venue(address(this), uint16(i)).kind;
        }
        for (uint256 g; g < R.length; ++g) {
            if (R[g] >> 128 != g + 1) continue;
            uint256 room = uint128(R[g]);
            uint256 f = s[g] < room ? s[g] : room;
            (fit, sum) = (fit + f, sum + s[g]);
            if ((kinds >> kind[g]) & 1 != 0) mine += f;
        }
    }

    /// @notice An exit's slices `cs` of collateral `coll` and `ss` of supply `sup` at venue `id` of `account`, as its
    ///         units round. No price is read. Named so its selector sorts after every one a flow calls here.
    /// @dev - Where the venue shares one reserve with others (`FLAMMStore.S.sharedVenues`; `n`, the pool's venue count,
    ///        zero otherwise), a slice that takes all but a millionth of its collateral or supply leaves one unit's
    ///        assets and one there per venue (`IFinancingAccount` ADMISSION), as each sibling leg earlier in the exit
    ///        (a supply withdrawn or a collateral redeemed from the same market) can lower the position's read by that
    ///        much once, and the whole slice would then pass it.
    ///      - Where the venue still owes after the exit (`pin`: its pair's LTV in the low 64 bits and the pair in the
    ///        next 8, zero otherwise) and its collateral accrues, a release in whole units can leave the position up to
    ///        one unit's assets and one under its exact rest: the collateral slice is cut to keep that much times
    ///        `lltv / max(lltv - ltv, gap, 1 %)` posted (`lltv` its threshold, read live; `gap` the pair's safety gap
    ///        at the Router, read only where the cut binds; `FLAMMStore.MIN_DUST_GAP_WAD`), the bound of the dust a
    ///        held exit may leave there (`FLAMMAdmitLib.heldRelease`), so no cut passes that dust, however near the
    ///        threshold sits over the LTV: where so little posted would let a unit take a venue at the LTV past its
    ///        threshold, the lender refuses the release, and the exit with it, rather than the exit forfeit its slice.
    ///      - A threshold at or under the LTV (a lender that may liquidate the position, or a cut to the pin) keeps one
    ///        unit's assets and one: no release takes the last unit.
    ///      - A slice under one unit's assets and one stays posted whole: the kind releases so little by burning a
    ///        whole unit (`CTokenAccount`'s `redeem` of one), which the lender refuses where the venue's margin is
    ///        under that unit's worth net of the repay, so the exit releases nothing there and forfeits at most that
    ///        much past the cut. The holders who remain keep what is left, which the exit records for the fee mark
    ///        (`FLAMMFlowLib.proRata`).
    ///      - The unit's assets are read at face, as `FLAMMSharedLib.roundingAllowance` reads them.
    function nearUnitsAt(
        address account,
        bytes32 id,
        uint256 coll,
        uint256 sup,
        uint256 cs,
        uint256 ss,
        uint256 n,
        uint256 pin
    ) public view returns (uint256, uint256) {
        IFinancingAccount k = IFinancingAccount(account);
        if (n != 0) {
            if (cs != 0 && coll - cs <= coll / 1e6) cs = _leave(coll, cs, k.collateralUnitsToAssets(id, 1), n);
            if (ss != 0 && sup - ss <= sup / 1e6) ss = _leave(sup, ss, k.supplySharesToAssets(id, 1), n);
        }
        if (cs == 0 || pin == 0 || k.capabilities() & CAP_ACCRUING_COLLATERAL == 0) return (cs, ss);
        (uint256 lltv, uint256 one) = (k.lltv(id), k.collateralUnitsToAssets(id, 1) + 1);
        (uint256 floor, uint256 ltv) = (one, uint64(pin));
        if (lltv > ltv) {
            uint256 d = lltv - ltv;
            if (d < FLAMMStore.MIN_DUST_GAP_WAD) d = FLAMMStore.MIN_DUST_GAP_WAD;
            uint256 f = Math.mulDiv(floor, lltv, d, Math.Rounding.Up);
            // the pair's gap, read only where the floor binds: a wider one keeps less
            if (coll - cs < f) {
                uint256 gap = FLAMMStore.s().router.pair(address(this), uint8(pin >> 64)).safetyGapWad;
                if (gap > d) f = Math.mulDiv(floor, lltv, gap, Math.Rounding.Up);
            }
            floor = f;
        }
        if (coll - cs < floor) cs = coll > floor ? coll - floor : 0;
        // a release under one unit's assets and one would burn a whole unit: that slice stays posted
        if (cs < one) cs = 0;
        return (cs, ss);
    }

    /// @dev A `slice` of `pos` that leaves at least `(unit + 1) * n` of it ({nearUnitsAt}), compared by division, so
    ///      the product is formed only where it is at most `pos`.
    function _leave(uint256 pos, uint256 slice, uint256 unit, uint256 n) private pure returns (uint256) {
        if ((pos - slice) / n > unit) return slice;
        if (pos / n <= unit) return 0;
        unchecked {
            return pos - (unit + 1) * n;
        }
    }

    /// @notice What a post may add at venue `id` now (`IFinancingAccount.Capacity.collateralPostable`): zero while its
    ///         cap is full or it refuses a post. Read from the account's one-field view, which answers that field in
    ///         the same state without the rooms the full capacity sizes, but at the Aave V3 kind while only the loan
    ///         reserve's configuration word cannot be read (ADMISSION): there it allows the post the full capacity
    ///         would refuse, as the Router's own post gate does (`MMRouterLib.canAct`), a post lowering the venue's
    ///         risk.
    function postable(FLAMMStore.S storage $, uint16 id) public view returns (uint256) {
        IMMRouter.VenueView memory v = $.router.venue(address(this), id);
        return IFinancingAccount(v.account).collateralPostable(v.id);
    }

    // ------------------------------------------------------------------ NAV
    /// @notice Whether a venue's figures are a frozen venue mark: a venue the book reads (neither retired nor idle)
    ///         whose kind can refuse an action (`FLAMMStore.S.gatedVenues`) allows none now and holds a position the
    ///         Router recognizes (collateral, supply or debt).
    /// @dev While its protocol cannot be read such a kind answers from its last good position and its `actions` allow
    ///      none (`IFinancingAccount`), so no flow takes a slice at those figures. A lender that refuses every action
    ///      while still readable reads the same way, which is conservative.
    ///      - No entry enters at them: the pool's pro-rata entries refuse `VenueFrozen`, whether or not the kind would
    ///        still take a leg.
    ///      - An exit forfeits its slice of such a venue that owes nothing (or no more than the lenders' rounding,
    ///        `MMRouterLib.RELEASE_SLACK`) and refuses where one owes more (`FLAMMFlowLib.proRata`).
    ///      - NAV does not price at them: {totalAssets} reverts `VenueFrozen`, and {tryMarkedTotalAssets} reads not ok,
    ///        as at an unchecked feed, so the fee's skim abstains, and the first skim that reads the fee mark again
    ///        counts no forfeit as performance.
    ///      - The entry maxima (`FLAMMMaxima`, periphery) read 0 then; the exit maximum passes over a frozen venue that
    ///        owes nothing (or that rounding) and reads 0 where one owes more.
    ///      - A fenced venue is not read here: it passes every walk (`FLAMMFenceLib`), so no exit forfeits or reverts
    ///        there; NAV refuses while a fence holds a pool part not written off ({fenced}), as the book here leaves
    ///        that part out; the entries refuse, and a skim that would charge a fee abstains
    ///        (`FLAMMMaintainLib.crystallize`, its fee mark waiting), while a fence holds a pool part, written off or
    ///        not ({isFrozen}, `FLAMM._notFrozen`, `FLAMMFlowLib._entryGuards`).
    function frozen(FLAMMStore.S storage $) internal view returns (bool) {
        uint256 g = $.gatedVenues & ~($.retiredVenues | $.idleVenues);
        IMMRouter r = $.router;
        for (uint16 i; g != 0; ++i) {
            if (g & 1 != 0) {
                // the bits alone, which its capacity reports in the same state without the rooms it sizes
                IMMRouter.VenueView memory v = r.venue(address(this), i);
                if (!acts(v.account, v.id)) {
                    (, uint256 coll,, uint256 sup, uint256 debt) = r.venuePosition(address(this), i);
                    if (coll | sup | debt != 0) return true;
                }
            }
            g >>= 1;
        }
        return false;
    }

    /// @notice Accrues interest at each live venue the pool's book reads, an idle one only where `touch` names it
    ///         (bit i: venue i), before an operation that reads those venues again and again, as a swap does before
    ///         its reads (`FLAMMSwapLib`): every kind's views project the next accrual exactly, so each read answers
    ///         the same and costs less; a Compound-style debt read, an upper bound before, reads exact. Accrual is
    ///         permissionless and idempotent, and the Router passes over an account whose accrual reverts
    ///         (`IMMRouter.accrueExcept`). An idle venue no read reaches is left, as its accrual would cost more than
    ///         it saves. Nothing on a pool with no live venue or no borrowing pair.
    function accrueRead(FLAMMStore.S storage $, uint256 touch) internal {
        if ($.noLiveVenue || $.poolBits & FLAMMStore.POOL_BORROWS == 0) return;
        $.router.accrueExcept(uint64($.idleVenues & ~touch), type(uint8).max);
    }

    /// @notice Whether venue `id` at `account` allows some action now (`IFinancingAccount.actions` not zero), the one
    ///         question a frozen venue mark asks ({frozen}, `FLAMMFlowLib.proRata`). Asked first of
    ///         `IActionsOf.actionsOf` for a supply withdrawal and a post, which reads only what those two need: either
    ///         bit set proves `actions` not zero in the same state, as each bit reads as `actions` reads it, and at the
    ///         Aave V3 kind the two need both reserves' configuration words, which `actions` reads (ADMISSION's one
    ///         exception answers only where one word cannot be read). Otherwise, or where the kind does not answer that
    ///         view, the full `actions`, whose revert bubbles up.
    function acts(address account, bytes32 id) public view returns (bool) {
        (bool ok, bytes memory ret) =
            account.staticcall(abi.encodeCall(IActionsOf.actionsOf, (id, CAN_WITHDRAW_SUPPLY | CAN_POST_COLLATERAL)));
        if (ok && ret.length == 32 && abi.decode(ret, (uint256)) & (CAN_WITHDRAW_SUPPLY | CAN_POST_COLLATERAL) != 0) {
            return true;
        }
        return IFinancingAccount(account).actions(id) != 0;
    }

    /// @notice {frozen}, or a venue fence holding a pool part, written off or not (a slot both retired and idle), for a
    ///         flow that asks only where some venue is gated or a slot is fenced: the entries and the fee mark's
    ///         restart. A write-off reopens NAV, which then leaves the part out, but every share still owns its slice
    ///         of it, so no entry is priced at that NAV until the part returns (the lift, an unwind of all of it) or is
    ///         given up (`FLAMMFenceLib.abandonFence`). After a whole unwind, or a kept share's clear, at a reported
    ///         loss the slot is no longer idle and this reads false while the cut stays at the fenced venue outside NAV
    ///         until the lift (`FLAMMClaimLib.unwindFence`). A token's custody fence is not read here
    ///         (`FLAMMFlowLib._entryGuards` reads it).
    function isFrozen(FLAMMStore.S storage $) public view returns (bool) {
        return $.retiredVenues & $.idleVenues != 0 || frozen($);
    }

    /// @notice Whether a fence holds a pool part not written off on book `b`, which NAV refuses: a venue slot both
    ///         retired and idle, or a token's open record (its fee pass marked the book, {keeps}: the record keeps
    ///         `FLAMMStore.POOL_SPREAD_OWED` set; `FLAMMStore.SWAP_FENCE`, read only then), and the fence word's
    ///         unwritten bits.
    function fenced(FLAMMStore.S storage $, Book memory b) internal view returns (bool) {
        return ($.retiredVenues & $.idleVenues != 0 || keeps(b) && $.swapBits & FLAMMStore.SWAP_FENCE != 0)
            && FLAMMStore.navRefused($);
    }

    /// @notice NAV in pool-asset base units at the checked snapshot, each venue's collateral and supply cut by the
    ///         share its lender cannot pay ({haircut}); reverts `PriceUnchecked` while a token with a position has an
    ///         unchecked feed, or, while a fee rate is on and the pool has a band, while the curator's fee mark cannot
    ///         read ({markedAt}: a cheap-lane pool's basket, a pending forfeit record), so nothing priced at NAV after
    ///         a skim trades the fee that skim could not charge; and `VenueFrozen` while a venue's figures are a frozen
    ///         venue mark ({frozen}) or a fence holds a pool part not written off ({fenced}).
    function totalAssets(FLAMMStore.S storage $) public view returns (uint256) {
        if (frozen($)) revert VenueFrozen();
        Book memory b = priced($);
        if (fenced($, b)) revert VenueFrozen();
        if (($.performanceFeeBp | $.protocolFeeBp) != 0 && !FLAMMStore.bandOff($) && !markedAt($, b)) {
            revert PriceUnchecked();
        }
        if (!haircut($, b)) revert VenueFrozen();
        return navAt(b);
    }

    /// @notice {totalAssets}, or `ok` false where it would revert `PriceUnchecked` or `VenueFrozen` at a frozen venue
    ///         mark: that mark reads as an unchecked feed does, and a fence's part reads as no value, as the book
    ///         leaves it out (so a skim that would charge a fee abstains while a fence holds a part, written off or
    ///         not, `FLAMMMaintainLib.crystallize`, and no fee-rate rise lands); in the fee mark's measure: NAV at 18
    ///         decimals of par whatever the pool asset (times `shareScale`), or, on a pool whose cheap lane is on and
    ///         whose deposit basket is set ({setBasket}), in the basket's units ({_inBasket}). Only the fee mark reads
    ///         it (`FLAMMFlowLib.mark`, and its restart where a band attaches, `FLAMMOpsLib.setMarketBand`).
    /// @dev `forfeit`: what exits forfeited at frozen venue marks since the fee mark last read
    ///      (`FLAMMStore.S.forfeited`, per share, 1e36), valued at the same prices, at face, as the fee mark's rise in
    ///      the same measure, rounded up; `ok` false where a token they are in has no checked price. Every flow's skim
    ///      reads it (`FLAMMMaintainLib.crystallize`): its name keeps its selector first in this library's dispatcher.
    function tryMarkedTotalAssets(FLAMMStore.S storage $)
        public
        view
        returns (bool ok, uint256 assets, uint256 forfeit)
    {
        if (frozen($)) return (false, 0, 0);
        Book memory b = priced($);
        if (!haircut($, b) || !checkedAt(b)) return (false, 0, 0);
        (ok, assets) = (true, navAt(b));
        // the record per share, 1e36, in pool-asset base units at each token's price, rounded up
        if ($.poolBits & FLAMMStore.POOL_FORFEIT != 0) {
            for (uint256 t; t < b.legs.length; ++t) {
                uint256 u = $.forfeited[t];
                if (u == 0) continue;
                uint256 p = b.legs[t].price36;
                if (t != 0 && p == 0) return (false, 0, 0);
                forfeit += t == 0 ? u : Math.mulDiv(u, 1e36, p, Math.Rounding.Up);
            }
        }
        uint256 scale = b.legs[0].scale;
        if (laneOn(b) && $.basketPool != 0) return _inBasket($, b, assets, forfeit, scale);
        // 18 decimals of par per share: NAV times the pool asset's scale, and the record's 1e36 per share to it; NAV
        // is at most what the tokens' supplies are worth, and the scale is under 2^40: no overflow
        unchecked {
            assets *= scale;
        }
        if (forfeit != 0) forfeit = Math.mulDiv(forfeit, scale, WAD, Math.Rounding.Up);
    }

    /// @notice Records a pool's deposit basket from `b`, the book of `supply` shares, where it holds or supplies token
    ///         1: per 1e18 shares every token's legs, each net of its debt and of the spread fee owed past custody and
    ///         rounded up (the pool asset's and token 1's in `basketPool` and `basketLoan`, each later token's in
    ///         `basketTok`), so the basket's value is never under the book's at any price and a price move alone never
    ///         reads as a gain; and restarts the curator's fee mark at the basket ratio at that book, 1e18 (carried
    ///         times the share scale, as every fee mark is), clearing a pending forfeit record
    ///         (`FLAMMStore.takeForfeit`), as that book already holds what the exits left. A basket with no pool-asset
    ///         entry, which reads as none, or that would not fit its words is not recorded. A token listed after the
    ///         record stays outside the basket until the next.
    function setBasket(FLAMMStore.S storage $, Book memory b, uint256 supply) internal {
        (Leg memory L0, Leg memory L1) = (b.legs[0], b.legs[1]);
        if (supply == 0 || L1.held + L1.supplied == 0) return;
        uint256 pool = Math.mulDiv(_net(L0), WAD, supply, Math.Rounding.Up);
        uint256 loan = Math.mulDiv(_net(L1), WAD, supply, Math.Rounding.Up);
        if (pool == 0 || pool > type(uint128).max || loan > type(uint128).max) return;
        uint256 n = b.legs.length;
        uint256[] memory rest = new uint256[](n);
        for (uint256 t = 2; t < n; ++t) {
            rest[t] = Math.mulDiv(_net(b.legs[t]), WAD, supply, Math.Rounding.Up);
            if (rest[t] > type(uint128).max) return;
        }
        ($.basketPool, $.basketLoan) = (uint128(pool), uint128(loan));
        for (uint256 t = 2; t < n; ++t) {
            if ($.basketTok[t] != rest[t]) $.basketTok[t] = rest[t];
            emit BasketTokenSet(uint8(t), rest[t]);
        }
        // the fee mark restarts at the book the basket is read from, which already holds what exits forfeited: a
        // pending forfeit record is spent with the restart (a frozen venue mark lets a seed through only on a pool with
        // no band)
        uint256 one;
        // the scale is under 2^40
        unchecked {
            one = WAD * $.shareScale;
        }
        if ($.poolBits & FLAMMStore.POOL_FORFEIT != 0) FLAMMStore.takeForfeit($, one);
        else $.peakSharePriceWad = uint128(one);
        emit BasketSet(uint128(pool), uint128(loan));
    }

    /// @notice Whether a pro-rata entry waits for the deposit basket (`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 recorded it
    ///         (`FLAMM.seedLeg`, {setBasket}), while the curator holds every share but the dead ones and the pool has
    ///         never opened (`FLAMMStore.S.opened`); a pool opened before that seed waits for good. The fee mark then
    ///         measures every holder against the book the curator seeded, never one a later dust inflow made.
    function basketGated(FLAMMStore.S storage $) internal view returns (bool) {
        return $.swapBits & FLAMMStore.SWAP_LANE != 0 && $.maxPerformanceFeeBp != 0 && $.basketPool == 0;
    }

    /// @dev A token's legs net of its debt and of the spread fee owed past custody, zero at most.
    function _net(Leg memory L) private pure returns (uint256) {
        (uint256 pos, uint256 neg) = (L.held + L.supplied + L.posted, L.owed + feeOf(L));
        return pos > neg ? pos - neg : 0;
    }

    /// @dev NAV `assets` and the record's value `w` (per share, 1e36, in pool-asset base units) in the deposit
    ///      basket's units, at the pool asset's `scale` as every fee mark is: NAV times `1e18 * scale / basket`,
    ///      `basket` the basket's value per 1e18 shares in pool-asset base units at `b`'s price scales,
    ///      `basketPool + ceil(basketLoan * 1e36 / p1)` plus each later token's entry so valued, and the record as the
    ///      fee mark's rise, `ceil(w * scale / basket)`; NAV per share against the basket is the fee mark's price, a
    ///      WAD ratio times `scale`, `1e18 * scale` at the book the basket was recorded at, which `FLAMM.limits()`
    ///      shows as the ratio. `ok` false while token 1's price is unchecked, or a later token's whose entry is
    ///      nonzero ({markedAt}, the same set).
    function _inBasket(FLAMMStore.S storage $, Book memory b, uint256 assets, uint256 w, uint256 scale)
        private
        view
        returns (bool, uint256, uint256)
    {
        uint256 p = b.legs[1].price36;
        if (p == 0) return (false, 0, 0);
        uint256 basket = $.basketPool + Math.mulDiv($.basketLoan, 1e36, p, Math.Rounding.Up);
        for (uint256 t = 2; t < b.legs.length; ++t) {
            uint256 e = $.basketTok[t];
            if (e == 0) continue;
            p = b.legs[t].price36;
            if (p == 0) return (false, 0, 0);
            basket += Math.mulDiv(e, 1e36, p, Math.Rounding.Up);
        }
        uint256 one;
        // the scale is under 2^40
        unchecked {
            one = WAD * scale;
        }
        return (true, Math.mulDiv(assets, one, basket), Math.mulDiv(w, scale, basket, Math.Rounding.Up));
    }

    /// @notice Cuts `b`'s posted and supplied legs by the share of face value each venue the book reads cannot pay
    ///         (`IFinancingAccount.haircut`: a lender's reserve deficit spread over its suppliers), rounded against
    ///         the pool; only a venue whose kind can report one is asked (`FLAMMStore.S.lossVenues`). NAV applies it,
    ///         and an exit cuts its slices by the same shares (`FLAMMFlowLib.proRata`); every other read, the Router's
    ///         included, values a venue's units at face, so the Router's mechanics see what the venue owes. Each share
    ///         is the larger of what the lender reports now and the venue's loss mark (`FLAMMKeptLib.largerLoss`): the
    ///         lender's figure is a spot ratio a supply to its reserve lowers within one call, so NAV, the fee mark
    ///         and every price read from them stand on a ratio no single call lowers. Each kept share not written off
    ///         (`FLAMMStore.KEPT_SHIFT`) first adds the pool's own part of its position behind the senior claims
    ///         (`FLAMMKeptLib.keptLegs`); false where one does not read, where NAV refuses (`VenueFrozen`) and the
    ///         skim abstains.
    function haircut(FLAMMStore.S storage $, Book memory b) internal view returns (bool) {
        // each kept share's own part, at its loss ratios behind the senior claims (`FLAMMKeptLib.keptLegs`)
        if ($.fenceWord >> FLAMMStore.KEPT_SHIFT != 0) {
            (bool ok, uint256[] memory p, uint256[] memory q, uint256[] memory o) =
                FLAMMKeptLib.keptLegs(b.legs.length, false);
            if (!ok) return false;
            for (uint256 t; t < p.length; ++t) {
                Leg memory L = b.legs[t];
                (L.posted, L.supplied, L.owed) = (L.posted + p[t], L.supplied + q[t], L.owed + o[t]);
            }
        }
        uint256 lossy = $.lossVenues & ~uint256($.retiredVenues | $.idleVenues);
        if (lossy == 0) return true;
        IMMRouter r = $.router;
        for (uint16 i; lossy >> i != 0; ++i) {
            if ((lossy >> i) & 1 == 0) continue;
            IMMRouter.VenueView memory v = r.venue(address(this), i);
            (uint256 cl, uint256 sl) = FLAMMKeptLib.largerLoss(i, v.account, v.id);
            if ((cl | sl) == 0) continue;
            (, uint256 coll,, uint256 sup,) = r.venuePosition(address(this), i);
            Leg memory C = b.legs[v.coll];
            Leg memory D = b.legs[v.debt];
            uint256 cut = Math.mulDiv(coll, cl, WAD, Math.Rounding.Up);
            C.posted = C.posted > cut ? C.posted - cut : 0;
            cut = Math.mulDiv(sup, sl, WAD, Math.Rounding.Up);
            D.supplied = D.supplied > cut ? D.supplied - cut : 0;
        }
        return true;
    }

    // ------------------------------------------------------------------ admission prices
    /// @notice Admits token `t`'s price against the pool asset: both USD prices answer now, each at least
    ///         `MIN_PRICE_STEPS` of its feed's steps, and the pool asset's price scale against `t` is at least
    ///         `MIN_PRICE36`; for token 1, the hook pair, so is the hooks' N36 (`price36 / 10^decimals`), and the pool
    ///         asset has `MIN_POOL_DECIMALS` at least. A stale feed reverts `InvalidConfig` too, which a retry clears.
    function admitToken(FLAMMStore.S storage $, uint256 t) public view {
        FLAMMStore.TokenCfg storage c = $.tokens[t];
        address token = c.token;
        (bool ok, uint256 u0, uint256 ut,) = $.priceFeed.peekPair($.poolAsset, token);
        if (!ok || u0 < _minUsd($, $.poolAsset) || ut < _minUsd($, token)) revert InvalidConfig();
        // the pool asset's `MIN_POOL_DECIMALS` holds from genesis, which refuses fewer (`FLAMMAdmitLib.initializePool`)
        uint256 min = FLAMMStore.MIN_PRICE36 * (t == 1 ? 10 ** c.decimals : 1);
        if (frame(u0, ut, $.shareScale, c.scale) < min) revert InvalidConfig();
    }

    /// @notice Admits pair (`a` -> `c`)'s price: both directions of its price scale at least `MIN_PRICE36`, from one
    ///         read of the two tokens.
    function admitPair(FLAMMStore.S storage $, uint256 a, uint256 c) public view {
        (bool ok, uint256 ua, uint256 uc,) = $.priceFeed.peekPair(FLAMMStore.tokenOf($, a), FLAMMStore.tokenOf($, c));
        (uint256 sa, uint256 sc) = (_scale($, a), _scale($, c));
        if (!ok || frame(ua, uc, sa, sc) < FLAMMStore.MIN_PRICE36 || frame(uc, ua, sc, sa) < FLAMMStore.MIN_PRICE36) {
            revert InvalidConfig();
        }
    }

    /// @dev `MIN_PRICE_STEPS` of `token`'s feed step, the USD value of one unit of its answer.
    function _minUsd(FLAMMStore.S storage $, address token) private view returns (uint256) {
        return FLAMMStore.MIN_PRICE_STEPS * PriceFeed(address($.priceFeed)).config(token).scale;
    }

    // ------------------------------------------------------------------ hooks' capabilities
    /// @notice Reverts `HookInvalid` unless `hook` declares capability `bit` ({capabilities}).
    function requireCapability(address hook, uint256 bit) internal view {
        if (capabilities(hook) & bit == 0) revert HookInvalid();
    }

    /// @notice `hook`'s `hookCapabilities()` ({IHookCapabilities}), by a raw static call: a revert, no code or an
    ///         answer under a word declares nothing.
    function capabilities(address hook) internal view returns (uint256 caps) {
        bytes4 sel = IHookCapabilities.hookCapabilities.selector;
        assembly ("memory-safe") {
            mstore(0x00, sel)
            if staticcall(gas(), hook, 0x00, 0x04, 0x00, 0x20) {
                if gt(returndatasize(), 0x1f) { caps := mload(0x00) }
            }
        }
    }

    /// @notice The band mode and the pairs against the swap hook a set installs, `hook`: with no band it must price
    ///         without a reference (`HOOK_CAP_UNPRICED`); while a pair that owes the pool asset or posts another token
    ///         is listed (`FLAMMStore.POOL_TWO_SIDED`), it must declare `HOOK_CAP_TWO_SIDED`.
    function checkHook(FLAMMStore.S storage $, address hook) public view {
        if ($.noBand) requireCapability(hook, HOOK_CAP_UNPRICED);
        if ($.poolBits & FLAMMStore.POOL_TWO_SIDED != 0) requireCapability(hook, HOOK_CAP_TWO_SIDED);
    }

    // ------------------------------------------------------------------ dials
    /// @notice Pair `p`'s dial move guard: both dials inside its envelope, an LTV not lowered within what the band and
    ///         the protocol's part keep (`FLAMMStore.coverSafe`, `DialOutOfEnvelope`), its LTV step, its cooldown, its
    ///         threshold's gap and its structural floor, and for a loosening move a standing book already inside the
    ///         credit law at the new LTV.
    /// @dev - A lower LTV takes neither the step nor the structural floor, so the pool follows a lender's cut in one
    ///        move, and while the cut stands over the pair's pin a lower LTV that raises neither dial skips the
    ///        cooldown too, so it follows at once, however recent the last move.
    ///      - A lower LTV lands at or over the threshold, at the envelope's floor, or at least the larger of the gap
    ///        and 1 % under the threshold (`FLAMMStore.MIN_DUST_GAP_WAD`; `LtvLltvGap` otherwise), as a raise does: an
    ///        LTV a hair under its threshold would leave an exit's whole-units floor at the dust's bound, short of what
    ///        keeps a unit's release there under the threshold (`nearUnitsAt`).
    ///      - Any other move waits the cooldown.
    ///      - A cut at one pair's lender binds that pair alone. A cut stands where a venue of the pair that binds it
    ///        (`minLltv`: one that can borrow or still owes) has a threshold under the pin plus the larger of the
    ///        pair's gap and 1 %, and lends nothing more until the pin plus the gap is within it.
    ///      - Only a cut leaves one there: the Router admits none that binds, enables borrowing on none, moves no debt
    ///        into one and raises no pin past one, each within the gap, and the pool holds an admission and a switch to
    ///        the larger of the gap and 1 % too ({requireDustGap}).
    function validateDialMove(FLAMMStore.S storage $, uint8 p, uint64 phiWad, uint64 newLtvWad) public view {
        FLAMMStore.PairCfg storage pc = $.pairs[p];
        if (!pc.live) revert InvalidConfig();
        if (phiWad < pc.phiMinWad || phiWad > pc.phiMaxWad || newLtvWad < pc.ltvMinWad || newLtvWad > pc.ltvMaxWad) {
            revert DialOutOfEnvelope();
        }
        uint64 ltv = pc.ltvWad;
        bool lower = newLtvWad < ltv;
        if (!lower && newLtvWad - ltv > pc.ltvMaxStepWad) revert LtvStepTooLarge();
        // the pair's binding threshold and its safety gap
        IMMRouter r = $.router;
        (uint256 lltv, uint256 gap) = (r.minLltv(address(this), p), r.pair(address(this), p).safetyGapWad);
        // every move keeps the larger of the gap and 1 % under the threshold, as an admission and a switch do
        if (gap < FLAMMStore.MIN_DUST_GAP_WAD) gap = FLAMMStore.MIN_DUST_GAP_WAD;
        if (block.timestamp < uint256(pc.lastDialMoveTs) + pc.ltvCooldownSec) {
            // a lower LTV raising neither dial, while a cut stands over the pin
            if (!lower || phiWad > pc.phiWad || lltv >= ltv + gap) revert DialCooldown();
        }
        if (!lower) {
            if (!FLAMMStore.coverSafe(newLtvWad, FLAMMStore.pairBand($, pc.coll, pc.debt))) revert DialOutOfEnvelope();
            if (lltv == NO_VENUE_LLTV || uint256(newLtvWad) + gap > lltv) revert LtvLltvGap();
            if (structuralDistWad(newLtvWad, lltv) < pc.minStructDistWad) revert LtvFloorBreached();
        } else if (newLtvWad < lltv && newLtvWad != pc.ltvMinWad && uint256(newLtvWad) + gap > lltv) {
            revert LtvLltvGap();
        }
        // Only a loosening move must clear the standing book: a tightening one enlarges no room, and testing it
        // would freeze the dials once a price move lifts a debt over the law. The move changes no load but those its
        // collateral token carries, so the law is read there alone.
        if (newLtvWad > ltv || phiWad > pc.phiWad) {
            Book memory b = bookOf($);
            priceIn($, b);
            if (!FLAMMLawLib.loadHolds($, b, pc.coll, p, newLtvWad)) revert LedgerBoundBreached();
        }
    }

    /// @notice Refuses (`LtvLltvGap`) a venue of pair `pair` admitted with its borrowing on, or switched on, whose
    ///         threshold `lltv` is under the pin plus 1 %: the Router holds it to the pin plus the pair's gap, so the
    ///         two hold it to the larger of them, as a dial move is ({validateDialMove}), and no move of the pool's own
    ///         leaves its pin within 1 % of a threshold that binds it.
    function requireDustGap(FLAMMStore.S storage $, uint8 pair, uint256 lltv) internal view {
        if (lltv < uint256($.pairs[pair].ltvWad) + FLAMMStore.MIN_DUST_GAP_WAD) revert LtvLltvGap();
    }
}
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": "0x82a048459DF53186031Fd66507B260EeaC7F67df"
    },
    "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": "0x3Bd2B976e70C0D6ea7eb041e36ad525F66F79A69"
    },
    "src/core/mm/AaveV3ReadsLib.sol": {
      "AaveV3ReadsLib": "0xD53F6170226A74D453e84414Ffc2FFcE5ded5983"
    },
    "src/core/flamm/FLAMMFlowLib.sol": {
      "FLAMMFlowLib": "0xAC619698656d47651EF67a050859578e176A909D"
    },
    "src/core/flamm/FLAMMGateLib.sol": {
      "FLAMMGateLib": "0x2291F5e012B0740468E2e2E9AeA37F7Fea64F98c"
    },
    "src/core/flamm/FLAMMKeptLib.sol": {
      "FLAMMKeptLib": "0x7a11899232dd9F17c28bF062Ec2ee2267158517b"
    },
    "src/core/mm/CTokenMarketLib.sol": {
      "CTokenMarketLib": "0xfD87dcDDdc9b4eCe3F2413A858B265D8Ec6dF060"
    },
    "src/core/flamm/FLAMMAdmitLib.sol": {
      "FLAMMAdmitLib": "0x4AAcA346B9430656eB1316094cea0Df0f2e1AED6"
    },
    "src/core/flamm/FLAMMBlindLib.sol": {
      "FLAMMBlindLib": "0x9E5010D8393EB299b6FEce8EB160b3826f7eEb41"
    },
    "src/core/flamm/FLAMMClaimLib.sol": {
      "FLAMMClaimLib": "0xC6C94A120AC43f689BD8D8444dFf300eb9Da2aFe"
    },
    "src/core/flamm/FLAMMFenceLib.sol": {
      "FLAMMFenceLib": "0x739D84c7662030d5Ed8C6BA7606152977D5A629f"
    },
    "src/core/flamm/FLAMMFloatLib.sol": {
      "FLAMMFloatLib": "0xf128B7AdB5bF43814D595E3d1fC95a1f2bB16b70"
    },
    "src/core/flamm/FLAMMQuoteLib.sol": {
      "FLAMMQuoteLib": "0xF284B0271EA829F3a15f005BB588b7Df4bEFd526"
    },
    "src/core/flamm/FLAMMTopUpLib.sol": {
      "FLAMMTopUpLib": "0xD56127118C7619e4a13713Fb4280Cf66D560C5A5"
    },
    "src/core/mm/CTokenRewardsLib.sol": {
      "CTokenRewardsLib": "0xcda63d7eCCF838F2732Bff676706BDE5abA4DcF7"
    },
    "src/core/mm/MMRouterAdminLib.sol": {
      "MMRouterAdminLib": "0x8423744b3F304ED0B43043d7ad4E7d8A247aDc96"
    },
    "src/core/flamm/FLAMMPolicyLib.sol": {
      "FLAMMPolicyLib": "0x6FE69Ed6659A547da6100225Cd0616CfDB678097"
    },
    "src/core/flamm/FLAMMSettleLib.sol": {
      "FLAMMSettleLib": "0x1834d367BD65AF7CCf41D2025758bB69Af56e060"
    },
    "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": "0x5691dc81338DFdF5e4E76Fccb79e38540ff4D380"
    },
    "src/core/flamm/FLAMMPairQuoteLib.sol": {
      "FLAMMPairQuoteLib": "0xa0c8489D5a572eAeAeEDDf48cb888c20A950c3E3"
    },
    "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.