Skip to content
Verified contractExactUNLICENSED

FLAMMBlindLib

Address0x634d5a14c42fb5bec82a7aea32bf636a8d298fcd
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,480,472
Creation transaction
0xc62098ba2e…a11ad38dbf
Libraries
src/core/mm/MMRouterLib.sol:MMRouterLib0x95b3…48ef2csrc/core/flamm/FLAMMLane.sol:FLAMMLane0x5d81…90de37src/core/flamm/FLAMMRoute.sol:FLAMMRoute0xb1ff…7fb0fesrc/periphery/FLAMMMaxima.sol:FLAMMMaxima0x6854…90a91bsrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0xf55c…49cf45src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x0be7…5ecc47src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xa5db…72803esrc/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0x2795…4cfb77src/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0x3a05…434368src/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x70ca…60bee4src/core/mm/CTokenMarketLib.sol:CTokenMarketLib0x60e4…314010src/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0x0b10…1ce950src/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x634d…298fcdsrc/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0x5dc3…aa7e91src/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0x9dbb…798f1asrc/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0x6b2b…518935src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0x99de…929869src/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0xe4be…cfac2esrc/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0x93ab…262861src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x6abb…60ea7esrc/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0x3858…f91f06src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0x4551…33b301src/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xb852…b71005src/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x6a6a…798659src/hooks/everlong/LeverageLib.sol:LeverageLib0x8039…16d055src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0xaa54…b56417src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0x3bc5…2055ddsrc/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xf6d5…9dfeef

52 files

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

src/core/flamm/FLAMMBlindLib.sol

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

import {
    FLAMMStore, Paused, InvalidConfig, PegBroken, LedgerBoundBreached, PriceUnchecked, BufferRefilled, CircularBook,
    WAD, GuardianMayOnlyTighten, IdleFloorSet, CustodyBlindSet, CreditPathSet, VenueReportsLoss, Expired,
    LocalRefill, LocalRefillSet
} from "src/core/flamm/FLAMMStore.sol";
import {FLAMMGateLib} from "src/core/flamm/FLAMMGateLib.sol";
import {FLAMMLawLib} from "src/core/flamm/FLAMMLawLib.sol";
import {FLAMMLane} from "src/core/flamm/FLAMMLane.sol";
import {FLAMMTopUpLib} from "src/core/flamm/FLAMMTopUpLib.sol";
import {FLAMMKeptLib} from "src/core/flamm/FLAMMKeptLib.sol";
import {IMMRouter} from "src/interfaces/core/mm/IMMRouter.sol";
import {IPriceFeed} from "src/interfaces/core/IPriceFeed.sol";
import {
    IFinancingAccount, CAP_ACCRUING_COLLATERAL, CAP_MUTABLE_THRESHOLD
} from "src/interfaces/core/mm/IFinancingAccount.sol";
import {ReentrancyGuardLib} from "src/libraries/ReentrancyGuardLib.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/// @notice A custody-blind pool's buffer (`FLAMMStore.CUSTODY_BLIND`): the refill, which borrows each venue's
///         debt token into custody ({refillBuffer}, `FLAMMFloatLib.refill`'s body), the gate a refill and a release
///         pass ({blindGate}, `FLAMMMaintainLib.maintain`'s release), what a flush may repay ({repayable}, the trigger
///         read under which anyone's flush repays below the reserve target among it), the idle floor's setter
///         ({setIdleFloor}) and the local refill's ({setLocalRefill}), the last three the bodies of `FLAMMFloatLib`'s
///         entries, out of that library so it keeps its room. The gate reads no custody: each venue as its lender
///         reports it and the credit law per backing token on the book with no custody and no supply, so a cheap fill,
///         which moves custody alone, moves nothing it reads. A refill that may post nothing is held to its own
///         venues alone, a local refill, only where the operator has turned that on and within its window of the
///         last whole refill ({refillBuffer}); every other refill and every release reads the whole book. A
///         linked library the pool's own libraries delegate to
///         with its storage as an argument, so no other caller reaches it (no fallback routes here), out of the cheap
///         lane's library, whose code the swap path runs.
library FLAMMBlindLib {
    /// @dev The idle floor's key in the pending table: `FLAMMFloatLib.setIdleFloor`'s selector, the entry's own, so a
    ///      scheduled cut reads as the curator made it.
    bytes4 private constant SET_IDLE_FLOOR = bytes4(keccak256("setIdleFloor(uint128)"));
    /// @dev The local refill's key in the pending table: `FLAMMFloatLib.setLocalRefill`'s selector, the entry's own.
    bytes4 private constant SET_LOCAL_REFILL = bytes4(keccak256("setLocalRefill(uint32)"));
    /// @dev The idle floor's word past the floor (`FLAMMStore.S.idleFloor`): where the local refill's window sits,
    ///      32 bits, and where the time of the last whole refill does, 48 bits.
    uint256 private constant WINDOW_SHIFT = 128;
    uint256 private constant WHOLE_SHIFT = 160;
    /// @dev The longest window the local refill takes, seconds: the longest a venue outside a refill's draws goes
    ///      unread by a refill while refills run.
    uint256 private constant MAX_LOCAL_WINDOW = 3_600;
    /// @dev A venue's lack under this share of what it posts takes no part of the law's shortfall ({_plan}): the dust a
    ///      venue at its pin gathers between refills as its debt accrues, which the refill's own venue posts instead.
    uint256 private constant DUST_WAD = 1e15;

    /// @notice `FLAMMFloatLib.initLaneTokens`'s custody-blind birth, out of that library so it keeps its room: sets the
    ///         law for the pool's life (`FLAMMStore.CUSTODY_BLIND`) and turns the credit path off, which only the
    ///         curator's `FLAMMFloatLib.setCreditPath` turns on again, through the pool's delay, where the pool's own
    ///         swap can run on its hook pair (three tokens or more, token 1 keeping no buffer). Refused
    ///         (`InvalidConfig`) where a live venue sits at a frame's account (no collateral token, `FRAME_VENUE` in
    ///         `IMMRouter.sol`), whose venues share one lender position while the gate holds each venue to its own
    ///         health ({blindGate}): the genesis venues are admitted before the law is set, out of reach of the blind
    ///         admission's refusal (`FLAMMAdmitLib._markAdmitted`), so the birth reads them.
    function birth(FLAMMStore.S storage $) public {
        uint256 live;
        for (uint256 q; q < $.pairCount; ++q) {
            live |= $.pairs[q].venues;
        }
        IMMRouter r = $.router;
        for (uint256 i; live >> i != 0; ++i) {
            if ((live >> i) & 1 == 0) continue;
            IMMRouter.VenueView memory v = r.venue(address(this), uint16(i));
            if (IFinancingAccount(v.account).COLLATERAL_ASSET() == address(0)) revert InvalidConfig();
        }
        $.features |= uint16(FLAMMStore.CUSTODY_BLIND);
        uint256 cfg = $.laneConfig;
        if (cfg & FLAMMStore.LANE_CREDIT_OFF == 0) {
            $.laneConfig = cfg | FLAMMStore.LANE_CREDIT_OFF;
            emit CreditPathSet(false);
        }
        emit CustodyBlindSet();
    }

    /// @notice `FLAMMFloatLib.refill`'s body, out of its library, under the caller's checks and lock: on a
    ///         custody-blind pool (`FLAMMStore.CUSTODY_BLIND`), borrows `amounts[i]` at venue `ids[i]` into custody,
    ///         each venue's own debt token, through the Router's borrow at that venue (`IMMRouter.borrow`, with all of
    ///         its checks: switches, drawn set, band, pin, caps, rate), posting first what its pin needs for its debt
    ///         and the draw read back a few units high (`FLAMMGateLib.READ_BACK_UNITS`), and nothing where what it
    ///         posts already covers it. Returns what it posted.
    /// @dev - One read of the venues and their prices serves every draw and the gate after them ({_walk}, {_plan}):
    ///        each indebted venue past its trigger takes its own lack to its target, and what the law per token still
    ///        lacks at the draws' collateral token goes to the venues that lack it, most in need first, the rest at the
    ///        first draw's venue. Where a venue is idle and not drawn, the prices read are those of the tokens of a
    ///        pair with a venue that read can price, one not idle or a draw's ({_prices}): a token of no such pair is
    ///        not read, and nothing reads its price.
    ///      - Every draw posts one collateral token, and all of the posts come out of at most `maxPost` of the custody
    ///        the pool owns of it.
    ///      - Refused (`LedgerBoundBreached`) while the pool asset's custody the pool owns sits under its idle floor
    ///        after the post (`FLAMMStore.S.idleFloor`: the asks' inventory, so a drain the refills run through leaves
    ///        the asks that repay; zero: no refill, `InvalidConfig`), a state check that a top-up made ahead does not
    ///        step around, though a top-up, an entry and the maintainer are not bound by it.
    ///      - The venues it posted or drew at are read again after, and both rules hold on what their lenders report.
    ///      - Refused (`InvalidConfig`) where the custody the pool owns of a drawn token after it passes the token's
    ///        reserve target, the guard that keeps a stranger's flush off the buffer (`FLAMMFloatLib.flush`): the
    ///        curator sets each borrowed token's target to the buffer it keeps, counting all the custody the pool owns
    ///        of the token, a curator's seed included (the first draw is the target less what custody already holds),
    ///        and a target left at zero takes no refill.
    ///      - The curator also holds each pair's debt cap tight (`FLAMMPolicyLib.setPairCaps`: one to two buffers, each at most
    ///        about a tenth of the book), the bound on what refills borrow over a drain.
    ///      - Refused (`VenueReportsLoss`) where it would post at a venue whose lender reports a loss on its collateral
    ///        of `FLAMMStore.LOSS_MOVE_FLOOR` or more, or takes a redemption fee of any size on it ({_requireNoLoss}).
    ///        Only a venue it posts at is read: a draw at a fee venue whose collateral already covers it, so that it
    ///        needs no new post, still lands. That reaches the keeper's and the operator's refill on a custody-blind
    ///        pool alone, and a repay of that venue's whole debt cures it.
    ///      - It needs the pool unpaused; each venue live and unfenced, of a live pair that borrows, both of its tokens
    ///        on peg, as a swap's draw needs. Each drawn token's flag and each pair's proof are cleared before its
    ///        draw, so strict mode's rule reads no stale proof.
    ///      The local refill. While the operator has it on ({setLocalRefill}: a window not zero), a refill with
    ///      `maxPost` zero is local: it prices, accrues and reads only the venues it draws at, and logs `LocalRefill`.
    ///      - Every check above holds on each drawn venue as on a whole refill: its recognized collateral carries its
    ///        debt and the draw at its pin, at the lower of the pool's price and its lender's own, with no post (a
    ///        planned post is over a budget of zero: `LedgerBoundBreached`); the idle floor; the Router's borrow; the
    ///        venue read again within its trigger; the law per token on the drawn venues' sums; the reserve targets.
    ///      - It gives up what a whole refill does for the venues it does not draw at: it neither refuses nor posts
    ///        for one past its trigger, does not prove the law per token over them, and does not refuse for another
    ///        pair without a price, not live, or owing its collateral token. It moves none of them: it posts nothing
    ///        and borrows at its own venues alone. Those venues stay the maintainer's, the keeper's top-up's and the
    ///        next whole refill's.
    ///      - It runs only within the window of the last whole refill made while it was on: a refill with `maxPost`
    ///        over zero, which reads every venue the book reads and, where it passes, writes its time. A whole refill
    ///        is the one call that renews the window: a release passes the whole gate too and writes nothing. Past
    ///        the window, and until a first whole refill after a turn-on or a longer window took effect
    ///        ({setLocalRefill}), it refuses (`Expired`, which a refill raises nowhere else), and the caller sends a
    ///        whole refill.
    ///      - Its refusals come in this order: not custody-blind, no draw or lengths apart (`InvalidConfig`); paused
    ///        (`Paused`); no idle floor (`InvalidConfig`); no whole refill on record or past its window (`Expired`);
    ///        then a whole refill's, from the draws' own checks on, read on the drawn venues alone. So a draw at a
    ///        slot no pool lists, 32 to 255, refuses `Expired` past the window and `InvalidConfig` within it. A call
    ///        whose slots are all 256 or more names no venue at all: it is no local refill, takes the whole path
    ///        and refuses `InvalidConfig` there, whatever the window.
    ///      - With the local refill off, as at birth, `maxPost` zero is a whole refill that may post nothing, and
    ///        nothing is written to the window's word.
    function refillBuffer(FLAMMStore.S storage $, uint16[] memory ids, uint256[] memory amounts, uint256 maxPost)
        public
        returns (uint256 put)
    {
        uint256 n = ids.length;
        if ($.features & FLAMMStore.CUSTODY_BLIND == 0 || n == 0 || amounts.length != n) revert InvalidConfig();
        if ($.paused) revert Paused();
        uint256 w = $.idleFloor;
        uint256 floor = uint128(w);
        if (floor == 0) revert InvalidConfig();
        uint256 slots = _slots(ids);
        // a refill that may post nothing, where the operator has the local refill on, is held to its own venues
        uint256 only = maxPost == 0 && uint32(w >> WINDOW_SHIFT) != 0 ? slots : 0;
        if (only != 0) {
            // no whole refill on record under this window, or one older than it
            uint256 wholeAt = uint48(w >> WHOLE_SHIFT);
            if (wholeAt == 0 || block.timestamp > wholeAt + uint32(w >> WINDOW_SHIFT)) revert Expired();
        }
        FLAMMGateLib.Book memory b = _prices($, slots, only);
        uint256 draws = _draws($, ids);
        if (only == 0) {
            FLAMMGateLib.accrueRead($, draws);
        } else if (!$.noLiveVenue && $.poolBits & FLAMMStore.POOL_BORROWS != 0) {
            // the drawn venues alone, where `FLAMMGateLib.accrueRead` accrues every venue a whole read reaches
            $.router.accrueExcept(uint64(~only), type(uint8).max);
        }
        (VenueRead[] memory rd, uint256[] memory posted, uint256[] memory owed) = _walk($, b, draws, only);
        uint256[] memory post = new uint256[](rd.length);
        uint256 x = _drawPlan($, b, rd, post, posted, owed, ids, amounts);
        put = _plan($, b, rd, post, posted, owed, x, ids[0]);
        if (put > _budget($, x, maxPost)) revert LedgerBoundBreached();
        if (put != 0) {
            _requireNoLoss($, rd, post);
            _postAt($, rd, post, x, put);
        }
        // the floor is a state, read after the refill's own post: a top-up ahead does not step around it
        if (FLAMMStore.ownHeld($, 0) < floor) revert LedgerBoundBreached();
        uint256 moved = _borrowAll($, rd, post, ids, amounts, b.usd) | (uint256(1) << x);
        _reread($, rd, post, posted, owed, draws);
        if (_shortfall($, b, posted, owed, FLAMMLawLib.NONE) != 0) revert LedgerBoundBreached();
        // the tokens it moved alone: the collateral it posted and each it drew
        FLAMMStore.reconcileMoved($, moved, 0, 0);
        if (only != 0) {
            emit LocalRefill(only);
        } else if (uint32(w >> WINDOW_SHIFT) != 0) {
            // a whole refill that passed, the local refill on: its time, which opens the window; nothing while off
            $.idleFloor = (w & ~(uint256(type(uint48).max) << WHOLE_SHIFT)) | block.timestamp << WHOLE_SHIFT;
        }
    }

    /// @dev The draws' venue slots as a mask, as the caller named them, unchecked: the venues {_prices} takes beside
    ///      those not idle. Read ahead of {_draws}, which checks them, so the prices are read before any draw is.
    function _slots(uint16[] memory ids) private pure returns (uint256 m) {
        for (uint256 i; i < ids.length; ++i) {
            m |= uint256(1) << ids[i];
        }
    }

    /// @dev The draws' venue slots as a mask, each once and none retired (`InvalidConfig`), woken first: a draw opens a
    ///      position there.
    function _draws(FLAMMStore.S storage $, uint16[] memory ids) private returns (uint256 draws) {
        for (uint256 i; i < ids.length; ++i) {
            uint256 bit = uint256(1) << ids[i];
            if (draws & bit != 0 || ids[i] >= FLAMMStore.MAX_POOL_VENUES) revert InvalidConfig();
            draws |= bit;
        }
        if (draws & $.retiredVenues != 0) revert InvalidConfig();
        FLAMMGateLib.wake($, draws);
    }

    /// @dev Each draw on the walk's read: its venue read and unfenced, its pair live and borrowing, one collateral
    ///      token for every draw (`InvalidConfig` otherwise), both of its pair's tokens on peg (`PegBroken`); its debt
    ///      token's flag and its pair's proof cleared; its venue's debt raised by the draw read back high, and what its
    ///      pin then needs past what it posts planned there (`post`, padded where collateral accrues; `posted` and the
    ///      read take it unpadded). Returns the collateral token.
    function _drawPlan(
        FLAMMStore.S storage $,
        FLAMMGateLib.Book memory b,
        VenueRead[] memory rd,
        uint256[] memory post,
        uint256[] memory posted,
        uint256[] memory owed,
        uint16[] memory ids,
        uint256[] memory amounts
    ) private returns (uint256 x) {
        x = FLAMMLawLib.NONE;
        for (uint256 i; i < ids.length; ++i) {
            uint256 k = _slotOf(rd, ids[i]);
            if (k == rd.length || amounts[i] == 0) revert InvalidConfig();
            VenueRead memory v = rd[k];
            FLAMMStore.PairCfg storage pc = $.pairs[v.pair];
            uint256 y = pc.debt;
            if (!pc.live || pc.borrowOff || (x != FLAMMLawLib.NONE && v.coll != x)) revert InvalidConfig();
            // the collateral token's peg once, at the first draw, each debt token's at its own
            if (x == FLAMMLawLib.NONE && !FLAMMGateLib.onPeg($, FLAMMStore.tokenOf($, v.coll), b.usd[v.coll])) {
                revert PegBroken();
            }
            x = v.coll;
            if (!FLAMMGateLib.onPeg($, FLAMMStore.tokenOf($, y), b.usd[y])) revert PegBroken();
            FLAMMStore.TokenCfg storage cy = $.tokens[y];
            if (cy.debtFree) cy.debtFree = false;
            FLAMMGateLib.drawAt($, v.pair);
            uint256 d = amounts[i] + FLAMMGateLib.READ_BACK_UNITS;
            (v.d, owed[v.pair]) = (v.d + d, owed[v.pair] + d);
            uint256 need = FLAMMGateLib.requiredPosted(v.d, pc.ltvWad, v.price);
            if (need <= v.c) continue;
            uint256 l = need - v.c;
            (post[k], posted[x], v.c) = (post[k] + l + v.slack, posted[x] + l, need);
        }
    }

    /// @dev What a refill may post of token `x`: at most `maxPost` of the custody the pool owns of it (the idle floor
    ///      is checked on the state after the post, {refillBuffer}).
    function _budget(FLAMMStore.S storage $, uint256 x, uint256 maxPost) private view returns (uint256) {
        uint256 own = FLAMMStore.ownHeld($, x);
        return maxPost < own ? maxPost : own;
    }

    /// @dev Each draw at its venue, after the posts: the Router's borrow into custody, its token's custody raised by it
    ///      (the borrow is exact; the caller reconciles), each drawn token then within its reserve target
    ///      (`InvalidConfig` past it), and each draw logged with what its venue took. Returns the drawn tokens, bit `t`
    ///      for token `t`.
    function _borrowAll(
        FLAMMStore.S storage $,
        VenueRead[] memory rd,
        uint256[] memory post,
        uint16[] memory ids,
        uint256[] memory amounts,
        uint256[] memory usd
    ) private returns (uint256 drawn) {
        IMMRouter r = $.router;
        for (uint256 i; i < ids.length; ++i) {
            uint256 k = _slotOf(rd, ids[i]);
            uint256 y = $.pairs[rd[k].pair].debt;
            r.borrow(ids[i], amounts[i], address(this), usd);
            FLAMMStore.setHeld($, y, FLAMMStore.heldOf($, y) + amounts[i]);
            drawn |= uint256(1) << y;
            emit BufferRefilled(ids[i], amounts[i], post[k]);
        }
        for (uint256 m = drawn; m != 0; m &= m - 1) {
            uint256 y;
            for (uint256 w = m; w & 1 == 0; w >>= 1) ++y;
            // the buffer within its guard: no custody of the debt token past its target, which a stranger may repay
            if (FLAMMStore.ownHeld($, y) > $.tokens[y].reserveTarget) revert InvalidConfig();
        }
    }

    /// @notice Whether `b` is a custody-blind pool's book (`FLAMMStore.CUSTODY_BLIND`). Only a cheap-lane pool can be
    ///         one, so a book with no cheap-lane bit (`FLAMMGateLib.laneOn`) reads no storage here.
    function blind(FLAMMStore.S storage $, FLAMMGateLib.Book memory b) internal view returns (bool) {
        return FLAMMGateLib.laneOn(b) && $.features & FLAMMStore.CUSTODY_BLIND != 0;
    }

    /// @dev One indebted or drawn venue as the gate reads it ({_walk}): `id`, its slot; `pair` and `coll`, its pair and
    ///      collateral token by index; `c`, its recognized collateral, and `d`, its debt, in each token's base units
    ///      (as a refill plans them, then as its lender reports them); `target` and `trig`, its target and trigger
    ///      LTVs, WAD ({_limits}); `price`, debt base units per collateral base unit, 1e36: its pair's price scale, or
    ///      the lower of that and its lender's own oracle while the pair's venue-oracle band is on ({_read}); `slack`,
    ///      what a post there pads, collateral base units ({_slack}); `lltv`, the threshold its lender liquidates
    ///      past, WAD, and `lender`, its lender's own price, 1e36, which a flush's pass-over judges it by
    ///      ({_liquidation}), set only where a flush reads the venues past their trigger ({_pastVenues}).
    struct VenueRead {
        uint16 id;
        uint8 pair;
        uint8 coll;
        uint256 c;
        uint256 d;
        uint256 target;
        uint256 trig;
        uint256 price;
        uint256 slack;
        uint256 lltv;
        uint256 lender;
    }

    /// @notice A custody-blind pool's gate after a move that may lower what it posts or raise what it owes outside a
    ///         pro-rata flow (a refill, a release: {refillBuffer}, `FLAMMMaintainLib.maintain`), at one read of every
    ///         venue the book reads ({_walk}): every indebted venue within its trigger ({_within}), priced at the
    ///         pool's price scale or, while its pair's venue-oracle band is on, at the lower of that and its lender's
    ///         own oracle, as the maintainer prices it ({_read}); and the credit law on the book with no custody and no
    ///         supply, at the pool's prices ({_shortfall}), each token's debt gross against what the pool posts of it.
    ///         Returns what it posted; `LedgerBoundBreached` where the law or a venue cannot be brought to hold.
    /// @dev - One venue is one health basis (the kinds' admission rule: a lender that pools collateral across pairs
    ///        holds each venue in an account or sub-account of its own), so no venue counts another's collateral; a
    ///        frame's account (no collateral token, `FRAME_VENUE` in `IMMRouter.sol`), whose venues share one lender
    ///        position, is refused both at a venue's admission (`FLAMMAdmitLib._markAdmitted`) and at the birth
    ///        ({birth}), which reads the venues admitted before the law, as the genesis venues are, out of the
    ///        admission's reach.
    ///      - Where `a` is a token the caller may post (`FLAMMLawLib.NONE`: none, a release, which then refuses), each
    ///        indebted venue past its trigger takes its own lack to its target where it posts `a`, and what the law
    ///        still lacks at `a` goes to the venues short of their target, most in need first, the rest at venue
    ///        `home`, the refill's own ({_plan}): no venue is then past its trigger, and none within it lends its lack
    ///        to another. All within `budget`; a venue past its trigger that posts another token, or a lack at another
    ///        token, refuses. The venues posted at are read again, and both rules hold on what their lenders credit.
    ///      What the mode holds, and what it does not:
    ///      - A cheap fill moves custody alone: no venue's collateral or debt, so nothing this gate reads.
    ///      - After a release or a whole refill that passes, every indebted venue sits within its trigger as priced
    ///        above; one at its pin stays under its lender's threshold through a fall of `1 - pin / threshold` of its
    ///        collateral's price (41.9 % at 0.5 under 0.86) counted from that venue's last time at its pin, not from
    ///        the last refill, which may have left it anywhere within its trigger, and the permissionless maintainer
    ///        takes over past the trigger as far as idle collateral goes. After a local refill that passes
    ///        ({refillBuffer}) that holds of the venues it drew at alone: another venue is where the last whole
    ///        refill and its lender's prices since have left it, a window old at most.
    ///      - A release reads and writes nothing of the local refill: only a whole refill renews its window.
    ///      - A wrong pull price on bids (a PRINT listing) loses at most its error times what bids can pay during the
    ///        episode: the buffer and every refill made in it, as far as the pair's debt cap and the out token's bucket
    ///        allow, not one buffer. A wrong word on a WORD listing, which no print fences, loses up to the same buffer
    ///        and refills, as far as the same caps allow, whatever its error. The guardian's pause stops every side,
    ///        and the keeper or the curator stops refilling on fills that run one way or, on a PRINT listing, on a gap
    ///        between the pull price and the feed.
    function blindGate(FLAMMStore.S storage $, uint256 a, uint256 budget, uint256 home) public returns (uint256 put) {
        FLAMMGateLib.Book memory b = _prices($, 0, 0);
        (VenueRead[] memory rd, uint256[] memory posted, uint256[] memory owed) = _walk($, b, 0, 0);
        uint256[] memory post = new uint256[](rd.length);
        put = _plan($, b, rd, post, posted, owed, a, home);
        if (put == 0) return 0;
        if (put > budget) revert LedgerBoundBreached();
        _postAt($, rd, post, a, put);
        _reread($, rd, post, posted, owed, 0);
        if (_shortfall($, b, posted, owed, FLAMMLawLib.NONE) != 0) revert LedgerBoundBreached();
    }

    /// @dev The gate's posts on the walk's read, by venue, added to `post`: each indebted venue past its trigger,
    ///      posting `a`, its own lack to its target (any other refuses); then what the law still lacks at `a` where it
    ///      lacks: at each indebted venue posting `a` short of its target, most in need first ({_neediest}), as far as
    ///      its own lack, a lack under `DUST_WAD` of what its venue posts passed over; what is left at venue `home`. So
    ///      no venue within its trigger but over its target lends its lack to another. Each padded once where its
    ///      venue's collateral accrues ({_slack}); `posted` and the read take them unpadded. Returns every post's sum,
    ///      `post`'s planned ones included.
    function _plan(
        FLAMMStore.S storage $,
        FLAMMGateLib.Book memory b,
        VenueRead[] memory rd,
        uint256[] memory post,
        uint256[] memory posted,
        uint256[] memory owed,
        uint256 a,
        uint256 home
    ) private view returns (uint256 put) {
        uint256 n = rd.length;
        for (uint256 k; k < n; ++k) {
            VenueRead memory v = rd[k];
            if (!_within(v)) {
                if (v.coll != a) revert LedgerBoundBreached();
                uint256 need = FLAMMGateLib.requiredPosted(v.d, v.target, v.price);
                (post[k], posted[a], v.c) = (post[k] + need - v.c + v.slack, posted[a] + need - v.c, need);
            }
            put += post[k];
        }
        uint256 short = _shortfall($, b, posted, owed, a);
        uint256 taken;
        while (short != 0) {
            (uint256 j, uint256 lack) = _neediest(rd, a, taken);
            if (j == n) break;
            taken |= uint256(1) << j;
            uint256 l = lack < short ? lack : short;
            put += _add(rd[j], post, j, l);
            (posted[a], short) = (posted[a] + l, short - l);
        }
        if (short == 0) return put;
        uint256 i = _slotOf(rd, home);
        if (i == n || rd[i].coll != a) revert LedgerBoundBreached();
        put += _add(rd[i], post, i, short);
        posted[a] += short;
    }

    /// @dev Plans a post of `l` at venue `v` (slot `k` of `post`), padded where its collateral accrues ({_slack})
    ///      unless it takes a post already: what the post adds to the refill's sum.
    function _add(VenueRead memory v, uint256[] memory post, uint256 k, uint256 l) private pure returns (uint256 put) {
        // a venue whose collateral accrues pads each post once: its pad is in `post` already where it took one
        put = post[k] == 0 ? l + v.slack : l;
        (post[k], v.c) = (post[k] + put, v.c + l);
    }

    /// @dev The venue of `rd` posting `a`, outside `taken`, furthest short of what its target needs (the most need per
    ///      unit posted), and its lack; `rd.length` where none lacks more than `DUST_WAD` of what it posts.
    function _neediest(VenueRead[] memory rd, uint256 a, uint256 taken) private pure returns (uint256 j, uint256 lack) {
        j = rd.length;
        uint256 most;
        for (uint256 k; k < rd.length; ++k) {
            VenueRead memory v = rd[k];
            if (v.coll != a || (taken >> k) & 1 != 0) continue;
            uint256 need = FLAMMGateLib.requiredPosted(v.d, v.target, v.price);
            if (need <= v.c || (need - v.c) * WAD <= v.c * DUST_WAD) continue;
            uint256 r = v.c == 0 ? type(uint256).max : Math.mulDiv(need, WAD, v.c);
            if (r > most) (j, lack, most) = (k, need - v.c, r);
        }
    }

    /// @dev The index in `rd` of venue `id`, `rd.length` where it reads none so.
    function _slotOf(VenueRead[] memory rd, uint256 id) private pure returns (uint256 k) {
        for (; k < rd.length && rd[k].id != id; ++k) {}
    }

    /// @dev Reverts `VenueReportsLoss` where a venue the refill would post at (`post[k]` nonzero) reports a loss on its
    ///      collateral of `FLAMMStore.LOSS_MOVE_FLOOR` or more, or takes a redemption fee of any size on it
    ///      (`FLAMMKeptLib.lossAtFloor`), its marks read first
    ///      (`FLAMMKeptLib.recordLossMarks`): the caller sizes the post, and NAV, which counts custody at par and cuts
    ///      what is posted by that ratio, would fall by the ratio's share of it in the call, as at the maintenance
    ///      path's top-up. A venue that owes there is covered by the collateral maintainer, which the posting law
    ///      sizes, and by the operator's emergency top-up. A venue it only borrows at, with no new post, is not in the
    ///      mask, so a refill can still borrow at a fee venue that needs no post; a repay of that venue's whole debt
    ///      cures it. Read only on a pool that lists a venue whose kind reports a loss (`FLAMMStore.LOSS_MARKS`).
    function _requireNoLoss(FLAMMStore.S storage $, VenueRead[] memory rd, uint256[] memory post) private {
        if ($.features & FLAMMStore.LOSS_MARKS == 0) return;
        FLAMMKeptLib.recordLossMarks();
        uint256 at;
        for (uint256 k; k < rd.length; ++k) {
            if (post[k] != 0) at |= uint256(1) << rd[k].id;
        }
        // a redemption fee of any size too: the post's way out pays it
        if (FLAMMKeptLib.lossAtFloor(at, FLAMMStore.LOSS_LEG_COLLATERAL | FLAMMStore.LOSS_LEG_FEES)) {
            revert VenueReportsLoss();
        }
    }

    /// @dev Posts `post[k]` of token `a` at each venue `rd[k]`, `put` in all, out of the custody the pool owns.
    function _postAt(FLAMMStore.S storage $, VenueRead[] memory rd, uint256[] memory post, uint256 a, uint256 put)
        private
    {
        address tok = FLAMMStore.tokenOf($, a);
        FLAMMStore.setHeld($, a, FLAMMStore.heldOf($, a) - put);
        FLAMMStore.grant($, tok, put);
        IMMRouter r = $.router;
        for (uint256 k; k < rd.length; ++k) {
            if (post[k] != 0) r.postCollateral(rd[k].id, post[k]);
        }
        FLAMMStore.revoke($, tok);
    }

    /// @dev Reads again each venue `rd[k]` posted at (`post[k]` nonzero) or drawn at (in `draws`): `posted` and `owed`
    ///      move from its planned read to what its lender now reports, and it must be within its trigger on that
    ///      (`LedgerBoundBreached`).
    function _reread(
        FLAMMStore.S storage $,
        VenueRead[] memory rd,
        uint256[] memory post,
        uint256[] memory posted,
        uint256[] memory owed,
        uint256 draws
    ) private view {
        IMMRouter r = $.router;
        for (uint256 k; k < rd.length; ++k) {
            VenueRead memory v = rd[k];
            if (post[k] == 0 && (draws >> v.id) & 1 == 0) continue;
            (uint256 c0, uint256 d0) = (v.c, v.d);
            (, v.c,,, v.d) = r.venuePosition(address(this), v.id);
            (posted[v.coll], owed[v.pair]) = (posted[v.coll] - c0 + v.c, owed[v.pair] - d0 + v.d);
            if (!_within(v)) revert LedgerBoundBreached();
        }
    }

    /// @dev Whether indebted venue `v` is within its trigger: its collateral carries its debt at its trigger LTV.
    function _within(VenueRead memory v) private pure returns (bool) {
        return v.c >= FLAMMGateLib.requiredPosted(v.d, v.trig, v.price);
    }

    /// @dev The gate's one read of the venues the book reads (none retired, idle or fenced) and of the venues in
    ///      `draws`, each from its lender: each one's recognized collateral summed by its collateral token and its debt
    ///      by its pair, as the Router's book and the per-pair read sum them, and the read ({VenueRead}, {_read}) at
    ///      `b`'s prices of each one that owes or takes a draw (`InvalidConfig` for a fenced one). A local refill's
    ///      (`only` not zero: its draws) reads the venues in `only` and no other, so its sums are theirs alone.
    function _walk(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 draws, uint256 only)
        private
        view
        returns (VenueRead[] memory rd, uint256[] memory posted, uint256[] memory owed)
    {
        IMMRouter r = $.router;
        uint256 n = r.venueCount(address(this));
        uint256 skip = only != 0 ? ~only : (uint256($.retiredVenues) | $.idleVenues) & ~draws;
        rd = new VenueRead[](n);
        (posted, owed) = (new uint256[](b.legs.length), new uint256[]($.pairCount));
        uint256[] memory pv = new uint256[]($.pairCount);
        uint256 k;
        for (uint256 i; i < n; ++i) {
            if ((skip >> i) & 1 != 0) continue;
            bool draw = (draws >> i) & 1 != 0;
            (, uint256 c,,, uint256 d) = r.venuePosition(address(this), uint16(i));
            if ((c | d) == 0 && !draw) continue;
            IMMRouter.VenueView memory v = r.venue(address(this), uint16(i));
            // a fenced venue: the book reads it not, and it takes no post or draw
            if (v.status != 0) {
                if (draw) revert InvalidConfig();
                continue;
            }
            (posted[v.coll], owed[v.pair]) = (posted[v.coll] + c, owed[v.pair] + d);
            if (d == 0 && !draw) continue;
            VenueRead memory x = rd[k++];
            (x.id, x.pair, x.coll, x.c, x.d) = (uint16(i), v.pair, v.coll, c, d);
            _read(r, v, x, FLAMMGateLib.frameOf(b, v.coll, v.debt), pv, $.pairs[v.pair].ltvWad, b.legs[v.coll].scale);
        }
        assembly ("memory-safe") {
            mstore(rd, k)
        }
    }

    /// @dev The credit law on the book with no custody and no supply, from the walk's sums: each live pair's debt
    ///      (`owed`, by pair) charged at its collateral token's price scale and its LTV, against what the pool posts of
    ///      that token (`posted`, by token), so a token owed at two or more pairs carries each pair's whole debt
    ///      (`FLAMMLawLib`'s forced load, as nothing held nets it). Returns what the law lacks at token `a`, the one
    ///      token the caller may post; `LedgerBoundBreached` where it lacks at another (`FLAMMLawLib.NONE`: any) or a
    ///      pair that is not live owes; `CircularBook` where an indebted pair's collateral is owed; `PriceUnchecked`
    ///      where a charged pair's price scale is unchecked.
    function _shortfall(
        FLAMMStore.S storage $,
        FLAMMGateLib.Book memory b,
        uint256[] memory posted,
        uint256[] memory owed,
        uint256 a
    ) private view returns (uint256 short) {
        uint256 m = owed.length;
        uint256[] memory load = new uint256[](posted.length);
        uint256 owing;
        for (uint256 q; q < m; ++q) {
            if (owed[q] != 0) owing |= uint256(1) << $.pairs[q].debt;
        }
        for (uint256 q; q < m; ++q) {
            uint256 d = owed[q];
            if (d == 0) continue;
            FLAMMStore.PairCfg storage pc = $.pairs[q];
            (uint256 x, uint256 t) = (pc.coll, pc.debt);
            if (!pc.live) revert LedgerBoundBreached();
            if ((owing >> x) & 1 != 0) revert CircularBook();
            uint256 p = FLAMMGateLib.frameOf(b, x, t);
            if (p == 0) revert PriceUnchecked();
            load[x] += FLAMMLawLib.term(d, p, pc.ltvWad);
        }
        for (uint256 t; t < posted.length; ++t) {
            uint256 g = posted[t] * WAD;
            if (load[t] <= g) continue;
            if (t != a) revert LedgerBoundBreached();
            short = (load[t] - g + WAD - 1) / WAD;
        }
    }

    /// @dev Venue `v`'s read past its figures (`x`): its price, the pool's price scale `p` (zero: `PriceUnchecked`) or,
    ///      while its pair's venue-oracle band is on, the lower of that and its lender's own oracle, as the maintainer
    ///      prices a due venue (`FLAMMTopUpLib`), so the gate and the maintainer read one venue alike; its target and
    ///      trigger ({_limits}); its pad ({_slack}). `pv` holds each pair's band and gap, read once.
    function _read(
        IMMRouter r,
        IMMRouter.VenueView memory v,
        VenueRead memory x,
        uint256 p,
        uint256[] memory pv,
        uint256 pin,
        uint256 scale
    ) private view {
        if (p == 0) revert PriceUnchecked();
        uint256 w = pv[v.pair];
        if (w == 0) {
            IMMRouter.PairView memory pr = r.pair(address(this), v.pair);
            w = (uint256(1) << 255) | (uint256(pr.oracleBandWad) << 64) | pr.safetyGapWad;
            pv[v.pair] = w;
        }
        if (uint64(w >> 64) != 0 && v.lltvWad != 0) {
            (bool ok, uint256 q) = IFinancingAccount(v.account).oraclePrice(v.id);
            if (ok && q != 0 && q < p) p = q;
        }
        uint256 caps = IFinancingAccount(v.account).capabilities();
        (x.target, x.trig) = _limits(v.lltvWad, pin, uint64(w), caps);
        (x.price, x.slack) = (p, _slack(v, caps, scale));
    }

    /// @dev A venue's target and trigger LTVs at threshold `lltv`, the maintainer's (`FLAMMTopUpLib`): the target is
    ///      its pair's pin `pin`, or, at a kind whose threshold can fall (`CAP_MUTABLE_THRESHOLD`) and was cut under
    ///      the pin plus the pair's gap `gap` but not to it, the threshold less the gap; a cut to the gap or under it
    ///      keeps the pin, as before the cut, where the venue is then within its trigger at or under its pin (and no
    ///      draw runs there: the Router's pin check refuses it). The trigger is `MAINTAIN_ROOM_SHARE_WAD` of the room
    ///      from the target to the threshold past it, the target where the threshold is under it. The maintainer keeps
    ///      the pin too where custody cannot bring the venue under its threshold at the lower price; the gate, which
    ///      reads no custody, holds such a venue to the cut target, the stricter.
    function _limits(uint256 lltv, uint256 pin, uint256 gap, uint256 caps)
        private
        pure
        returns (uint256 target, uint256 trig)
    {
        target = pin;
        if (caps & CAP_MUTABLE_THRESHOLD != 0 && lltv < pin + gap && lltv > gap) target = lltv - gap;
        trig = lltv > target ? target + (lltv - target) * FLAMMTopUpLib.MAINTAIN_ROOM_SHARE_WAD / WAD : target;
    }

    /// @dev What a post at venue `v` pads past its need where its collateral accrues (`CAP_ACCRUING_COLLATERAL`): one
    ///      unit's assets, at most a millionth of one whole collateral token (its scale `scale`), and one, which the
    ///      lender's rounding may keep of the post, as the Router pads its plan's posts (`MMRouterLib._postSlack`).
    function _slack(IMMRouter.VenueView memory v, uint256 caps, uint256 scale) private view returns (uint256 s) {
        if (caps & CAP_ACCRUING_COLLATERAL == 0) return 0;
        s = IFinancingAccount(v.account).collateralUnitsToAssets(v.id, 1);
        uint256 most = 1e12 / scale;
        return (s < most ? s : most) + 1;
    }

    /// @notice What a flush on a custody-blind pool repays of token `a` at pair `p` (`FLAMMStore.NO_PAIR`: every pair
    ///         owing it) out of `own`, the custody the pool owns of it, toward `owed` (`FLAMMFloatLib.flush`,
    ///         `flushPair`, which repay what this returns and count every repay by the token's balance): for the keeper
    ///         or the curator all it owes, as far as custody goes; for anyone else the custody past the token's reserve
    ///         target, the buffer a refill borrowed ({refillBuffer}), so no stranger unwinds it and the
    ///         refill's gas and interest are not anyone's to waste. Where custody does not cover the whole debt (the
    ///         keeper's or the curator's call) or the target holds some custody back (anyone else's), and an indebted
    ///         venue of those pairs is past its trigger, as the gate prices it ({_read}), the caller first repays
    ///         here at each such venue, most past first, as far as its debt over what its collateral carries at its
    ///         target ({_repayPast}), so exits reopen and the lender does not liquidate it while the buffer sits in
    ///         custody, and no repay in the Router's order lands at a healthy venue first; then the custody left (the
    ///         keeper's or the curator's) or the custody still past the target. A venue that is under water at that
    ///         price, or that the repay cannot bring back under the threshold its lender liquidates past, and that
    ///         its lender reads unhealthy, is passed over ({_lost}). Under water, a repay would pay the lender's bad
    ///         debt from the custody every share owns. Past the threshold and not under water, the pass-over gives
    ///         something up: a liquidator repays the venue's debt and takes that much collateral and its incentive on
    ///         top (about 4.4 % at a 0.86 threshold), so each unit repaid first would save about 4.4 % of itself. It
    ///         is given up so that no stranger spends the buffer into a venue its lender liquidates anyway: the
    ///         keeper's or the curator's flush, which repays there as far as custody goes, is the path that saves it,
    ///         or the curator's fence. Anyone else's flush repays nothing at
    ///         a venue passed over: its custody past the target goes venue by venue to the other venues
    ///         ({_repayBeside}), never through the Router's order, which reads no venue's health, and the cure reads
    ///         the venues whatever custody the flush holds, so custody that covers the whole debt reaches no such
    ///         venue either; and that flush lends nothing of the token (`held`): its lend would go to the lender
    ///         whose own check reads the pool's venue unhealthy, where a supplier bears a share of the bad debt a
    ///         liquidation leaves, the pool's own among it. A pair whose price cannot be read counts no venue, so none of its venues is passed
    ///         over. A repay never raises a venue's ratio, so it needs no gate after it.
    function repayable(FLAMMStore.S storage $, uint256 a, uint256 own, uint256 owed, uint8 p)
        public
        returns (uint256 pay, bool held)
    {
        pay = owed < own ? owed : own;
        bool kept = msg.sender == $.core.keeper() || msg.sender == $.core.owner();
        // the keeper's or the curator's repay of the whole debt cures every venue
        if (kept && own >= owed) return (pay, false);
        uint256 t = kept ? 0 : $.tokens[a].reserveTarget;
        (uint256 owing,) = FLAMMStore.lanes($, a);
        if (p != FLAMMStore.NO_PAIR) owing &= uint256(1) << p;
        (uint256 cured, uint256 passed) = _repayPast($, a, owing, pay);
        (own, owed) = (own - cured, owed - cured);
        uint256 rest = own > t ? own - t : 0;
        pay = rest < owed ? rest : owed;
        if (!kept && passed != 0) {
            if (pay != 0) _repayBeside($, a, owing, passed, pay);
            (pay, held) = (0, true);
        }
    }

    /// @dev Anyone else's repay of token `a` beside the venues the cure passed over (`passed`, bit `i` for venue `i`):
    ///      out of at most `budget` of the token's custody, at each indebted venue of the pairs in `pairs` outside
    ///      `passed`, in slot order, each as far as its debt; a venue that refuses a repay now is passed over, as the
    ///      Router's cascade passes it. The caller counts what it repaid by the token's balance.
    function _repayBeside(FLAMMStore.S storage $, uint256 a, uint256 pairs, uint256 passed, uint256 budget) private {
        IMMRouter r = $.router;
        address tok = FLAMMStore.tokenOf($, a);
        FLAMMStore.approveRouter($, tok, budget);
        passed |= $.retiredVenues;
        for (uint256 q; pairs >> q != 0 && budget != 0; ++q) {
            if ((pairs >> q) & 1 == 0) continue;
            for (uint256 m = $.pairs[q].venues & ~passed; m != 0 && budget != 0; m &= m - 1) {
                uint256 i;
                for (uint256 w = m; w & 1 == 0; w >>= 1) ++i;
                (,,,, uint256 d) = r.venuePosition(address(this), uint16(i));
                if (d == 0 || FLAMMGateLib.repayRefused($, i)) continue;
                // the grant left, as {_repayPast} counts it
                r.repay(uint16(i), budget < d ? budget : d);
                budget = FLAMMStore.granted($, tok);
            }
        }
        FLAMMStore.revoke($, tok);
    }

    /// @dev Repays token `a` at each indebted venue of a pair in `pairs` (bit `p` for pair `p`) past its trigger, as
    ///      the gate prices it ({_read}; a pair whose price cannot be read counts no venue), the furthest past first
    ///      ({_mostPast}), each as far as its debt over what its collateral carries at its target, out of at most
    ///      `budget` of the token's custody; a venue that refuses a repay now is passed over, and so is one the repay
    ///      cannot save ({_lost}). Returns what it repaid, and the venues it passed over as past saving (`passed`, bit
    ///      `i` for venue `i`).
    function _repayPast(FLAMMStore.S storage $, uint256 a, uint256 pairs, uint256 budget)
        private
        returns (uint256 cured, uint256 passed)
    {
        IMMRouter r = $.router;
        VenueRead[] memory rd = _pastVenues($, r, pairs);
        if (rd.length == 0) return (0, 0);
        address tok = FLAMMStore.tokenOf($, a);
        FLAMMStore.approveRouter($, tok, budget);
        uint256 done;
        while (budget != 0) {
            (uint256 j, uint256 lack) = _mostPast(rd, done);
            if (j == rd.length) break;
            done |= uint256(1) << j;
            if (FLAMMGateLib.repayRefused($, rd[j].id)) continue;
            if (lack > budget) lack = budget;
            if (_lost(rd[j], lack) && !_lenderHealthy(r, rd[j].id)) {
                passed |= uint256(1) << rd[j].id;
                continue;
            }
            // the grant left, not the budget less what the venue took: a venue that takes less than the Router
            // pulled returns the rest to custody, where it stays, as `FLAMMSettleLib._repayInput` counts it
            cured += r.repay(rd[j].id, lack);
            budget = FLAMMStore.granted($, tok);
        }
        FLAMMStore.revoke($, tok);
    }

    /// @dev The indebted venues of the pairs in `pairs`, none retired, idle or fenced, past their trigger.
    function _pastVenues(FLAMMStore.S storage $, IMMRouter r, uint256 pairs)
        private
        view
        returns (VenueRead[] memory rd)
    {
        rd = new VenueRead[](r.venueCount(address(this)));
        uint256[] memory pv = new uint256[]($.pairCount);
        uint256 skip = $.retiredVenues | $.idleVenues;
        uint256 k;
        for (uint256 q; pairs >> q != 0; ++q) {
            if ((pairs >> q) & 1 == 0) continue;
            FLAMMStore.PairCfg storage pc = $.pairs[q];
            (uint8 x, uint8 y) = (pc.coll, pc.debt);
            (bool ok, uint256 ux, uint256 uy,) =
                $.priceFeed.peekPair(FLAMMStore.tokenOf($, x), FLAMMStore.tokenOf($, y));
            uint256 p = ok ? FLAMMGateLib.frame(ux, uy, _scaleOf($, x), _scaleOf($, y)) : 0;
            if (p == 0) continue;
            for (uint256 m = pc.venues & ~skip; m != 0; m &= m - 1) {
                uint256 i;
                for (uint256 w = m; w & 1 == 0; w >>= 1) ++i;
                (, uint256 c,,, uint256 d) = r.venuePosition(address(this), uint16(i));
                if (d == 0) continue;
                IMMRouter.VenueView memory v = r.venue(address(this), uint16(i));
                if (v.status != 0) continue;
                VenueRead memory e = rd[k];
                (e.id, e.pair, e.coll, e.c, e.d) = (uint16(i), v.pair, v.coll, c, d);
                _read(r, v, e, p, pv, pc.ltvWad, _scaleOf($, x));
                if (_within(e)) continue;
                (e.lltv, e.lender) = _liquidation(v, e.price);
                ++k;
            }
        }
        assembly ("memory-safe") {
            mstore(rd, k)
        }
    }

    /// @dev Whether a repay of `rep` cannot save venue `v`: it is under water at its read price, its debt worth more
    ///      than its collateral, or the repay leaves it past the threshold its lender liquidates past, at its lender's
    ///      own price ({_liquidation}). {_repayPast} passes such a venue over only where its lender's own check reads
    ///      it unhealthy too ({_lenderHealthy}).
    ///      - Under water is read at the read price, the lower of the pool's and the lender's while the pair's band
    ///        is on: where the pool's price is right the venue's collateral is worth less than what a repay pays for
    ///        it, whatever its lender reads.
    ///      - Whether the repay restores the lender's health is the lender's to judge, so it is read at the lender's
    ///        own price and threshold: read at the lower price, or at a borrow ceiling, a repay that would restore
    ///        the lender's health was skipped.
    ///      Every venue of a custody-blind pool sits at a pair's own account ({birth}), whose lender liquidates on
    ///      that venue alone. Under water is read first, whatever the threshold: a threshold of zero (a lender's
    ///      brake on the collateral, which {_liquidation} sizes at the lender's own or at one whole) once read as
    ///      none lost, and a stranger's flush then repaid into a venue under water.
    function _lost(VenueRead memory v, uint256 rep) private pure returns (bool) {
        if (Math.mulDiv(v.c, v.price, 1e36) < v.d) return true;
        return v.lltv != 0 && FLAMMGateLib.requiredPosted(v.d - rep, v.lltv, v.lender) > v.c;
    }

    /// @dev What {_lost} judges venue `v` by past its read price `p`: the threshold its lender liquidates past, and
    ///      its lender's own price.
    ///      - The threshold is the lender's own (`FLAMMGateLib.liquidationWad`): `lltv` where it is that threshold,
    ///        the kind's own read of it where `lltv` may be a borrow ceiling under it or zero, and one whole where no
    ///        read answers it, so that only a venue under water is passed over there. It is never zero.
    ///      - The price is its lender's own oracle's where it reads, whatever the pair's band, else `p`.
    function _liquidation(IMMRouter.VenueView memory v, uint256 p) private view returns (uint256 lltv, uint256 price) {
        (lltv, price) = (FLAMMGateLib.liquidationWad(v), p);
        (bool ok, uint256 q) = IFinancingAccount(v.account).oraclePrice(v.id);
        if (ok && q != 0) price = q;
    }

    /// @dev Venue `id`'s lender's own check of its position (`IMMRouter.venueHealthy`); a read that reverts reads
    ///      healthy, so the repay runs as before.
    function _lenderHealthy(IMMRouter r, uint16 id) private view returns (bool) {
        try r.venueHealthy(address(this), id) returns (bool h) {
            return h;
        } catch (bytes memory reason) {
            ReentrancyGuardLib._passOnLock(reason);
            return true;
        }
    }

    /// @dev The venue of `rd` outside `done` furthest past its trigger (the most it needs at its trigger per unit it
    ///      posts), and its debt over what its collateral carries at its target, rounded up; `rd.length` where none.
    function _mostPast(VenueRead[] memory rd, uint256 done) private pure returns (uint256 j, uint256 lack) {
        j = rd.length;
        uint256 most;
        for (uint256 k; k < rd.length; ++k) {
            if ((done >> k) & 1 != 0) continue;
            VenueRead memory v = rd[k];
            uint256 need = FLAMMGateLib.requiredPosted(v.d, v.trig, v.price);
            uint256 r = v.c == 0 ? type(uint256).max : Math.mulDiv(need, WAD, v.c);
            if (r <= most) continue;
            uint256 carried = Math.mulDiv(Math.mulDiv(v.c, v.price, 1e36), v.target, WAD);
            (j, lack, most) = (k, v.d > carried ? v.d - carried : 0, r);
        }
    }

    /// @notice `FLAMMFloatLib.setIdleFloor`'s body, out of that library so it keeps its room: on a custody-blind pool
    ///         (`InvalidConfig` on any other), the curator's or the guardian's raise of the idle floor applies at once
    ///         and drops a scheduled cut; a cut is the curator's alone, through the pending table (`FLAMMLane.capDue`):
    ///         the first call schedules it for the pool's delay, the identical call within one more delay applies it.
    ///         A floor of zero runs no refill, so its raise turns refills on: the curator's alone, never the
    ///         guardian's.
    function setIdleFloor(FLAMMStore.S storage $, uint128 floor) public {
        uint256 w = $.idleFloor;
        uint256 cur = uint128(w);
        bool tight = floor >= cur;
        bool guardian = FLAMMStore.curatorOrGuardian($);
        if (guardian && (!tight || cur == 0)) revert GuardianMayOnlyTighten();
        ReentrancyGuardLib._guard();
        if ($.features & FLAMMStore.CUSTODY_BLIND == 0) revert InvalidConfig();
        if (FLAMMLane.capDue($, tight, abi.encode(SET_IDLE_FLOOR, floor)) == 0) {
            // the floor alone: the word's upper bits are the local refill's ({setLocalRefill})
            $.idleFloor = (w >> WINDOW_SHIFT << WINDOW_SHIFT) | floor;
            emit IdleFloorSet(floor);
        }
        ReentrancyGuardLib._unlockGuard();
    }

    /// @notice `FLAMMFloatLib.setLocalRefill`'s body, out of that library so it keeps its room: on a custody-blind pool
    ///         (`InvalidConfig` on any other, and for a window past `MAX_LOCAL_WINDOW`), the curator's or the
    ///         guardian's cut of the local refill's window, the turn-off (zero) among them, applies at once and drops
    ///         a scheduled raise; a raise, the turn-on among them, is the curator's alone, through the pending table
    ///         (`FLAMMLane.capDue`): the first call schedules it for the pool's delay, the identical call within one
    ///         more delay applies it, and the curator or the guardian cancels it (`FLAMMAdmitLib.cancel`). The floor
    ///         is kept. A raise that takes effect, the turn-on among them, and a turn-off drop the time of the last
    ///         whole refill, so the first local refill under a longer window waits for a whole refill made under it;
    ///         a cut that leaves it on keeps that time, as it only shortens the window.
    function setLocalRefill(FLAMMStore.S storage $, uint32 window) public {
        uint256 w = $.idleFloor;
        bool tight = window <= uint32(w >> WINDOW_SHIFT);
        bool guardian = FLAMMStore.curatorOrGuardian($);
        if (guardian && !tight) revert GuardianMayOnlyTighten();
        ReentrancyGuardLib._guard();
        if ($.features & FLAMMStore.CUSTODY_BLIND == 0 || window > MAX_LOCAL_WINDOW) revert InvalidConfig();
        if (FLAMMLane.capDue($, tight, abi.encode(SET_LOCAL_REFILL, window)) == 0) {
            // a raise and a turn-off start with no whole refill on record; a cut keeps the one it has
            if (!tight || window == 0) w &= ~(uint256(type(uint48).max) << WHOLE_SHIFT);
            $.idleFloor = (w & ~(uint256(type(uint32).max) << WINDOW_SHIFT)) | uint256(window) << WINDOW_SHIFT;
            emit LocalRefillSet(window);
        }
        ReentrancyGuardLib._unlockGuard();
    }

    /// @dev The book's prices alone, for the gate, which reads no custody, on legs that carry only their scale. Where
    ///      the walk skips no venue for being idle, every token's USD price and price scale (`FLAMMGateLib.priceIn`).
    ///      Where it skips one (an idle venue outside `touch`, bit `i`: venue `i`, a draw's), those of each token of
    ///      a pair with a venue the walk can read at a price ({_walk}): a live venue not idle, or one in `touch`. Any
    ///      other token then reads zero, as an unchecked one does: the walk reads no venue of its pairs, so no
    ///      venue's read, draw or post and no term of the law takes its price ({_read}, {_drawPlan}, {_shortfall}),
    ///      and the Router's borrow reads the drawn pair's two alone (`MMRouterLib.priceOf`).
    ///      - Each price read is the one `FLAMMGateLib.priceIn` makes, none reverting: where token 1 is wanted, the
    ///        pool asset and token 1 from one read of their pair and, where that does not answer, a token past them
    ///        is listed and the pool asset is wanted, the pool asset alone; where token 1 is not wanted, the pool
    ///        asset alone, which is that read's answer where the pair answers and what it falls back to where it does
    ///        not (`PriceFeed`, `MarketOracleFeed`: a pair's answer is each token's own under one check); every other
    ///        wanted token from its own. So a feed bound to a pool of three or more tokens must answer a pair's base
    ///        as that token's own read answers it: a pool of two tokens reads its one pair either way.
    ///      - A pair's live venues are its `venues` (`FLAMMAdmitLib`, `FLAMMFenceLib`: set at an admission and at a
    ///        fence's lift, cleared at a retirement and at a fence), so the pairs taken hold every venue the walk
    ///        does not skip.
    ///      - A pool with no band reads no price (`FLAMMStore.bandOff`).
    ///      - A local refill's (`only` not zero: its draws) are those of its draws' pairs' tokens alone: the walk then
    ///        skips every venue outside `only`.
    function _prices(FLAMMStore.S storage $, uint256 touch, uint256 only)
        private
        view
        returns (FLAMMGateLib.Book memory b)
    {
        uint256 n = $.tokenCount;
        (b.legs, b.usd) = (new FLAMMGateLib.Leg[](n), new uint256[](n));
        b.legs[0].scale = $.shareScale;
        for (uint256 t = 1; t < n; ++t) {
            b.legs[t].scale = $.tokens[t].scale;
        }
        uint256 skip = only != 0 ? ~only : $.idleVenues & ~touch;
        if (skip == 0) {
            FLAMMGateLib.priceIn($, b);
            return b;
        }
        if (FLAMMStore.bandOff($)) return b;
        uint256 want;
        uint256 m = $.pairCount;
        for (uint256 q; q < m; ++q) {
            FLAMMStore.PairCfg storage pc = $.pairs[q];
            if (pc.venues & ~skip != 0) want |= (uint256(1) << pc.coll) | (uint256(1) << pc.debt);
        }
        IPriceFeed feed = $.priceFeed;
        bool alone = want & 1 != 0;
        if (want & 2 != 0) {
            (bool ok, uint256 u0, uint256 u1,) = feed.peekPair($.poolAsset, $.tokens[1].token);
            if (ok) (b.usd[0], b.usd[1]) = (u0, u1);
            alone = alone && !ok && n > 2;
        }
        if (alone) {
            (bool ok0, uint256 v0,) = feed.peekUsd($.poolAsset);
            if (ok0) b.usd[0] = v0;
        }
        for (uint256 t = 2; t < n; ++t) {
            if ((want >> t) & 1 == 0) continue;
            (bool ok, uint256 v,) = feed.peekUsd($.tokens[t].token);
            if (ok) b.usd[t] = v;
        }
        FLAMMGateLib.frameAll(b);
    }

    /// @dev Token `t`'s scale: the pool asset's from the first word.
    function _scaleOf(FLAMMStore.S storage $, uint256 t) private view returns (uint256) {
        return t == 0 ? $.shareScale : $.tokens[t].scale;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {
    "src/core/mm/MMRouterLib.sol": {
      "MMRouterLib": "0x95b386d242c061ab2551a0d294c94dfe3948ef2c"
    },
    "src/core/flamm/FLAMMLane.sol": {
      "FLAMMLane": "0x5d81d4a7cfd40c3dfe9e009212545608be90de37"
    },
    "src/core/flamm/FLAMMRoute.sol": {
      "FLAMMRoute": "0xb1ffeae12c53f876aa0e495e9c00c829f47fb0fe"
    },
    "src/periphery/FLAMMMaxima.sol": {
      "FLAMMMaxima": "0x68546ce65986354c5394e4bc2f28027ef490a91b"
    },
    "src/core/flamm/FLAMMLawLib.sol": {
      "FLAMMLawLib": "0xf55c5807b6fbe5555443fd6ddbbd52079849cf45"
    },
    "src/core/flamm/FLAMMOpsLib.sol": {
      "FLAMMOpsLib": "0x0be7fdb3d611b05df90a61778a644654735ecc47"
    },
    "src/core/mm/AaveV3ReadsLib.sol": {
      "AaveV3ReadsLib": "0xa5db415d1af2158dd0a4a3c9c1eada277472803e"
    },
    "src/core/flamm/FLAMMFlowLib.sol": {
      "FLAMMFlowLib": "0x27957f4ddf818de39a1c9dba0bf273a5994cfb77"
    },
    "src/core/flamm/FLAMMGateLib.sol": {
      "FLAMMGateLib": "0x3a05779218510235badcbddcdd78732a16434368"
    },
    "src/core/flamm/FLAMMKeptLib.sol": {
      "FLAMMKeptLib": "0x70cace9076ac8dd6a691ced2f9aa62a5c360bee4"
    },
    "src/core/mm/CTokenMarketLib.sol": {
      "CTokenMarketLib": "0x60e4ab6b6ba72325c58924ee7753b14b37314010"
    },
    "src/core/flamm/FLAMMAdmitLib.sol": {
      "FLAMMAdmitLib": "0x0b107b1f0c64f3716554ccc83b53e492e51ce950"
    },
    "src/core/flamm/FLAMMBlindLib.sol": {
      "FLAMMBlindLib": "0x634d5a14c42fb5bec82a7aea32bf636a8d298fcd"
    },
    "src/core/flamm/FLAMMClaimLib.sol": {
      "FLAMMClaimLib": "0x5dc3bb30c60390ce9522b7e3ca315dd334aa7e91"
    },
    "src/core/flamm/FLAMMFenceLib.sol": {
      "FLAMMFenceLib": "0x9dbba0cbd9d7883f4eedd1c8e08780fac4798f1a"
    },
    "src/core/flamm/FLAMMFloatLib.sol": {
      "FLAMMFloatLib": "0x6b2b25ebba12e78afea697b9ac6d2167a6518935"
    },
    "src/core/flamm/FLAMMQuoteLib.sol": {
      "FLAMMQuoteLib": "0x99de54a108c64ebe23ac7766901c199a91929869"
    },
    "src/core/flamm/FLAMMTopUpLib.sol": {
      "FLAMMTopUpLib": "0xe4be161081d1c9aa91951ca347cc99da35cfac2e"
    },
    "src/core/mm/CTokenRewardsLib.sol": {
      "CTokenRewardsLib": "0x93ab647215a9f9f1050302a76506afcbc0262861"
    },
    "src/core/mm/MMRouterAdminLib.sol": {
      "MMRouterAdminLib": "0x6abb06b1e9cba80888992d366913bb9b7760ea7e"
    },
    "src/core/flamm/FLAMMPolicyLib.sol": {
      "FLAMMPolicyLib": "0x3858e2202cebcb6f12f36a596260dd2ed8f91f06"
    },
    "src/core/flamm/FLAMMSettleLib.sol": {
      "FLAMMSettleLib": "0x4551cddb1de95f5452f6a0f836e047e01833b301"
    },
    "src/core/flamm/FLAMMSharedLib.sol": {
      "FLAMMSharedLib": "0xb852d9cbdda85cbed7da0885bca2714ba1b71005"
    },
    "src/periphery/FLAMMExitMaxima.sol": {
      "FLAMMExitMaxima": "0x6a6a3ff1e834dbbf07dee472e07d1ca977798659"
    },
    "src/hooks/everlong/LeverageLib.sol": {
      "LeverageLib": "0x80396f9f894cc3060dfaa7468c4f576e8b16d055"
    },
    "src/core/flamm/FLAMMMaintainLib.sol": {
      "FLAMMMaintainLib": "0xaa5434e13eb54f37c577229efc981cceceb56417"
    },
    "src/core/flamm/FLAMMPairQuoteLib.sol": {
      "FLAMMPairQuoteLib": "0x3bc57bc05cc9dd1fe18106add8ffc060882055dd"
    },
    "src/hooks/everlong/EverlongOpsLib.sol": {
      "EverlongOpsLib": "0xf6d56f4ed6a7c441fd96c53a327026bac19dfeef"
    }
  },
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
    "forge-std/=lib/forge-std/src/",
    "solady/=lib/solady/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.