Skip to content
Verified contractExactUNLICENSED

CTokenMarketLib

Address0x18c53f2acabcdeedb575a136f49fa4c43eb2071c
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,396,566
Creation transaction
0x67f7d9b514…2d70e439c6
Libraries
src/core/mm/MMRouterLib.sol:MMRouterLib0xa474…d2b4e5src/core/flamm/FLAMMLane.sol:FLAMMLane0x0988…d22e98src/core/flamm/FLAMMRoute.sol:FLAMMRoute0x312e…0fdaa9src/periphery/FLAMMMaxima.sol:FLAMMMaxima0x4a99…d6259csrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0x5d47…27cc62src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x0bfe…043753src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xd53f…ed5983src/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0x2577…4e3473src/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0xf0be…2b9555src/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x7a11…58517bsrc/core/mm/CTokenMarketLib.sol:CTokenMarketLib0x18c5…b2071csrc/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0xa6db…bdcbcbsrc/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x0b8d…2e7e5csrc/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0x02b4…731ccesrc/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0xa16d…a201e8src/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0x539e…a79737src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0xa4d3…d5ce2esrc/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0x7c55…d233dfsrc/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0xcda6…a4dcf7src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x8423…7adc96src/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0xa6b4…0c67f9src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0xb489…d3c7cbsrc/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xfaae…2511basrc/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x480f…4e0a81src/hooks/everlong/LeverageLib.sol:LeverageLib0x1b1d…40ad11src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0x9499…409cc2src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0x0775…d94cbesrc/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xabe4…7426f7

src/core/mm/CTokenMarketLib.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 {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {
    IVToken,
    IVenusComptroller,
    IVenusBoundedOracle,
    IVenusRateModel
} from "src/interfaces/utils/integrations/IVenus.sol";
import {VenueReads} from "src/core/mm/VenueReads.sol";
import {
    IFinancingAccount,
    CAN_BORROW,
    CAN_REPAY,
    CAN_SUPPLY,
    CAN_WITHDRAW_SUPPLY,
    CAN_POST_COLLATERAL,
    CAN_RELEASE_COLLATERAL
} from "src/interfaces/core/mm/IFinancingAccount.sol";
import {WAD, ORACLE_PRICE_SCALE} from "src/interfaces/core/mm/IMMRouter.sol";

/// @notice The Venus kind's (`CTokenAccount`) reads of its markets, linked to it rather than inlined, so the account
///         keeps its EIP-170 margin: a registration's check of its markets ({checkMarkets}), the loan market's rate
///         model's blocks a year ({rates}) and its rate after a leg ({rateAfter}), a venue's rooms ({rooms}), its two
///         markets' bounded price ({price}), its health ({health}), whether Venus may force-liquidate a frame
///         ({forced}), and a frame's books of its markets ({join}). The reads a view takes several times a flow, a
///         market as its next accrual leaves it (`_market`) and a loan market's forced-liquidation flags (`_forcedIn`),
///         are this file's own functions, compiled into the account and into the library alike.
///         Each read is a static call of bounded gas whose failure reads as unreadable, unless its caller left it short
///         of its whole budget (`VenueReads.ReadStarved`), as the account's own; none writes.
library CTokenMarketLib {
    /// @dev Venus's ceiling on a borrow rate per block: a market whose rate model answers more cannot accrue.
    uint256 internal constant MAX_BORROW_RATE = 0.0005e16;
    /// @dev The account's budget for a plain read (`CTokenAccount.READ_GAS`).
    uint256 internal constant READ_GAS = 100_000;
    /// @dev The account's budget for a read that prices markets (`CTokenAccount.HEAVY_GAS`).
    uint256 internal constant HEAVY_GAS = 1_000_000;
    /// @dev What Venus's collateral-factor check on the debt sub-account is given for each market it has entered: it
    ///      walks every one and prices each that holds a position, one Venus's governance entered it in too, so its
    ///      cost follows their count, which nothing here caps ({_checkGas}). Half `HEAVY_GAS`, well over what one
    ///      priced market adds to it cold.
    uint256 internal constant MARKET_GAS = HEAVY_GAS / 2;
    /// @dev The most that check is given, reached at thirty markets, under the 2^24 gas one transaction may spend where
    ///      Venus runs (EIP-7825). The budget is not always left: a caller that reaches the check deep in a
    ///      transaction with less than it (eight million at sixteen markets) gets `VenueReads.ReadStarved` where the
    ///      check fails, never a false answer, as at every read here.
    uint256 internal constant MAX_CHECK_GAS = 15_000_000;
    // Venus's `Action` ids the rooms read.
    uint256 internal constant MINT = 0;
    uint256 internal constant REDEEM = 1;
    uint256 internal constant BORROW = 2;
    uint256 internal constant REPAY = 3;
    uint256 internal constant ENTER_MARKET = 7;
    /// @dev The most markets the debt sub-account may have entered for a borrow or a release to be sized: Venus prices
    ///      each before either, and each one past the venue's two adds a price read of up to `HEAVY_GAS` to the sizing.
    uint256 internal constant MAX_ENTERED = 8;
    /// @dev The most markets a frame's venues may name over its life ({_count}).
    uint256 internal constant MAX_MARKETS = 5;
    /// @dev `VenueAccountBase.SIZED`: size the fields too.
    uint8 internal constant SIZED = 64;
    /// @dev The action bits a venue's loan market decides.
    uint8 internal constant LOAN_ACTIONS = CAN_BORROW | CAN_REPAY | CAN_SUPPLY | CAN_WITHDRAW_SUPPLY;
    /// @dev The action bits a venue's collateral market decides.
    uint8 internal constant COLLATERAL_ACTIONS = CAN_POST_COLLATERAL | CAN_RELEASE_COLLATERAL;

    /// @dev One vToken as its next accrual leaves it (`accrued`), as it stores itself where its rate model cannot be
    ///      read, or nothing where its state cannot be read (`read` false). `irm`: its rate model. `cash`, `borrows`,
    ///      `reserves`: its totals in base units. `free`: the cash a leg can draw, less the reserves an accrual may
    ///      sweep out of it. `supply`: its total units. `rate`: its exchange rate, base units per unit scaled by `WAD`.
    ///      `index`: its borrow index at that accrual; `index0`: the index it stores.
    struct Market {
        bool read;
        bool accrued;
        address irm;
        uint256 cash;
        uint256 free;
        uint256 borrows;
        uint256 reserves;
        uint256 supply;
        uint256 rate;
        uint256 index;
        uint256 index0;
    }

    /// @dev A venue's position units as Venus holds them, or as its latest leg recorded them (`live` false): its
    ///      collateral units, its supply units and its debt sub-account's stored borrow balance, each the venue's own
    ///      part at a frame's account; and `all`, that sub-account's whole stored borrow balance at the loan market.
    struct Units {
        bool live;
        uint256 collateral;
        uint256 supply;
        uint256 owed;
        uint256 all;
    }

    /// @dev A venue as {rooms} reads it: the comptroller, its two markets, its debt and credit sub-accounts, its group,
    ///      the two tokens' unit caps, how many of the account's venues share the collateral market's and the loan
    ///      market's caps, and whether the account is a frame's.
    struct Ctx {
        address comptroller;
        address cv;
        address lv;
        address d;
        address cs;
        uint96 group;
        uint256 capC;
        uint256 capL;
        uint256 posts;
        uint256 loans;
        bool frame;
    }

    /// @notice A frame's venues would name more than `MAX_MARKETS` markets.
    error FrameFull();
    /// @notice A venue's market is not listed at the comptroller, not of it, or not over the token named.
    error MarketUnknown();

    /// @notice Each of a venue's two markets, `cv` over `c` and `lv` over `l`, a market of `comptroller` listed there:
    ///         else `MarketUnknown`. Its probes get bounded gas, so a market that answers no `underlying` is refused
    ///         plainly: vBNB mints native BNB on any call it does not know, which halts a static call and would spend
    ///         all of its gas.
    function checkMarkets(address comptroller, address cv, address c, address lv, address l) public view {
        address[2] memory m = [cv, lv];
        address[2] memory t = [c, l];
        for (uint256 k; k < 2; ++k) {
            (bool listed,) = _listed(comptroller, m[k]);
            (, uint256 u) = _get(m[k], IVToken.underlying.selector);
            (, uint256 home) = _get(m[k], IVToken.comptroller.selector);
            if (!listed || u != _w(t[k]) || home != _w(comptroller)) revert MarketUnknown();
        }
    }

    /// @notice The account's `_capacity` before its held amounts come off: the fields in `want` (action bits; the rest
    ///         read zero), each as its view reads it.
    /// @dev An action is refused, its bit clear and its field zero:
    ///      - every action while the position cannot be read or the protocol is paused;
    ///      - an action Venus pauses, on a market it unlists or whose rate model cannot be read;
    ///      - a supply, post or borrow under a cap of 0;
    ///      - a borrow the group disallows, from outside the loan market while Venus pauses entering it, or while Venus
    ///        may force-liquidate (a post too);
    ///      - a release or a supply withdrawal while the redemption fee cannot be read, and an indebted release while
    ///        the fee is set;
    ///      - a supply withdrawal from a credit sub-account Venus entered into a market.
    ///
    ///      No action bit reads a price: while a bounded price it needs cannot be read, the borrow (both markets') and
    ///      the release (every market the debt sub-account has entered) keep their bits and read zero, and only a sized
    ///      borrow or release reads one.
    ///
    ///      Bounds:
    ///      - A borrow and both withdrawals are bounded by the market's cash less the reserves its accrual may sweep, a
    ///        borrow also by the borrow cap, a supply by the supply cap, and a post by an equal part of it among the
    ///        account's venues on that collateral market, so the posts of one plan fit it together.
    ///      - At a frame's account a borrow and a supply take an equal part of the loan market's cap among the frame's
    ///        venues borrowing there, and a post needs the debt sub-account in the collateral market or Venus letting
    ///        it enter (it may have left, `CTokenAccount.leave`).
    ///      - While the frame's other venues lack anything at Venus's prices and collateral factors, net ({_deficit}),
    ///        a sized borrow and release are bounded too by the frame's spare room at Venus, so Venus's check passes on
    ///        them: a borrow by what that room buys at the debt price, a release by the collateral it values at the
    ///        venue's factor once the redemption has accrued its market ({_spareAfter}, {_releaseRoom}). While they
    ///        lack nothing, each venue's pin keeps the frame whole and neither reads that room (`IFinancingAccount`
    ///        ADMISSION).
    ///      - Under a fee, each withdrawal is what that cash and the position's units pay net of it.
    function rooms(
        Ctx memory x,
        Units memory u,
        uint8 want,
        address[] storage markets,
        mapping(address => uint256) storage loanVenues
    ) public view returns (IFinancingAccount.Capacity memory c) {
        if (!u.live) return c;
        (bool ok, uint256 n) = _get(x.comptroller, IVenusComptroller.protocolPaused.selector);
        if (!ok || n != 0) return c;
        // A sized borrow or release reads the bounded prices; nothing else does.
        bool priced = want & SIZED != 0 && want & (CAN_BORROW | CAN_RELEASE_COLLATERAL) != 0;
        // Read once, only where a borrow or a post is wanted.
        bool isForced = want & (CAN_BORROW | CAN_POST_COLLATERAL) != 0
            && _forced(x.comptroller, markets, loanVenues, x.lv, x.d, x.frame);
        // The redemption fee, `WAD` (no withdrawal, no release) where it cannot be read.
        uint256 fee = WAD;
        if (want & (CAN_WITHDRAW_SUPPLY | CAN_RELEASE_COLLATERAL) != 0) {
            (ok, n) = _get(x.comptroller, IVenusComptroller.treasuryPercent.selector);
            if (ok && n < WAD) fee = n;
        }
        // Whether the debt sub-account is in the loan market: a borrow from outside enters it (unreadable: outside),
        // and a release from inside prices it too (unreadable: inside).
        bool okIn;
        bool inLoan;
        if (want & CAN_BORROW != 0 || (priced && want & CAN_RELEASE_COLLATERAL != 0)) {
            (okIn, inLoan) = _member(x.comptroller, x.d, x.lv);
        }
        // A borrow and a release price every market the debt sub-account has entered, one Venus's governance entered
        // too; past `MAX_ENTERED` of them neither is sized, which bounds that pricing's gas. The actions stay open, as
        // where a price cannot be read: no unsized read takes the list.
        bool collPriced;
        bool loanPriced;
        uint256 pc;
        uint256 pd;
        uint256 pdc;
        uint256 entered;
        if (priced) {
            address dbo = _oracle(x.comptroller);
            (ok, entered) = _entered(x.comptroller, dbo, x.d, x.cv, x.lv);
            if (ok) {
                (collPriced, pc, pdc) = _prices(dbo, x.cv);
                if (collPriced && (want & CAN_BORROW != 0 || !okIn || inLoan)) (loanPriced,, pd) = _prices(dbo, x.lv);
            }
        }
        // At a frame's account, while its other venues lack anything, a sized borrow and release fit its spare room,
        // read at the loan market's next accrual, which a borrow there makes first.
        uint256 lack;
        uint256 cf;
        uint256 spare;
        Market memory lm;
        bool lmFull;
        if (x.frame && collPriced) {
            lmFull = want & LOAN_ACTIONS != 0;
            lm = _market(x.lv, lmFull);
            (ok, lack, cf, spare) = _deficit(x, u, pc, pd, entered, _interest(lm, u.all));
            if (!ok) (collPriced, loanPriced) = (false, false);
        }
        uint8 a;
        if (want & LOAN_ACTIONS != 0) {
            Market memory m = lmFull ? lm : _market(x.lv, true);
            (bool listed, bool coreBorrows) = _listed(x.comptroller, x.lv);
            if (m.accrued && listed) {
                if (want & CAN_REPAY != 0 && _open(x.comptroller, x.lv, REPAY)) a |= CAN_REPAY;
                uint256 cap = want & CAN_SUPPLY != 0 && _open(x.comptroller, x.lv, MINT) && m.rate <= x.capL
                    ? _cap(x.comptroller, true, x.lv)
                    : 0;
                if (cap != 0) {
                    a |= CAN_SUPPLY;
                    c.suppliable = _room(cap, Math.mulDiv(m.rate, m.supply, WAD)) / x.loans;
                }
                if (want & CAN_WITHDRAW_SUPPLY != 0 && fee < WAD && _open(x.comptroller, x.lv, REDEEM)) {
                    (bool okC, bool inC) = _member(x.comptroller, x.cs, x.lv);
                    if (okC && !inC) {
                        a |= CAN_WITHDRAW_SUPPLY;
                        c.supplyWithdrawable = _payable(m, u.supply, fee);
                    }
                }
                cap = want & CAN_BORROW != 0 && !isForced && _open(x.comptroller, x.lv, BORROW)
                    && (inLoan || _open(x.comptroller, x.lv, ENTER_MARKET))
                    && _groupBorrows(x.comptroller, x.group, x.lv, coreBorrows)
                    ? _cap(x.comptroller, false, x.lv)
                    : 0;
                if (cap != 0) {
                    a |= CAN_BORROW;
                    if (loanPriced) {
                        uint256 b = Math.min(m.free, _room(cap, m.borrows) / x.loans);
                        c.borrowable = lack == 0 ? b : Math.min(b, Math.mulDiv(spare, WAD, pd));
                    }
                }
            }
        }
        if (want & COLLATERAL_ACTIONS != 0) {
            Market memory m = _market(x.cv, true);
            (bool listed,) = _listed(x.comptroller, x.cv);
            if (m.accrued && listed) {
                uint256 cap = want & CAN_POST_COLLATERAL != 0 && !isForced && _open(x.comptroller, x.cv, MINT)
                    && m.rate <= x.capC && (!x.frame || _entersOrIn(x.comptroller, x.d, x.cv))
                    ? _cap(x.comptroller, true, x.cv)
                    : 0;
                if (cap != 0) {
                    a |= CAN_POST_COLLATERAL;
                    c.collateralPostable = _room(cap, Math.mulDiv(m.rate, m.supply, WAD)) / x.posts;
                }
                // Indebted, only with no fee: the Router proves health on the collateral that stays.
                if (
                    want & CAN_RELEASE_COLLATERAL != 0 && fee < WAD && (fee == 0 || u.owed == 0)
                        && _open(x.comptroller, x.cv, REDEEM)
                ) {
                    a |= CAN_RELEASE_COLLATERAL;
                    if (collPriced && (loanPriced || (okIn && !inLoan))) {
                        uint256 r = _payable(m, u.collateral, fee);
                        if (lack != 0) {
                            uint256 room = _spareAfter(x, m, spare, pdc, loanVenues);
                            r = Math.min(r, _releaseRoom(room, cf, pc, m.rate, fee));
                        }
                        c.collateralReleasable = r;
                    }
                }
            }
        }
        c.actions = a;
    }

    /// @notice Whether Venus may liquidate the debt sub-account `d` past its health check through loan market `lv` (its
    ///         forced liquidation, or the sub-account's in it), or cannot say; at a frame's account (`frame`), through
    ///         any loan market of the frame (`markets` its markets, `loanVenues` how many of its venues borrow each),
    ///         as a liquidation through one reaches every venue's collateral.
    function forced(
        address comptroller,
        address[] storage markets,
        mapping(address => uint256) storage loanVenues,
        address lv,
        address d,
        bool frame
    ) public view returns (bool) {
        return _forced(comptroller, markets, loanVenues, lv, d, frame);
    }

    /// @notice A frame venue's markets and tokens joining the frame's books: its collateral market `cv` and loan market
    ///         `lv` counted among the frame's `markets` once each (past `MAX_MARKETS` `FrameFull`), one more venue
    ///         borrowing from `lv`, and each of its two tokens' unit caps, `10 ** (decimals + 12)`, read at its first
    ///         venue (zero, so no market of it is entered, where its decimals cannot be read or pass 18), as the
    ///         deployer reads them for a pair's own account (`CTokenAccountDeployer.unitCap`).
    function join(
        address[] storage markets,
        mapping(address => uint256) storage loanVenues,
        mapping(address => uint256) storage unitCaps,
        address cv,
        address lv,
        address c,
        address l
    ) public {
        _count(markets, cv);
        _count(markets, lv);
        ++loanVenues[lv];
        address[2] memory t = [c, l];
        for (uint256 k; k < 2; ++k) {
            if (unitCaps[t[k]] != 0) continue;
            (bool ok, uint256 d) = _get(t[k], IERC20Metadata.decimals.selector);
            if (ok && d <= 18) unitCaps[t[k]] = 10 ** (d + 12);
        }
    }

    /// @notice Venus's collateral-factor check on the debt sub-account `d` at loan market `lv`'s next accrual, its
    ///         `interest` entering as a borrow there: no shortfall at the bounded prices; false where it cannot be
    ///         read. It walks every market `d` has entered, whose list it reads first: its gas follows their count
    ///         ({_checkGas}), so no market Venus's governance enters `d` in can make a healthy position read unhealthy
    ///         for want of gas; a caller that leaves the read short of that budget gets `ReadStarved`, not an answer. A
    ///         frame's account (`frame`) is given at least twice `HEAVY_GAS`.
    function health(address comptroller, address d, address lv, uint256 interest, bool frame)
        public
        view
        returns (bool)
    {
        (bool ok, address[] memory markets) = _assetsIn(comptroller, d);
        if (!ok) return false;
        uint256 err;
        uint256 shortfall;
        (ok, err, shortfall) = _peek(
            _checkGas(markets.length, frame),
            comptroller,
            IVenusComptroller.getHypotheticalAccountLiquidity.selector,
            _w(d),
            _w(lv),
            0,
            interest,
            2
        );
        return ok && err == 0 && shortfall == 0;
    }

    /// @notice The loan market's rate model `model` at the post-leg totals of its next accrual (`cash`, `debt`,
    ///         `reserves`, `dBorrow` more debt and `dSupplyDown` less supply), per second: its rate per block times its
    ///         `perYear` blocks a year, over a 365-day year, rounded up. Venus's models read utilization alone, so the
    ///         accrued state needs no other projection.
    ///         Not `ok` past Venus's rate ceiling, where the model cannot be read, or where the leg would take the
    ///         market's whole supply or more cash than it holds. A zero delta is exempt from the supply bound, so an
    ///         empty market fails on liquidity, not on its rate.
    function rateAfter(
        address model,
        uint256 cash,
        uint256 debt,
        uint256 reserves,
        uint256 perYear,
        uint256 dBorrow,
        uint256 dSupplyDown
    ) public view returns (bool, uint256) {
        if ((dSupplyDown != 0 && dSupplyDown >= cash + debt - reserves) || dBorrow + dSupplyDown > cash) {
            return (false, 0);
        }
        (bool ok, uint256 rate) = _rateAt(model, cash - dBorrow - dSupplyDown, debt + dBorrow, reserves);
        if (!ok || rate > MAX_BORROW_RATE) return (false, 0);
        return (true, (rate * perYear + 365 days - 1) / 365 days);
    }

    /// @notice The loan market `lv` at its next accrual (`_market`) and its rate model's blocks per year, under either
    ///         name Venus's models use (`blocksPerYear` or `BLOCKS_PER_YEAR`); zero where neither reads in range.
    function rates(address lv) public view returns (Market memory m, uint256 perYear) {
        m = _market(lv, true);
        bool ok;
        (ok, perYear) = _get(m.irm, IVenusRateModel.blocksPerYear.selector);
        if (ok && perYear != 0 && perYear <= type(uint64).max) return (m, perYear);
        (ok, perYear) = _get(m.irm, IVenusRateModel.BLOCKS_PER_YEAR.selector);
        if (!ok || perYear > type(uint64).max) perYear = 0;
    }

    /// @notice The prices Venus's collateral-factor checks use, from its deviation-bounded oracle: the collateral
    ///         market `cv` at its collateral price, the loan market `lv` at its debt price, their ratio scaled by 1e36,
    ///         the Router's price scale. Not `ok` while either cannot be read (Venus's resilient oracle reverts where
    ///         it cannot price) or the ratio would not fit.
    function price(address comptroller, address cv, address lv) public view returns (bool ok, uint256 p) {
        address dbo = _oracle(comptroller);
        uint256 coll;
        uint256 debt;
        (ok, coll,) = _prices(dbo, cv);
        if (ok) (ok,, debt) = _prices(dbo, lv);
        if (!ok || coll / debt >= type(uint256).max / ORACLE_PRICE_SCALE) return (false, 0);
        return (true, Math.mulDiv(coll, ORACLE_PRICE_SCALE, debt));
    }

    /// @notice What the debt sub-account `d`'s group gives collateral market `cv` (`getEffectiveLtvFactor`), within
    ///         `READ_GAS`: its collateral factor (`weighting` 0), which Venus's borrow and redemption checks weigh the
    ///         collateral by, or its liquidation threshold (1), which its liquidation check does; not `ok` where it
    ///         cannot be read. Internal: the account's registration, its threshold and its counted view read it too.
    function ltvFactor(address comptroller, address d, address cv, uint256 weighting)
        internal
        view
        returns (bool ok, uint256 cf)
    {
        (ok, cf,) = _peek(
            READ_GAS, comptroller, IVenusComptroller.getEffectiveLtvFactor.selector, _w(d), _w(cv), weighting, 0, 0
        );
    }

    // ------------------------------------------------------------------ reads
    /// @dev {forced}, for {rooms} too.
    function _forced(
        address comptroller,
        address[] storage markets,
        mapping(address => uint256) storage loanVenues,
        address lv,
        address d,
        bool frame
    ) private view returns (bool) {
        if (!frame) return _forcedIn(comptroller, lv, d);
        uint256 n = markets.length;
        for (uint256 i; i < n; ++i) {
            address m = markets[i];
            if (loanVenues[m] != 0 && _forcedIn(comptroller, m, d)) return true;
        }
        return false;
    }

    /// @dev Counts market `m` among a frame's `markets`, once.
    function _count(address[] storage markets, address m) private {
        uint256 n = markets.length;
        for (uint256 i; i < n; ++i) {
            if (markets[i] == m) return;
        }
        if (n == MAX_MARKETS) revert FrameFull();
        markets.push(m);
    }

    /// @dev A frame's spare room at Venus, in its prices' dollars (1e18 a dollar): Venus's liquidity for its debt
    ///      sub-account with the venue's loan market at its next accrual, `interest` entering as a borrow there (a
    ///      borrow accrues that market first), every other market as stored, as Venus's own check reads the markets a
    ///      leg does not touch; zero while the frame is short. And what the frame's other venues lack there, net: this
    ///      venue's own surplus (its collateral part at the market's stored rate, its group's collateral factor and
    ///      the collateral price `pc`, rounded down, less its debt part grown by its share of `interest` at the debt
    ///      price `pd`, rounded up) plus the shortfall and less that room, zero where they lack nothing; with the
    ///      venue's collateral factor. `ok` false where a read fails; the frame's read is given its check's gas at
    ///      `entered` markets, the debt sub-account's ({_checkGas}).
    function _deficit(Ctx memory x, Units memory u, uint256 pc, uint256 pd, uint256 entered, uint256 interest)
        private
        view
        returns (bool ok, uint256 lack, uint256 cf, uint256 spare)
    {
        uint256 rate;
        (ok, cf) = ltvFactor(x.comptroller, x.d, x.cv, 0);
        if (ok) (ok, rate) = _get(x.cv, IVToken.exchangeRateStored.selector);
        if (!ok) return (false, 0, 0, 0);
        uint256 err;
        uint256 short;
        (address comptroller, address d, address lv) = (x.comptroller, x.d, x.lv);
        bytes4 selector = IVenusComptroller.getHypotheticalAccountLiquidity.selector;
        uint256 budget = _checkGas(entered, true);
        bool whole = gasleft() >= budget * 64 / 63 + 10_000;
        assembly ("memory-safe") {
            let p := mload(0x40)
            mstore(p, selector)
            mstore(add(p, 0x04), d)
            mstore(add(p, 0x24), lv)
            mstore(add(p, 0x44), 0)
            mstore(add(p, 0x64), interest)
            ok := staticcall(budget, comptroller, p, 0x84, 0, 0)
            if lt(returndatasize(), 0x60) { ok := 0 }
            if ok {
                returndatacopy(p, 0, 0x60)
                err := mload(p)
                spare := mload(add(p, 0x20))
                short := mload(add(p, 0x40))
            }
        }
        if (!ok && !whole) revert VenueReads.ReadStarved();
        if (!ok || err != 0) return (false, 0, 0, 0);
        uint256 own = Math.mulDiv(Math.mulDiv(Math.mulDiv(cf, rate, WAD), pc, WAD), u.collateral, WAD);
        uint256 owed = u.all == 0 ? 0 : Math.mulDiv(u.owed, u.all + interest, u.all, Math.Rounding.Up);
        uint256 owes = Math.mulDiv(pd, owed, WAD, Math.Rounding.Up);
        if (own + short > owes + spare) lack = own + short - owes - spare;
    }

    /// @dev What loan market `m`'s next accrual adds to a stored debt `owed` there, at most: the stored debt plus one
    ///      carried at the index's growth, as the account projects a debt with no borrow record of its own
    ///      (`CTokenAccount._projected`); none where the market is accrued or cannot accrue.
    function _interest(Market memory m, uint256 owed) private pure returns (uint256) {
        if (owed == 0 || m.index == m.index0) return 0;
        return Math.mulDiv(owed + 1, m.index, m.index0) - owed;
    }

    /// @dev The frame's `spare` dollars as a redemption out of collateral market `m` (`x.cv`) leaves them, which
    ///      accrues that market first: less the interest its accrual adds to the frame's debt there, at its debt price
    ///      `pd`, where one of the frame's venues borrows from it (`loanVenues`); none where that debt cannot be read.
    function _spareAfter(
        Ctx memory x,
        Market memory m,
        uint256 spare,
        uint256 pd,
        mapping(address => uint256) storage loanVenues
    ) private view returns (uint256) {
        if (loanVenues[x.cv] == 0) return spare;
        (bool ok, uint256 owed,) = _peek(READ_GAS, x.cv, IVToken.borrowBalanceStored.selector, _w(x.d), 0, 0, 0, 0);
        if (!ok) return 0;
        uint256 cut = Math.mulDiv(_interest(m, owed), pd, WAD, Math.Rounding.Up);
        return spare > cut ? spare - cut : 0;
    }

    /// @dev The most a release out of a collateral market at exchange rate `rate` may pay, net of the redemption fee
    ///      `fee`, for Venus's check to pass on the frame's `spare` dollars: the gross amount whose value at the
    ///      venue's factor `cf` times its price `pc`, rounded up, is `spare` or less, less one unit's assets,
    ///      as a redemption by amount can burn up to one unit past it (`CTokenAccount._redeem`), then net of the fee,
    ///      rounded down. Unbounded where Venus values the collateral at nothing and the frame is not short.
    function _releaseRoom(uint256 spare, uint256 cf, uint256 pc, uint256 rate, uint256 fee)
        private
        pure
        returns (uint256)
    {
        uint256 value = Math.mulDiv(cf, pc, WAD, Math.Rounding.Up);
        if (value == 0) return spare == 0 ? 0 : type(uint256).max;
        uint256 gross = Math.mulDiv(spare, WAD, value);
        uint256 unit = Math.ceilDiv(rate, WAD);
        return gross > unit ? Math.mulDiv(gross - unit, WAD - fee, WAD) : 0;
    }

    /// @dev What a redemption out of `units` of the accrued market `m` can pay its holder: nothing while its free cash
    ///      is under one unit's payout, as every redemption burns at least one unit; else the market's free cash with
    ///      no fee (the Router bounds it by the position); under a fee, the most whose gross amount both that cash and
    ///      the units cover, net of the fee.
    function _payable(Market memory m, uint256 units, uint256 fee) private pure returns (uint256) {
        if (m.free < m.rate / WAD) return 0;
        if (fee == 0) return m.free;
        uint256 v = Math.mulDiv(units, m.rate, WAD);
        return Math.min(Math.mulDiv(m.free, WAD - fee, WAD), v - Math.mulDiv(v, fee, WAD));
    }

    /// @dev `vToken`'s Core Pool listing and borrow switch.
    function _listed(address comptroller, address vToken) private view returns (bool, bool) {
        (bool ok, uint256 listed, uint256 borrows) =
            _ask(comptroller, IVenusComptroller.markets.selector, _w(vToken), 0, 6);
        return (ok && listed != 0, ok && borrows != 0);
    }

    /// @dev Whether the debt sub-account's group lets it borrow `lv`: the Core Pool's own switch for group 0, else the
    ///      group's, while the group is active (Venus never falls back to the Core Pool for a borrow).
    function _groupBorrows(address comptroller, uint96 group, address lv, bool coreBorrows)
        private
        view
        returns (bool)
    {
        if (group == 0) return coreBorrows;
        (bool ok,, uint256 on) = _ask(comptroller, IVenusComptroller.poolMarkets.selector, group, _w(lv), 6);
        if (ok && on != 0) (ok,, on) = _ask(comptroller, IVenusComptroller.pools.selector, group, 0, 1);
        return ok && on != 0;
    }

    /// @dev Whether `action` on `vToken` is not paused (and readable).
    function _open(address comptroller, address vToken, uint256 action) private view returns (bool) {
        (bool ok, uint256 paused,) = _ask(comptroller, IVenusComptroller.actionPaused.selector, _w(vToken), action, 0);
        return ok && paused == 0;
    }

    /// @dev `vToken`'s supply cap (`supplySide`) or borrow cap; zero, which closes the action, where unreadable.
    function _cap(address comptroller, bool supplySide, address vToken) private view returns (uint256 cap) {
        bytes4 selector = supplySide ? IVenusComptroller.supplyCaps.selector : IVenusComptroller.borrowCaps.selector;
        (, cap,) = _ask(comptroller, selector, _w(vToken), 0, 0);
    }

    /// @dev Whether `account` has entered `vToken` (`member`), where it can be read (`ok`).
    function _member(address comptroller, address account, address vToken) private view returns (bool ok, bool member) {
        uint256 w;
        (ok, w,) = _ask(comptroller, IVenusComptroller.checkMembership.selector, _w(account), _w(vToken), 0);
        member = ok && w != 0;
    }

    /// @dev Whether `account` is in `vToken`, or Venus lets it enter: a post there enters it first where it is not.
    function _entersOrIn(address comptroller, address account, address vToken) private view returns (bool) {
        (bool ok, bool member) = _member(comptroller, account, vToken);
        return member || (ok && _open(comptroller, vToken, ENTER_MARKET));
    }

    /// @dev The comptroller's deviation-bounded oracle; zero where unreadable.
    function _oracle(address comptroller) private view returns (address) {
        (, uint256 w) = _get(comptroller, IVenusComptroller.deviationBoundedOracle.selector);
        return address(uint160(w));
    }

    /// @dev Whether every market the debt sub-account `d` has entered ({_assetsIn}), which Venus's checks for it walk
    ///      before a borrow and a release alike, one its governance entered it in (`enterMarketForAccount`) among them,
    ///      prices at `dbo` now beside the venue's two (`cv`, `lv`), and they are `MAX_ENTERED` at most; and how many
    ///      there are. Beyond its price such a market can only raise the sub-account's liquidity, as nobody can borrow
    ///      there for it. False while the list cannot be read.
    ///      Not covered: `getAssetsIn` leaves out a market Venus has unlisted, which its checks still walk, so a market
    ///      its governance entered and then unlisted, once its price fails, makes a sized borrow or release revert.
    function _entered(address comptroller, address dbo, address d, address cv, address lv)
        private
        view
        returns (bool, uint256 n)
    {
        (bool listed, address[] memory markets) = _assetsIn(comptroller, d);
        n = markets.length;
        if (!listed || n > MAX_ENTERED) return (false, n);
        for (uint256 i; i < n; ++i) {
            address m = markets[i];
            if (m != cv && m != lv) {
                (bool ok,,) = _prices(dbo, m);
                if (!ok) return (false, n);
            }
        }
        return (true, n);
    }

    /// @dev The markets the debt sub-account `d` has entered (`getAssetsIn`), read within `HEAVY_GAS`, which holds a
    ///      list of hundreds; `listed` false while it cannot be read whole, and a read the caller left short of its
    ///      budget reverts `ReadStarved`, as {_peek} does.
    function _assetsIn(address comptroller, address d) private view returns (bool listed, address[] memory markets) {
        bytes4 selector = IVenusComptroller.getAssetsIn.selector;
        bool whole = gasleft() >= HEAVY_GAS * 64 / 63 + 10_000;
        bool answered;
        assembly ("memory-safe") {
            let p := mload(0x40)
            mstore(p, selector)
            mstore(add(p, 0x04), d)
            answered := staticcall(HEAVY_GAS, comptroller, p, 0x24, 0, 0)
            let size := returndatasize()
            if and(answered, gt(size, 0x3f)) {
                returndatacopy(p, 0, size)
                let n := mload(add(p, 0x20))
                // The list whole: its offset, its length, a word a market, nothing more.
                listed := and(and(eq(mload(p), 0x20), lt(n, 0x10000)), eq(size, add(0x40, shl(5, n))))
                if listed {
                    markets := add(p, 0x20)
                    mstore(0x40, add(p, size))
                }
            }
        }
        if (!answered && !whole) revert VenueReads.ReadStarved();
    }

    /// @dev The gas Venus's collateral-factor check is given at `n` entered markets: `MARKET_GAS` each, never under
    ///      `HEAVY_GAS` (the venue's two markets), twice it at a frame's account (`frame`), nor over `MAX_CHECK_GAS`.
    function _checkGas(uint256 n, bool frame) private pure returns (uint256) {
        return Math.min(Math.max(n * MARKET_GAS, frame ? 2 * HEAVY_GAS : HEAVY_GAS), MAX_CHECK_GAS);
    }

    /// @dev `vToken`'s bounded collateral and debt prices; `ok` where both read nonzero.
    function _prices(address dbo, address vToken) private view returns (bool ok, uint256 coll, uint256 debt) {
        if (dbo == address(0)) return (false, 0, 0);
        (ok, coll, debt) =
            _peek(HEAVY_GAS, dbo, IVenusBoundedOracle.getBoundedPricesView.selector, _w(vToken), 0, 0, 0, 1);
        ok = ok && coll != 0 && debt != 0;
    }

    /// @dev What a cap leaves over what is used, zero at or past it.
    function _room(uint256 cap, uint256 used) private pure returns (uint256) {
        return cap > used ? cap - used : 0;
    }
}

// ------------------------------------------------------------------ the kind's reads, shared with the account
/// @dev One market as its next accrual leaves it: Venus's accrual replayed (simple interest over the blocks since, at
///      the rate its model answers for the stored totals; reserves take the reserve factor of it; the exchange rate is
///      cash plus borrows less reserves over supply), every product rounded down as Venus rounds it. A market accrued
///      this block reads as stored; `full` false then reads only its rate and index. A flash loan, the one time Venus
///      counts cash it lent out, accrues its market first, so a market to project has none. It stops at the first
///      read that fails, unread.
function _market(address vToken, bool full) view returns (CTokenMarketLib.Market memory m) {
    if (vToken == address(0)) return m;
    (bool ok, uint256 last) = _get(vToken, IVToken.accrualBlockNumber.selector);
    uint256 index;
    if (ok) (ok, m.rate) = _get(vToken, IVToken.exchangeRateStored.selector);
    if (ok) (ok, index) = _get(vToken, IVToken.borrowIndex.selector);
    if (!ok) return m;
    (m.index, m.index0) = (index, index);
    bool fresh = last >= block.number;
    if (fresh && !full) {
        (m.read, m.accrued) = (true, true);
        return m;
    }
    uint256 rf;
    uint256 irm;
    (ok, m.cash) = _get(vToken, IVToken.getCash.selector);
    if (ok) (ok, m.borrows) = _get(vToken, IVToken.totalBorrows.selector);
    if (ok) (ok, m.reserves) = _get(vToken, IVToken.totalReserves.selector);
    if (ok) (ok, m.supply) = _get(vToken, IVToken.totalSupply.selector);
    if (ok) (ok, rf) = _get(vToken, IVToken.reserveFactorMantissa.selector);
    if (ok) (ok, irm) = _get(vToken, IVToken.interestRateModel.selector);
    if (!ok) return m;
    (m.read, m.irm, m.free) = (true, address(uint160(irm)), m.cash);
    if (fresh) {
        m.accrued = true;
        return m;
    }
    (bool okRate, uint256 rate) = _rateAt(m.irm, m.cash, m.borrows, m.reserves);
    // Venus cannot accrue past its ceiling or an unreadable model: the stored state stands.
    if (!okRate || rate > CTokenMarketLib.MAX_BORROW_RATE || rf > WAD) return m;
    uint256 factor = rate * (block.number - last);
    uint256 interest = Math.mulDiv(factor, m.borrows, WAD);
    uint256 borrows = m.borrows + interest;
    uint256 reserves = m.reserves + Math.mulDiv(rf, interest, WAD);
    if (reserves > m.cash + borrows) return m;
    (m.borrows, m.reserves, m.index) = (borrows, reserves, index + Math.mulDiv(factor, index, WAD));
    if (m.supply != 0) m.rate = Math.mulDiv(m.cash + borrows - reserves, WAD, m.supply);
    m.free = m.cash > reserves ? m.cash - reserves : 0;
    m.accrued = true;
}

/// @dev Whether Venus may liquidate the debt sub-account `d` past its health check through loan market `lv` alone (its
///      forced liquidation, or the sub-account's in it), or cannot say: `CTokenMarketLib.forced` at a pair's own
///      account, and at each of a frame's loan markets.
function _forcedIn(address comptroller, address lv, address d) view returns (bool) {
    (bool ok, uint256 on,) = _ask(comptroller, IVenusComptroller.isForcedLiquidationEnabled.selector, _w(lv), 0, 0);
    if (ok && on == 0) {
        (ok, on,) = _ask(comptroller, IVenusComptroller.isForcedLiquidationEnabledForUser.selector, _w(d), _w(lv), 0);
    }
    return !ok || on != 0;
}

/// @dev Rate model `irm`'s borrow rate per block at `cash`, `borrows` and `reserves`, within `READ_GAS`.
function _rateAt(address irm, uint256 cash, uint256 borrows, uint256 reserves) view returns (bool ok, uint256 rate) {
    (ok, rate,) =
        _peek(CTokenMarketLib.READ_GAS, irm, IVenusRateModel.getBorrowRate.selector, cash, borrows, reserves, 0, 0);
}

/// @dev Words 0 and `j` of the comptroller's answer to `selector(a, b)` within `READ_GAS` ({_peek}).
function _ask(address comptroller, bytes4 selector, uint256 a, uint256 b, uint256 j)
    view
    returns (bool, uint256, uint256)
{
    return _peek(CTokenMarketLib.READ_GAS, comptroller, selector, a, b, 0, 0, j);
}

/// @dev An address as a call's argument word.
function _w(address a) pure returns (uint256) {
    return uint256(uint160(a));
}

/// @dev `target`'s answer to `selector()`, as {_peek} reads it within `CTokenMarketLib.READ_GAS`.
function _get(address target, bytes4 selector) view returns (bool ok, uint256 v) {
    (ok, v,) = _peek(CTokenMarketLib.READ_GAS, target, selector, 0, 0, 0, 0, 0);
}

/// @dev Words 0 and `j` of `target`'s answer to the static call `selector(a, b, c, d)` given `budget` gas; `ok` false
///      on a revert, no code or an answer shorter than `j + 1` words. Trailing argument words a function does not take
///      are ignored by it. A failure counts as unreadable only where the call had its whole budget: given less, it may
///      have run out of gas in any call below it (Venus's reads nest several deep, and each call keeps 1/64 of its
///      gas back), so it reverts `ReadStarved` instead, and no caller can make the venue read as unreadable by
///      starving it (`IFinancingAccount` ADMISSION). Not `try`/`catch`: its decode would revert in this call. The
///      account's reads and its library's alike.
function _peek(uint256 budget, address target, bytes4 selector, uint256 a, uint256 b, uint256 c, uint256 d, uint256 j)
    view
    returns (bool ok, uint256 x, uint256 y)
{
    // Under this, the call gets less than `budget`: 1/64 stays here, and the call's access and setup cost some.
    bool whole = gasleft() >= budget * 64 / 63 + 10_000;
    assembly ("memory-safe") {
        let p := mload(0x40)
        mstore(p, selector)
        mstore(add(p, 0x04), a)
        mstore(add(p, 0x24), b)
        mstore(add(p, 0x44), c)
        mstore(add(p, 0x64), d)
        ok := staticcall(budget, target, p, 0x84, 0, 0)
        let n := shl(5, add(j, 1))
        if lt(returndatasize(), n) { ok := 0 }
        if ok {
            returndatacopy(p, 0, n)
            x := mload(p)
            y := mload(add(p, shl(5, j)))
        }
    }
    if (!ok && !whole) revert VenueReads.ReadStarved();
}

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

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
}

lib/openzeppelin-contracts-compat/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

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

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

pragma solidity ^0.8.0;

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

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

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

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

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

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

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

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

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

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

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

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

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

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

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

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

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

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

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

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}

src/core/mm/VenueReads.sol

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

/// @notice The guarded read a venue kind takes of a protocol that may not answer (`IFinancingAccount` ADMISSION): a
///         static call of bounded gas whose failure reads as unreadable, never as a revert, unless the caller left it
///         short of its budget. Lista Moolah (`MoolahAccount`) reads through it, Aave V3 (`AaveV3Account`) its rate
///         strategy, the Router a venue's minimums (`MMRouterLib._underMinimum`), and every kind that fences its reads
///         reverts its `ReadStarved`.
library VenueReads {
    /// @notice A guarded read failed, and the call had too little gas on hand to tell a protocol that cannot answer
    ///         from a read starved of gas.
    error ReadStarved();

    /// @dev `data` sent to `target` as a static call with at most `budget` gas: `ok == false` on a revert, no code or
    ///      an answer under `words` words, which {word} reads until the next call. A read that fails with too little
    ///      gas on hand to forward `budget` in full may have failed for want of gas: it reverts `ReadStarved` rather
    ///      than read the venue as unreadable, so no caller makes it look frozen by starving it. Not `try`/`catch`: its
    ///      decode would revert in this call.
    function peekData(uint256 budget, address target, bytes memory data, uint256 words)
        internal
        view
        returns (bool ok)
    {
        uint256 g = gasleft();
        assembly ("memory-safe") {
            ok := staticcall(budget, target, add(data, 0x20), mload(data), 0, 0)
            if lt(returndatasize(), shl(5, words)) { ok := 0 }
        }
        if (!ok && g < budget + budget / 63 + 5_000) revert ReadStarved();
    }

    /// @dev Word `i` of the last call's answer.
    function word(uint256 i) internal pure returns (uint256 v) {
        assembly ("memory-safe") {
            returndatacopy(0, shl(5, i), 0x20)
            v := mload(0)
        }
    }
}

src/interfaces/core/mm/IFinancingAccount.sol

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

/// @dev A `Capacity.actions` bit, what the venue lets this position do now: a borrow.
uint8 constant CAN_BORROW = 1;
/// @dev A `Capacity.actions` bit: a repay.
uint8 constant CAN_REPAY = 2;
/// @dev A `Capacity.actions` bit: a supply.
uint8 constant CAN_SUPPLY = 4;
/// @dev A `Capacity.actions` bit: a withdrawal of supply.
uint8 constant CAN_WITHDRAW_SUPPLY = 8;
/// @dev A `Capacity.actions` bit: a post of collateral.
uint8 constant CAN_POST_COLLATERAL = 16;
/// @dev A `Capacity.actions` bit: a release of collateral.
uint8 constant CAN_RELEASE_COLLATERAL = 32;
/// @dev Every `Capacity.actions` bit.
uint8 constant ALL_ACTIONS = 63;

/// @dev A `capabilities()` bit, what a kind may do, fixed per kind: `refinance` moves debt between two of its ids in
///      one step.
uint256 constant CAP_ATOMIC_REFINANCE = 1;
/// @dev A `capabilities()` bit: a collateral release depends on the venue's liquidity.
uint256 constant CAP_LENT_COLLATERAL = 2;
/// @dev A `capabilities()` bit: `lltv` can fall after admission.
uint256 constant CAP_MUTABLE_THRESHOLD = 4;
/// @dev A `capabilities()` bit: collateral units grow in assets.
uint256 constant CAP_ACCRUING_COLLATERAL = 8;
/// @dev A `capabilities()` bit: the venue can refuse an action (pause, freeze, hooks).
uint256 constant CAP_ACTION_GATES = 16;
/// @dev A `capabilities()` bit: the venue caps or rate-limits a leg.
uint256 constant CAP_PROTOCOL_CAPS = 32;
/// @dev A `capabilities()` bit: its legs can move other venues' cash and rate (one reserve behind them).
uint256 constant CAP_SHARED_LIQUIDITY = 64;
/// @dev A `capabilities()` bit: a collateral release reads the venue's oracle, owing or not.
uint256 constant CAP_PRICED_RELEASE = 128;
/// @dev A `capabilities()` bit: `haircut` can answer nonzero.
uint256 constant CAP_REPORTED_LOSS = 256;
/// @dev A `capabilities()` bit: a partial repay can be held short (a minimum, `IHeldRepay`); the pool reads it.
uint256 constant CAP_HELD_REPAY = 512;
/// @dev A `capabilities()` bit: `haircut` is a fee each redemption pays, not a loss; the pool reads it.
uint256 constant CAP_REDEMPTION_FEE = 1024;
/// @dev Every bit the Router admits: the sixteen of its record. Bits 11 to 15 (2048 to 32768) are spare, for
///      capabilities a later pool may read and the Router never does: the Router admits them, so a later pool
///      implementation can give one a meaning without a new Router. This pool gives none of them a meaning and refuses
///      a kind that declares any of them (`InvalidConfig`, when it admits the venue), so no kind declares one until a
///      pool reads it.
uint256 constant KNOWN_CAPABILITIES = 65535;

/// @notice One pool's account at one venue kind for one credit pair: it posts the pair's collateral token and borrows
///         and lends its loan token. Venues are `bytes32` ids for the protocol's parameters, validated against the
///         bound token pair at registration; positions are held in the account's own name. A frame's account, bound
///         to (zero, frame) (`FRAME_VENUE`), is one pool's account at one kind for every pair the pool puts
///         in the frame: it validates each venue against the pair the Router names at its registration and names that
///         pair's two tokens back for the venue's id ({IFrameAccount}). The Router
///         drives the normal path; only the bound pool drives the risk-reducing emergency path. Every mutator is
///         exact-delta: it reverts unless the venue's change matches the request. The Router pins each account to its
///         deployer's CREATE2 address for its bindings (`IAccountDeployer`), not to a shared codehash, so a kind may
///         keep its bindings as immutables.
/// @dev ADMISSION. The Router and the pool assume the following of every kind, and cannot be changed to relax it (the
///      first capability rule's spare bits and the two capability rules after it are the pool's: it refuses such a
///      kind when it admits the venue, which for a scheduled admission is when the schedule executes, as the account
///      exists only then):
///      - `capabilities()` declares only the bits above that the Router or the pool reads (0 to 10), which the Router
///        reads once, when it admits a venue, as the pool does: the Router refuses a kind that declares a bit outside
///        `KNOWN_CAPABILITIES` (`IMMRouter.UnknownCapability`), as it could not honour it, and admits the spare bits
///        11 to 15, which this pool refuses (`InvalidConfig`), as it gives none of them a meaning;
///      - a kind that declares `CAP_LENT_COLLATERAL`, `CAP_PRICED_RELEASE` or `CAP_HELD_REPAY` also declares
///        `CAP_ACTION_GATES`: the Router caps every release at `collateralReleasable` under the gates and either of the
///        first two, and the pool asks what a venue can release now only where it is gated
///        (`FLAMMGateLib.releasableOf`), as an entry's preview reads a minimum position only there
///        (`FLAMMSharedLib.heldLegsCheck`);
///      - each one-field view ({actions}, {collateralReleasable}, {supplyWithdrawable} and the others beside
///        {capacity}) answers that field of {capacity} in the same state, but at the Aave V3 kind where one reserve's
///        configuration word cannot be read and the other's can, which only an upgrade of its Pool reaches: that word
///        refuses the whole capacity, but only the views that read it (`AaveV3ReadsLib._gate`). The pool reads the
///        action bits of a frozen venue mark, of an exit's and the emergency top-up's frozen-venue tests and of a
///        repay's refusal, what a gated venue can release, and a shared reserve's release and withdrawal figures, from
///        these views (`FLAMMGateLib.frozen`, `FLAMMFlowLib.proRata`, `FLAMMMaintainLib.emergency`,
///        `FLAMMGateLib.repayRefused`, `FLAMMGateLib.releasableOf`, `FLAMMGateLib.sharedFit` and `coverReleases`,
///        `FLAMMSharedLib.releaseRoom`'s legs), as the Router's hot paths do;
///      - a kind that declares `CAP_SHARED_LIQUIDITY` also declares `CAP_REPORTED_LOSS`: one reserve behind many
///        borrowers is a lender whose losses its suppliers bear, and an exit's slices there leave one unit's assets
///        and one per venue of the pool where they would take all but a millionth of a position
///        (`FLAMMFlowLib.proRata`), as each sibling leg can lower the position's read by that much. One kind number
///        is one reserve per token (a kind's deployer binds one lender: one Aave Pool, one comptroller), which the
///        pool's cash budget for covers and draws keys on (`FLAMMGateLib.sharedFit`): a second lender takes a
///        second kind number, and no lender is listed under two;
///      - supply and collateral are held in units that never rebase; `position` converts them at the accrued state;
///      - every read the Router takes values those units at their face, as the venue owes them: a loss that face
///        values overstate (a lender's reserve deficit) is reported through {haircut} alone, by a kind that declares
///        `CAP_REPORTED_LOSS` (the pool asks no other), which the pool applies to its NAV and to an exit's slices and
///        the Router never reads, so the post and supply bounds below hold at face. A kind reports only a loss its
///        lender records where the kind can read it: the comptroller kind (`CTokenAccount`) reports a redemption fee
///        alone, so its venues stay at face in NAV and in an exit's slices however much of that face the lender
///        cannot pay;
///      - a kind whose {haircut} is a fee the lender takes on each redemption (a Compound-style redemption fee), not a
///        loss face values overstate, declares `CAP_REDEMPTION_FEE` beside `CAP_REPORTED_LOSS` (the pool refuses the
///        fee bit alone when it admits the venue, as it does the shared one): a redemption of `assets` there burns them
///        grossed up by the fee, so the pool sizes an exit's collateral and supply legs there net of the haircut, which
///        burns the exiter's units exactly, and its exit maximum reads those net legs against what the venue can pay.
///        Without the bit an exit's slices leave at face and its payout is cut by the haircut, which custody keeps. The
///        pool records the bit when it admits the venue (`FLAMMStore.S.feeVenues`);
///      - where collateral accrues, a post of `assets` raises the position's collateral by at least `assets` less one
///        unit's assets (`collateralUnitsToAssets(id, 1)`) and one, and one unit is worth a negligible amount: every
///        borrow's health check allows that much, and the Router's plan pads each post there by that much, the unit's
///        assets capped at a millionth of one whole token as the release side's allowance is (`MMRouterLib._postSlack`,
///        `MMRouterLib._roundingSlack`): at a market whose unit a donation has raised (a nearly empty market) the pad
///        stays at that millionth, so a dust draw its rounding refuses is refused, and the market keeps no unit of a
///        post;
///      - where collateral accrues, {collateralOf} is `collateralUnitsToAssets` of {positionOf}'s collateral units in
///        the same state, by a conversion that never falls as the units grow: the Router values the units it posted
///        by it and recognizes the lesser of that and the collateral, with no read of the units (a frame kind keeps
///        the rule for each venue's part);
///      - where collateral accrues, a leg of another position at the same market (a sibling venue's redemption,
///        which lowers the shared exchange rate) lowers this position's collateral by less than one unit's assets plus
///        one: the Router allows that much collateral-side slack after a repay that lowers the debt, at
///        `CAP_ACCRUING_COLLATERAL` kinds only;
///      - a supply of `assets` raises the position's supplied assets by at least `assets` less one share's assets
///        (`supplySharesToAssets(id, 1)`) and one, and one share is worth a negligible amount, or the supply reverts:
///        the Router values no supply but a migration's, so a share price anyone can raise (a donation to a nearly
///        empty vault) would otherwise take the deposit;
///      - one id is one health basis: a liquidation of one id never reaches another's collateral (a kind whose
///        positions share one basis gives each id its own address, sub-account or position). A frame's account is the
///        one exception:
///        - its ids are the venues of every pair the pool put in the frame, which share one position at the lender and
///          so one health basis, and a liquidation there may reach every venue posting the seized token;
///        - its kind gives each token there the roles its lender's book allows (posted, or borrowed and supplied), and
///          a token supplied there is never seizable as another venue's collateral;
///        - venues sharing a collateral, a loan or a supply market each hold a recorded part of it and read that part
///          alone, the collateral parts never summing past what the account holds there, the debt parts never under
///          what it owes, the supply parts never past what it supplied, and units past the parts (a gift to the
///          account) are no venue's;
///        - a part moves with its venue's own legs and the lender's index: another venue's leg moves it by the lender's
///          rounding alone, never a debt part up nor a collateral part down, so the four-unit allowances below hold at
///          a frame as at a pair's own account;
///        - a liquidation moves the parts of the markets it reaches in proportion, and where it leaves a market at or
///          under a millionth of what its parts record and of the next post or borrow there, that leg may restart them:
///          what is left, at most a millionth of the leg, is then no venue's, or the borrowing venue's to owe; past
///          either, the parts stay in proportion;
///        - where a liquidation, or anyone's repay, left a shared loan market's debt off its parts' records, a part's
///          own legs there round by up to one more of the lender's units: a release's allowance covers that below a
///          lender index of about one and a half, any move into or out of that market rounds as much, and a refinance
///          that moves such a part may pass its own (`IMMRouter.Conservation`: the move is sized again);
///        - where a seizure left a shared collateral market's holding under its records, a post's part there may land
///          one more of the lender's units short of the post bound above, which the Router's plan pad and a borrow's
///          allowance absorb (about two units' worth);
///        - a kind that holds no frame answers no {IFrameAccount.tokensOf}, or no tokens for the id, which the Router
///          reads of every frame venue, and may refuse such an account where it deploys it or a venue where it
///          registers it;
///      - at a frame's account, each id names one pair:
///        - the id commits to the two tokens the Router wrapped into its registration, which {IFrameAccount.tokensOf}
///          answers (the Router refuses a venue whose id names others, `IMMRouter.VenueMismatch`), and a registration
///          changes neither another venue's threshold nor the account's mode at the lender (one e-mode, one pool
///          group, fixed by its first venue);
///        - its {borrowable}, {collateralReleasable} and {collateralPostable} report what the lender's liquidity, caps
///          and gates allow, as at a pair's own account, while the frame's other venues hold no net deficit at the
///          lender's prices and thresholds, as each venue's pin then keeps the frame whole;
///        - while they hold one, a borrow and a release are bounded too by the frame's spare room at the lender, so the
///          lender's own check passes on them; that room never raises a figure;
///        - the Router reads them before its own legs (a refinance reads its source's release before its bridge repays
///          there and its destination's borrow before the collateral lands, a plan each borrow before its own post)
///          and holds each venue at its pair's pin itself, so every leg it takes passes at the lender;
///        - a figure the spare room bounds counts no collateral those legs bring after the read, so a plan lends less
///          there and a move into such a frame may be refused; a kind's notes name any interest its read of that room
///          leaves out (`CTokenAccount` reads every market but the venue's own two as stored);
///        - its {returnToPool} takes the loan token of any of its venues;
///      - {collateralPostable} reports the room its lender leaves the venue's collateral market, net of what the
///        account holds for the venue's next post and parted among the account's own venues there, so one plan's
///        posts at one account fit that room together (`CTokenAccount` gives each an equal part):
///        - a post adds to the lender's market at most its assets and, where collateral accrues, what the account held
///          for it: a post too small to mint a unit, so under one unit's assets (`collateralUnitsToAssets(id, 1)`),
///          which the next post mints with its own;
///        - where the kind declares `CAP_SHARED_LIQUIDITY` (one reserve per token, as every deployer bound at its
///          number declares it, which the Router holds the pool's venues of the kind to when it admits one:
///          `IMMRouter.addVenue`) that room is one for every account of the kind, and the Router sizes each post of a
///          plan within what the plan's posts through the pair's other accounts there, each with one unit's assets
///          where collateral accrues, left of its venue's report (`MMRouterLib.buildPlan`), so a pair whose venues sit
///          at several of them (its own, its own under a later deployer, frames') never posts past it;
///        - an account that parts the room among several venues there has each part held to its share less those
///          posts whole, so a plan may leave room unposted that a later plan posts;
///        - at a kind without it, no two accounts' posts share one cap: its markets cap no post, or each position's
///          own;
///      - the Router bounds a pool's venues by their number alone (`MAX_VENUES`), never a pro-rata exit's gas, which
///        grows with the pool's live positions, each repaid and released in the exit, and with what each kind's legs
///        price (a lender that prices more markets or reserves on a release, a frame's release every market its account
///        entered, a gift's collateral flag left set), nor a releasing swap's, which grows with the venues it reads,
///        those where its input repays a debt and those it walks to release collateral of the token it pays out, and
///        with what their legs price, and can grow faster per venue than an exit's, against the 2^24 gas one
///        transaction may take (EIP-7825). The curator keeps a pool's positions within what one exit and one releasing
///        swap carry; nothing checks it on chain;
///      - a repay never reverts on its size or on a price:
///        - where a venue refuses a partial repay (a minimum position valued at its own oracle, a burn of zero scaled
///          units), the kind repays what the venue takes, down to that minimum, or nothing while that price cannot be
///          read, and the Router returns the rest to the pool; a repay of the whole debt reads no price;
///        - a kind whose venue can hold a partial repay of more than dust short (a minimum position) declares
///          `CAP_HELD_REPAY` and answers `IHeldRepay.minimumDebt`, never reverting and within
///          `MMRouterLib.MINIMUM_READ_GAS` (1,000,000 gas): the Router reads it by a static call of that much gas and
///          passes over a venue whose read reverts, answers short or runs past it. The pool records the bit when it
///          admits the venue (`FLAMMStore.S.heldRepayVenues`);
///        - such a venue refuses a borrow or a supply that leaves its position under the minimum, and the Router's plan
///          and supply cascade pass over a slice or a take there that would;
///        - a curator's or keeper's move into such a venue (`IMMRouter.migrateSupply`, `IMMRouter.refinanceDebt`) that
///          would leave its position under the minimum is not passed over: it reverts at the venue, which refuses it,
///          and the move's caller sizes it again;
///        - an entry's preview refuses such a leg as the entry does, and one reaching the minimum exactly, which the
///          lender's rounding decides (`FLAMMSharedLib.heldLegsCheck`);
///        - a payout's or a rotation's quote, which reads the plan, refuses where the swap's plan does on the state
///          both read. Two settlement steps move that state between the quote's read and the swap's plan: the
///          withdrawal of the payout pair's lent backing, which frees post room under the posting market's supply cap,
///          and a release out of a reserve the draw's venue shares while that venue is held under the reserve's cash by
///          its debt cap, its collateral or its rate ceiling. There a quoted swap can revert
///          `IMMRouter.InsufficientLiquidity` by the slice its plan passes over, which is under one minimum position,
///          and a swap the quote refuses can fill; a swap never fills under its quote;
///        - a cover's quote counts the release of a partial repay only where the repay leaves the debt over that
///          minimum by the lenders' rounding (`FLAMMGateLib.holdsRepay`; at a shared reserve, what it may release still
///          comes off the reserve's cash), and a rotation repays the venue whole or passes it over;
///        - a kind whose venue refuses every repay for a while (a pause, a broker) clears `CAN_REPAY` under
///          `CAP_ACTION_GATES` while it does;
///      - a lender's rounding moves debt by at most four base units: a partial repay leaves at most four over the
///        exact rest (`MMRouterLib.RELEASE_SLACK`), and a refinance's repay and borrow together change the two venues'
///        summed debt by at most four (`MMRouterLib.REFINANCE_SLACK`). A kind that rounds coarser has those releases
///        and refinances refused by the excess;
///      - a collateral release reads no price at zero debt unless the kind reports `CAP_PRICED_RELEASE`: its release
///        then reads the venue's oracle, owing or not, and while that oracle cannot be read its {collateralReleasable}
///        is zero, so the Router leaves the collateral posted, waiting for the oracle, and never asks the venue for a
///        release that would fail on that oracle;
///      - what {collateralReleasable} and {supplyWithdrawable} report can be paid: a venue that pays a release or a
///        withdrawal in whole units (a Compound-style market, whose redemption burns at least one unit) reports
///        nothing while its cash is under one unit's payout, as no redemption can be paid then; the pool's exit
///        maximum and its cash budget read those figures as payable;
///      - no view the Router or the pool reads reverts ({capacity} and its single fields {borrowable},
///        {supplyWithdrawable}, {suppliable}, {collateralReleasable}, {collateralPostable} and {actions}, with
///        `IActionsOf.actionsOf` where the kind answers it,
///        {positionOf}, {position}, {debtOf}, {collateralOf}, {lltv}, the two conversions, {healthy}, {oraclePrice},
///        {borrowRateAfter}, {ceilingBorrowSlice} and {haircut}): the pool reads every live venue on every flow, and
///        retiring a venue reads it, so one revert would stop every flow of the pool and keep the venue from being
///        retired:
///        - while its protocol cannot be read, a kind catches the revert, answers from its last good position, neither
///          zeroed nor marked down, and refuses every action: `actions` all clear, every capacity zero, {healthy} false
///          while it owes, {oraclePrice} and {borrowRateAfter} `ok == false` (so {ceilingBorrowSlice} zero), and every
///          leg refused; but at the Aave V3 kind while only one reserve's configuration word cannot be read, only the
///          views that read that word refuse, and a leg whose views read only the other still goes (the one-field
///          views' bullet above);
///        - a kind never answers so when the failed call ran out of gas (it left the kind at most 1/64 of the gas it
///          forwarded): it reverts instead, so no caller can make a venue look frozen by starving it;
///        - only under `CAP_ACTION_GATES` does the Router read every refusal (`actions` and each capacity), so a kind
///          that can become unreadable declares it;
///        - kind 0 cannot become so, as the immutable Morpho Blue it binds and the rate model whose codehash it pins
///          answer every read; a kind built from it for another venue that can refuse an action, cap a leg or become
///          unreadable (a pausable or upgradeable core, a rate model behind a proxy) declares `CAP_ACTION_GATES` and
///          `CAP_PROTOCOL_CAPS`;
///        - the pool reads a venue that holds a position and allows no action as a frozen venue mark: its value views
///          refuse (`VenueFrozen`), and no flow moves that venue's share through idle cash;
///      - {position}'s `debt` is zero exactly when {positionOf}'s `borrowShares` is: the Router tells an owing venue
///        from either read (its drawn sets and a retirement from the raw shares, a plan's draw test and its `book` from
///        the debt), so the two must agree;
///      - {positionOf} is a raw read of the position's units, with no accrual and no rate model, that answers wherever
///        {position} does: the Router's drawn sets and retirements and the pool's emergency path read it while a
///        venue's rate model cannot be read;
///      - debt never matures and is prepayable whenever its venue takes a repay (a kind under `CAP_ACTION_GATES`
///        reports a refused repay as a cleared `CAN_REPAY`), credit and debt never net, and one id fails as a unit;
///      - a position without debt gains none until the Router borrows or refinances onto it: no one else can borrow
///        for it or move debt onto it, as a redistribution of other borrowers' debt would (the pool's debt-free flags,
///        `FLAMMStore.TokenCfg.debtFree`, rely on it);
///      - one position's collateral units and supply shares fit in 128 bits, and so do its debt and its collateral
///        assets: the Router tracks what it posted and supplied as uint128, and a leg that would carry either past
///        2^128 - 1 reverts; a repay's snapshot packs the venue's debt and collateral assets in 128 bits each.
///      What varies by kind is reported, never assumed: each leg's liquidity, caps and rate limits through
///      {capacity}, a refused action as zero capacity and a cleared `actions` bit, the threshold through {lltv}, and
///      the position's own borrow rate through {borrowRateAfter}.
interface IFinancingAccount {
    /// @notice {refinance} at a kind with no atomic move.
    error Unsupported();

    /// @notice What one position can move now, within the venue's liquidity, caps and rate limits; a refused action
    ///         reads zero, an unbounded leg `type(uint256).max`. Native units: `borrowable`, `suppliable` and
    ///         `supplyWithdrawable` of the loan token, `collateralReleasable` of the collateral token before any health
    ///         check (a kind that never lends collateral bounds it by nothing while it allows a release; under
    ///         `CAP_PRICED_RELEASE`, zero while the venue's oracle cannot be read), and `collateralPostable` of the
    ///         collateral token a post may add before the venue's own cap on its collateral refuses (a kind that caps
    ///         no post bounds it by nothing while it takes posts).
    struct Capacity {
        uint256 borrowable; // loan-token base units
        uint256 suppliable; // loan-token base units
        uint256 supplyWithdrawable; // loan-token base units
        uint256 collateralReleasable; // collateral-token base units
        uint8 actions; // the `CAN_` bits of what the venue lets this position do now
        uint256 collateralPostable; // collateral-token base units
    }

    /// @notice The Router, the one caller of the normal path (`NotRouter`, on the kind's base, for any other).
    function ROUTER() external view returns (address);
    /// @notice The pool whose positions this account holds, the one caller of the emergency path (`NotPool` for any
    ///         other).
    function POOL() external view returns (address);
    /// @notice The account's collateral token, which it posts; zero for a frame's account, whose venues name their own.
    function COLLATERAL_ASSET() external view returns (address);
    /// @notice The account's loan token, which it borrows and lends; for a frame's account, its frame.
    function LOAN_ASSET() external view returns (address);
    /// @notice The account's venue kind; one kind number is one lender (ADMISSION).
    function KIND() external view returns (uint8);
    /// @notice The kind's `CAP_` bits, which the Router and the pool read once, when each admits a venue.
    function capabilities() external view returns (uint256);

    // ---- normal path (router)
    /// @notice Registers a venue from protocol-specific params; returns its id and current threshold. Idempotent. A
    ///         frame's account takes `abi.encode(collateral, debt, params)`: the venue's pair's two tokens, then its
    ///         params.
    /// @param venueParams The kind's parameters, or a frame's wrapped form.
    /// @return id The venue's id at this account.
    /// @return lltvWad The venue's threshold now, WAD ({lltv}).
    function registerVenue(bytes calldata venueParams) external returns (bytes32 id, uint64 lltvWad);
    /// @notice Posts `assets` of the collateral token the Router has moved here.
    /// @param id The venue's id.
    /// @param assets The amount, in collateral-token base units.
    /// @return units The collateral units minted.
    function supplyCollateral(bytes32 id, uint256 assets) external returns (uint256 units);
    /// @notice Releases exactly `assets` of collateral.
    /// @param id The venue's id.
    /// @param assets The amount, in collateral-token base units.
    /// @param to The pool, or another account the Router registered for it (`BadReceiver` otherwise).
    /// @return units The collateral units burned.
    function withdrawCollateral(bytes32 id, uint256 assets, address to) external returns (uint256 units);
    /// @notice Borrows exactly `assets` of the loan token for the pool, or reverts.
    /// @param id The venue's id.
    /// @param assets The amount, in loan-token base units.
    /// @param to The receiver, which must be the pool (`BadReceiver`).
    function borrow(bytes32 id, uint256 assets, address to) external;
    /// @notice Repays up to `assets` from the loan tokens held here: in full where `assets` covers the accrued debt,
    ///         else what the venue takes of it (a minimum position, a held full exit: ADMISSION); never reverts on
    ///         either.
    /// @param id The venue's id.
    /// @param assets The most to repay, in loan-token base units.
    /// @return repaid What the venue took; the Router sends the rest back through {returnToPool}.
    function repay(bytes32 id, uint256 assets) external returns (uint256 repaid);
    /// @notice Lends `assets` of the loan token the Router has moved here.
    /// @param id The venue's id.
    /// @param assets The amount, in loan-token base units.
    /// @return shares The supply shares minted: zero only where a kind holds a supply too small to mint one for its
    ///         next (ADMISSION's bound on a supply); a kind whose lender would take it for nothing reverts.
    function supply(bytes32 id, uint256 assets) external returns (uint256 shares);
    /// @notice Withdraws supplied loan asset by exact `assets` or exact `shares` (exactly one nonzero) to the
    ///         pool, to this account, or to another account of the same pool.
    /// @param id The venue's id.
    /// @param assets The exact amount, in loan-token base units, or zero.
    /// @param shares The exact supply shares, or zero.
    /// @param to The receiver (`BadReceiver` for any other than the three above).
    /// @return withdrawn What the venue paid, in loan-token base units.
    /// @return sharesBurned The supply shares burned.
    function withdraw(bytes32 id, uint256 assets, uint256 shares, address to)
        external
        returns (uint256 withdrawn, uint256 sharesBurned);
    /// @notice Returns exactly `amount` of `token`, the loan token of the venue the Router repays (the account's loan
    ///         asset, or at a frame's account any of its venues'), to the pool; never a balance sweep. Any other token
    ///         reverts `VenueMismatch`.
    /// @param token The loan token.
    /// @param amount The amount, in the token's base units.
    function returnToPool(address token, uint256 amount) external;
    /// @notice Brings the venue's interest to now, so the reads that follow in the block take the accrued state. Best
    ///         effort: a failed accrual changes nothing, and a kind that never accrues does nothing.
    /// @param id The venue's id.
    function accrue(bytes32 id) external;
    /// @notice Moves `assets` of debt (`0` = all) and `collateralMove` collateral from `src` to `dst` in one
    ///         step; a kind without `CAP_ATOMIC_REFINANCE` reverts `Unsupported`. The Router counts the move one
    ///         collateral unit per asset, so it bridges a kind whose collateral accrues instead.
    /// @param src The source venue's id.
    /// @param dst The destination venue's id.
    /// @param assets The debt to move, in loan-token base units.
    /// @param collateralMove The collateral to move, in collateral-token base units.
    /// @return moved The debt moved.
    function refinance(bytes32 src, bytes32 dst, uint256 assets, uint256 collateralMove) external returns (uint256 moved);

    // ---- emergency path (bound pool only)
    /// @notice Repays up to `assets` from the loan tokens the pool has moved here, and sends back to the pool what the
    ///         venue does not take.
    /// @dev Each kind must state which of these survive each of its outage modes; the pool assumes none does. Morpho
    ///      Blue with its IRM unreadable: only `emergencyTopUp` on an indebted position stays live (`supplyCollateral`
    ///      alone does not accrue), and an `emergencyRepay` at a position with no debt repays nothing and returns the
    ///      assets; the rest revert until the market reads again.
    /// @param id The venue's id.
    /// @param assets The most to repay, in loan-token base units.
    /// @return repaid What the venue took.
    function emergencyRepay(bytes32 id, uint256 assets) external returns (uint256 repaid);
    /// @notice Posts `assets` of the collateral token the pool has moved here onto a position that owes (`NoDebt`
    ///         otherwise).
    /// @param id The venue's id.
    /// @param assets The amount, in collateral-token base units.
    /// @return units The collateral units minted.
    function emergencyTopUp(bytes32 id, uint256 assets) external returns (uint256 units);
    /// @notice Withdraws supplied loan asset to the pool by exact `assets` or exact `shares`, as {withdraw}. A kind may
    ///         read a request for the whole balance in its own form (`AaveV3Account`).
    /// @param id The venue's id.
    /// @param assets The amount, in loan-token base units, or zero.
    /// @param shares The supply shares, or zero.
    /// @return withdrawn What the venue paid, in loan-token base units.
    function emergencyWithdrawSupplied(bytes32 id, uint256 assets, uint256 shares) external returns (uint256 withdrawn);
    /// @notice Releases `assets` of collateral to the pool from a position that owes nothing (`DebtOutstanding`
    ///         otherwise).
    /// @param id The venue's id.
    /// @param assets The amount, in collateral-token base units.
    function emergencyWithdrawCollateral(bytes32 id, uint256 assets) external;

    // ---- views
    /// @notice The lowest threshold this position can be held to without a new action of the pool, live: the tighter
    ///         of the venue's borrow ceiling and liquidation threshold, a ramp's target included.
    /// @param id The venue's id.
    /// @return The threshold, WAD.
    function lltv(bytes32 id) external view returns (uint64);
    /// @notice The position's raw units, with no accrual and no rate model (ADMISSION).
    /// @param id The venue's id.
    /// @return supplyShares The supply shares it holds.
    /// @return borrowShares The borrow shares it owes.
    /// @return collateralUnits The collateral units it holds.
    function positionOf(bytes32 id)
        external
        view
        returns (uint256 supplyShares, uint256 borrowShares, uint256 collateralUnits);
    /// @notice The position at the accrued state, or the last good one while the protocol cannot be read: it never
    ///         reverts (ADMISSION). Its `collateral` and `debt` are {collateralOf} and {debtOf} in the same state: the
    ///         Router reuses them.
    /// @param id The venue's id.
    /// @return collateral The collateral, in collateral-token base units.
    /// @return supplyShares The supply shares it holds.
    /// @return supplied Those shares' worth, in loan-token base units.
    /// @return debt The debt, in loan-token base units.
    function position(bytes32 id)
        external
        view
        returns (uint256 collateral, uint256 supplyShares, uint256 supplied, uint256 debt);
    /// @notice The position's debt at the accrued state, in loan-token base units.
    function debtOf(bytes32 id) external view returns (uint256);
    /// @notice The position's collateral at the accrued state, in collateral-token base units.
    function collateralOf(bytes32 id) external view returns (uint256);
    /// @notice What `units` of collateral are worth at the accrued state, rounded down.
    /// @param id The venue's id.
    /// @param units The collateral units ({positionOf}).
    /// @return The worth, in collateral-token base units.
    function collateralUnitsToAssets(bytes32 id, uint256 units) external view returns (uint256);
    /// @notice What `shares` of supply are worth at the accrued state, rounded down.
    /// @param id The venue's id.
    /// @param shares The supply shares ({positionOf}).
    /// @return The worth, in loan-token base units.
    function supplySharesToAssets(bytes32 id, uint256 shares) external view returns (uint256);
    /// @notice `capacity(id).borrowable` alone, in the same state; so is each view below its own field of {capacity}
    ///         (`supplyWithdrawable`, `suppliable`, `collateralReleasable`, `collateralPostable`, `actions`), but at
    ///         the one exception ADMISSION names. The Router's hot paths read the one field they need where
    ///         {capacity} would build them all.
    function borrowable(bytes32 id) external view returns (uint256);
    /// @notice `capacity(id).supplyWithdrawable` alone, in the same state, but at the Aave V3 kind while only the
    ///         collateral reserve's configuration word cannot be read (ADMISSION).
    function supplyWithdrawable(bytes32 id) external view returns (uint256);
    /// @notice `capacity(id).suppliable` alone, in the same state.
    function suppliable(bytes32 id) external view returns (uint256);
    /// @notice `capacity(id).collateralReleasable` alone, in the same state, but at the Aave V3 kind while only the
    ///         loan reserve's configuration word cannot be read (ADMISSION).
    function collateralReleasable(bytes32 id) external view returns (uint256);
    /// @notice `capacity(id).collateralPostable` alone, in the same state, but at the Aave V3 kind while only the
    ///         loan reserve's configuration word cannot be read (ADMISSION).
    function collateralPostable(bytes32 id) external view returns (uint256);
    /// @notice `capacity(id).actions` alone, in the same state.
    function actions(bytes32 id) external view returns (uint8);
    /// @notice What the position can move now: each leg's room and the actions the venue allows.
    function capacity(bytes32 id) external view returns (Capacity memory);
    /// @notice The borrow rate this position pays after its leg (`deltaBorrow` more debt, `deltaSupplyDown` less
    ///         supply), at the accrued state, so a quote before any leg and the check after the withdrawal agree.
    ///         `ok == false`, never a clamped answer, when `deltaSupplyDown` would reach the venue's supply, the
    ///         post-state is undefined or the rate cannot be read.
    /// @param id The venue's id.
    /// @param deltaBorrow The added debt, in loan-token base units.
    /// @param deltaSupplyDown The supply taken out, in loan-token base units.
    /// @return ok Whether the rate reads.
    /// @return ratePerSecWad The rate, per second, WAD.
    function borrowRateAfter(bytes32 id, uint256 deltaBorrow, uint256 deltaSupplyDown)
        external
        view
        returns (bool ok, uint256 ratePerSecWad);
    /// @notice The Router's trim of a borrow slice over the venue's rate ceiling: zero where {borrowRateAfter}
    ///         `(id, deltaBorrow, deltaSupplyDown)`, at the slice's start, is not `ok` or reads over `maxRate`; else
    ///         the low end `lo` of a bisection of `[0, hi]` that, while `hi - lo > hi / 10_000 + 1` (`hi` its
    ///         shrinking upper end), reads {borrowRateAfter}`(id, deltaBorrow + mid, deltaSupplyDown)` at
    ///         `mid = lo + (hi - lo) / 2` and moves `lo` up to `mid` where that read is `ok` and at most `maxRate`,
    ///         else `hi` down to it. It answers exactly what that search over {borrowRateAfter} would, so it errs low;
    ///         a kind may take the reads no step moves once.
    /// @param id The venue's id.
    /// @param deltaBorrow The debt the plan already adds here, in loan-token base units.
    /// @param deltaSupplyDown The supply the plan already takes out, in loan-token base units.
    /// @param hi The slice's upper end, in loan-token base units.
    /// @param maxRate The rate ceiling, per second, WAD.
    /// @return slice The slice, in loan-token base units.
    function ceilingBorrowSlice(bytes32 id, uint256 deltaBorrow, uint256 deltaSupplyDown, uint256 hi, uint256 maxRate)
        external
        view
        returns (uint256 slice);
    /// @notice The venue's own price: loan base units per collateral base unit, scaled by 1e36. While its pair's
    ///         venue-oracle band is on, `ok == false` refuses the paths the venue prices (a borrow, a priced release
    ///         of an indebted venue's collateral, a refinance onto it) and an admission given a price; with the band
    ///         off no path reads it and the venue's own checks stand alone.
    /// @param id The venue's id.
    /// @return ok Whether the price reads.
    /// @return price The price, scaled by 1e36.
    function oraclePrice(bytes32 id) external view returns (bool ok, uint256 price);
    /// @notice The venue's own health predicate, as the market enforces it when collateral leaves. Morpho Blue: no
    ///         borrow shares, or `collateral * price / 1e36 * LLTV >= debt` at the accrued state (debt rounded up,
    ///         bound down); with debt, false when the oracle cannot be read.
    function healthy(bytes32 id) external view returns (bool);
    /// @notice The share of face value the venue cannot pay on this position's collateral and on its supply, WAD each
    ///         (a lender's reserve deficit spread over its suppliers), zero where it can pay all. Every other read
    ///         values units at face; the pool applies this to its NAV and to an exit's slices, and the Router never
    ///         reads it. A kind that can answer nonzero declares `CAP_REPORTED_LOSS`: the pool asks no other. It is
    ///         only as complete as what the lender records: the comptroller kind (`CTokenAccount`) answers a
    ///         redemption fee alone, as its lender records no bad debt, so a loss there reads zero.
    /// @param id The venue's id.
    /// @return collateralLossWad The share lost on its collateral, WAD.
    /// @return supplyLossWad The share lost on its supply, WAD.
    function haircut(bytes32 id) external view returns (uint64 collateralLossWad, uint64 supplyLossWad);
}

/// @notice A frame's account (`FRAME_VENUE`), which a kind that holds frames answers: the Router reads it of
///         every venue it admits there and refuses one whose tokens are not its pair's (`IMMRouter.VenueMismatch`),
///         so an id there names one pair for good, and a kind that answers nothing takes no frame venue.
interface IFrameAccount {
    /// @notice The two tokens venue `id` was registered for, as the Router wrapped them; zero for an id never
    ///         registered. Never reverts.
    /// @param id The venue's id.
    /// @return collateral The venue's collateral token.
    /// @return debt The venue's debt token.
    function tokensOf(bytes32 id) external view returns (address collateral, address debt);
    /// @notice Whether the lender counts venue `id`'s posted collateral in the account's health now, whatever the
    ///         venue's threshold reads: {IFinancingAccount.lltv} may be a borrow ceiling, which reads zero where the
    ///         lender lends nothing more on a collateral it still counts at its liquidation threshold, and reads live
    ///         where the lender counts the collateral for nothing (Aave V3: the account's collateral flag on the token
    ///         is down). False while that cannot be read, and for an id never registered. The pool reads it of a
    ///         frame's venues alone, for the frame's sums, its due venues and its top-ups through a mate
    ///         (`FLAMMTopUpLib`); the Router never reads it. Never reverts.
    /// @param id The venue's id.
    /// @return Whether the lender counts the venue's collateral.
    function collateralCounted(bytes32 id) external view returns (bool);
}

/// @notice A view a kind may answer beside {IFinancingAccount.actions}, sized to the actions a reader wants: the Router
///         reads a venue's gate through it (`MMRouterLib.canAct`) where the venue's account answered it at admission
///         as its `actions` (`IMMRouter.addVenue`), and through `actions` elsewhere, so a kind may add it or not.
interface IActionsOf {
    /// @notice `actions(id) & want`, in the same state, reading only what those actions need: a bit reads the same
    ///         whatever else `want` names, but at the Aave V3 kind where one reserve's configuration word cannot be
    ///         read and the other's can: {IFinancingAccount.actions} reads none there, while a bit that needs only the
    ///         readable word answers by it, so with the collateral's word unreadable a repay passes the Router's gate
    ///         (`MMRouterLib.canAct`). Never reverts (ADMISSION).
    /// @param id The venue's id.
    /// @param want The `CAN_` bits asked about.
    /// @return The bits of `want` the venue allows now.
    function actionsOf(bytes32 id, uint8 want) external view returns (uint8);
}

src/interfaces/core/mm/IMMRouter.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 {IFinancingAccount} from "src/interfaces/core/mm/IFinancingAccount.sol";
import {WAD as ONE_WAD} from "src/libraries/Constants.sol";

/// @dev One in WAD, the 18-decimal fixed point of LTVs, bands, rates and USD prices.
uint256 constant WAD = ONE_WAD;
/// @dev A venue oracle's price scale: debt base units per collateral base unit, times 1e36.
uint256 constant ORACLE_PRICE_SCALE = 1e36;
/// @dev Tokens a pool may list, its pool asset (token 0) included; the owed and backing sets are 16-bit masks over
///      them.
uint256 constant MAX_TOKENS = 16;
/// @dev Credit pairs a pool may hold, retired ones included: a retired pair keeps its index and its accounts'
///      addresses. Every ordered pair of two distinct tokens, each added once, so the limit never binds before the
///      token list does; a pair index is a uint8.
uint256 constant MAX_PAIRS = MAX_TOKENS * (MAX_TOKENS - 1);
/// @dev The Morpho Blue venue kind. A constant, not an enum: governance adds kinds through
///      `FLAMMFactory.setAccountDeployerOf`.
uint8 constant VENUE_KIND_MORPHO_BLUE = 0;
/// @dev Venues the Router holds for one pool at once; a retired venue's slot (and id) is reused by the next admission,
///      and the pool's own records take fewer (`FLAMMStore.MAX_POOL_VENUES`). The Router bounds their number alone,
///      never a pro-rata exit's gas, which grows with the pool's live positions, each repaid and released in the exit,
///      nor a releasing swap's, which grows with the venues it reads, those where its input repays a debt and those it
///      walks to release collateral of the token it pays out (`IMMRouter.reclaimBestEffort`), and can grow faster per
///      venue than an exit's, against the 2^24 gas one transaction may take (EIP-7825). A swap whose release takes it
///      past that gas reverts at every gas limit while the release is due, where no venue's release alone takes three
///      million gas (a release that began with that much and failed starved ends the walk as the lender's burn:
///      `reclaim`). The curator's or keeper's `Release` on the maintenance path (`FLAMM.maintain`) releases with no
///      swap what its caller names, so it clears a release due before a swap, never one the swap's own repay makes due.
///      The curator keeps a pool's positions within what one exit and one releasing swap carry; nothing checks it on
///      chain.
uint256 constant MAX_VENUES = 64;
/// @dev `IMMRouter.minLltv` where no venue of the pair binds the pin: none can borrow and none owes anything. A zero
///      threshold binds.
uint256 constant NO_VENUE_LLTV = type(uint256).max;
/// @dev A status bit of a venue (`IMMRouter.VenueView.status`, one byte of bits; zero is a live venue, in every
///      priority order). Retired: the slot holds no position the Router reads, and the next admission may reuse it. A
///      retired venue is not fenced.
uint8 constant VENUE_RETIRED = 1;
/// @dev A status bit of a venue, as {VENUE_RETIRED}. Fenced: locked by its pool (`IMMRouter.lockVenue`) until the pool
///      lifts the lock or the venue retires.
uint8 constant VENUE_FENCED = 2;
/// @dev The word that opens a frame venue's params (`IMMRouter.addVenue`): `abi.encode(FRAME_VENUE, frame, params)`
///      puts the venue in frame `frame` (a tag the pool picks, read as an address) at its kind: one account, one
///      position at the lender, shared by the venues of every pair the pool puts in that frame, instead of the pair's
///      own account. A pool chooses per venue: plain params (the pair's own account, the default), one frame for every
///      pair at a lender, or several frames; a pair may hold venues at its own account and at several frames of one
///      kind at once.
bytes32 constant FRAME_VENUE = keccak256("FLAMM.frameVenue");

/// @notice A pair's price in its venues' price scale: debt base units per collateral base unit, scaled by 1e36, from
///         the two tokens' USD prices (WAD per whole token) and decimals (each at most 18): `usdColl * 10^(36 +
///         debtDecimals - collDecimals) / usdDebt`, rounded down, in one `mulDiv`. Zero, an unchecked price, when
///         either USD price is zero or the result would not fit a word, so an absurd answer never reverts a read. The
///         Router, the pool and the periphery price every pair with this function alone, so each direction comes from
///         the two USD prices and none is the inverse of another.
function pairPrice36(uint256 usdColl, uint256 usdDebt, uint8 collDecimals, uint8 debtDecimals) pure returns (uint256) {
    if (usdColl == 0 || usdDebt == 0) return 0;
    uint256 m = 10 ** (36 + uint256(debtDecimals) - uint256(collDecimals));
    if (usdColl / usdDebt >= type(uint256).max / m) return 0;
    return Math.mulDiv(usdColl, m, usdDebt);
}

/// @notice The shared money-market router. Each pool lists tokens (token 0 is its pool asset) and credit pairs over
///         them: a pair borrows its debt token against its collateral token, at venues held in its (pair, kind)
///         financing accounts, or in a frame's account its pool shares among several pairs at a kind (`FRAME_VENUE`).
///         Pool-scoped calls act on `msg.sender`'s namespace, and refuse a caller no `registerPool` registered
///         (`NotRegistered`), `accrueExcept` aside, which accrues nothing for one; `registerPool` is Factory-only; the
///         protocol owner (`protocolSafe`) pauses and unpauses (`setGlobalPaused`). Amounts are native base units.
///         Inbound legs pull from the pool's allowance what they consume: a post pulls the venue's collateral token, a
///         repay, supply or bridge its debt token, and a repay hands back in the same call what its lender did not
///         take. Every mutating call but `setGlobalPaused` holds the Router's transient lock
///         (`ReentrancyGuardLib.Reentrant`), and the views that read positions through a plan or a walk (`drawn`,
///         `venuePosition`, `book`, `fundingCeiling`, `fundingCollateral`, `borrowRoom`, `supplyRoom`, `reclaimable`)
///         refuse while it is held.
/// @dev    The protocol owner. `protocolSafe`, the Factory's `PROTOCOL_SAFE`, is the protocol owner's address on chain:
///         as deployed a `FactoryAdmin` forwarder, whose `SAFE` is the owner's multisig. The rewards every account
///         sends there, and the fees paid to the Factory's `protocolFeeReceiver` while it names that address, sit there
///         until the protocol owner moves them with `execute`.
///
///         Prices. Every priced call takes `usd`, the pool's checked USD price of each of its tokens (WAD per whole
///         token, indexed as the pool's token list, exactly `tokenCount` long, else `BadPriceVector`); zero means
///         that token is unchecked. The Router prices each venue at its own pair ({pairPrice36} of the venue's
///         collateral and debt tokens), so no caller hands it a pair's price. A priced path refuses an unchecked pair;
///         the price gates only risk-increasing legs.
///
///         No circularity. The owed set is the tokens some unfenced venue lends the pool, the backing set the
///         collateral tokens of those venues. A borrow at a venue that owes nothing, on pair (a -> b), is refused
///         (`DrawOutsideDrawnSet`) when a is owed, when b backs a debt, or when b would raise the owed set past
///         `maxDrawnTokens`. Every path that can start a debt checks it (`borrow`, `fund`'s borrow phase, `borrowRoom`
///         and `fundingCeiling`), `refinanceDebt` stays inside one pair onto a venue whose pair already owes, and
///         `lockVenue` lifts no fence where the venue would make the sets circular, so among the unfenced venues no
///         token is ever owed and backing at once: a pool is never long and short one pair, and no chain a -> b -> c is
///         drawn. A fenced venue's debt and collateral sit outside both sets.
///
///         Fences. `lockVenue` fences one live venue, whatever it holds, so a pool can stand clear of one lender that
///         stops answering its legs while that lender's other markets, and other lenders of the same tokens, stay live;
///         a pool fences every venue naming a token to take the token out of its pool book.
///         - A fenced venue's borrow and supply switches go off and cannot turn on while it is fenced
///           (`VenueIsFenced`), and it leaves the four priority orders.
///         - `book`, `accrueExcept`, the cascades (`repayCascade`, `supplyCascade`, `withdrawCascade`, `reclaim`,
///           `reclaimBestEffort`, `reclaimable`), the plans (`fund`, `fundingCeiling`, `fundingCollateral`,
///           `borrowRoom`) and the drawn sets pass a fenced venue; the caps, `minLltv` and the by-id views still count
///           it.
///         - It takes no leg that adds to it or moves it to another venue (a post, a borrow, a supply, a priced release
///           while it owes, a refinance or a migration at either end; `borrow` and `supply` refuse on its switches) and
///           stays open to the by-id legs that unwind it: `repay`, a proportional `withdrawCollateral`,
///           `withdrawSupplied`, `syncManaged`, `recognizeCollateral` and, once it holds nothing, `retireVenue`.
///         - The pool's `lockVenue` lifts the fence: the venue rejoins the priority orders, last.
///         - A frame's account (`FRAME_VENUE`) is one position at its lender for all its venues: the Router refuses a
///           venue joining it while one there is fenced (`VenueIsFenced`), and no more, as each of its other venues
///           takes every leg its own state allows, so the pool fences, lifts and gives up a frame's venues together.
interface IMMRouter {
    /// @notice A listed token as the Router records it for a pool ({token}).
    struct TokenView {
        address token; // the token's address
        uint8 decimals; // at most 18
        uint256 scale; // 10^(18 - decimals): lifts the token's base units to 18 decimals
        uint128 supplyCap; // across every venue lending it, in the token's base units; zero: none
        bool retired; // terminal: the token takes no new pair and no supply cap
    }

    /// @notice A credit pair as the Router records it ({pair}): it borrows token `debt` against token `coll`.
    struct PairView {
        uint8 coll; // the collateral token's index in the pool's list
        uint8 debt; // the debt token's index in the pool's list
        uint64 pinLtvWad; // the LTV a borrow is held to, WAD
        uint64 safetyGapWad; // the room a borrowing venue's threshold keeps over the pin, WAD; written once
        uint64 oracleBandWad; // how far a venue's own oracle may sit from the pair's price, WAD; zero: none is read
        uint128 debtCap; // the pair's debt across its venues, in debt-token base units; zero: none
        bool borrowEnabled; // the pair's borrow switch, beside each venue's own
        bool retired; // terminal: its venues are retired and hold nothing
    }

    /// @notice A venue as the Router records it ({venue}), with its account's threshold read live.
    struct VenueView {
        address account; // the financing account that holds the position
        bytes32 id; // the venue's id at that account
        uint8 kind; // the venue kind, one lender
        uint8 pair; // its credit pair's index
        uint8 coll; // its pair's collateral token's index
        uint8 debt; // its pair's debt token's index
        uint64 lltvWad; // live: the account's threshold now
        bool borrowEnabled; // the venue's borrow switch, beside its pair's
        bool supplyEnabled; // the venue's supply switch
        uint8 status; // VENUE_RETIRED and VENUE_FENCED bits; zero: live, in every priority order
        uint128 debtCap; // the venue's debt, in debt-token base units; zero: none
        uint128 supplyCap; // the venue's supply, in debt-token base units; zero: none
        uint64 maxBorrowRateWad; // the highest borrow rate a borrow may leave, per second, WAD; zero: none
    }

    /// @notice `pool` is registered, with `poolAsset` as its token 0 ({registerPool}).
    event PoolRegistered(address indexed pool, address poolAsset);
    /// @notice `pool` lists `token` as token `idx`: the pool asset at {registerPool}, any other at {addToken}.
    event TokenAdded(address indexed pool, uint8 indexed idx, address token);
    /// @notice `pool` sets token `idx`'s supply cap, in the token's base units ({setTokenSupplyCap}).
    event TokenSupplyCapSet(address indexed pool, uint8 indexed idx, uint128 supplyCap);
    /// @notice `pool` retires token `idx` ({retireToken}).
    event TokenRetired(address indexed pool, uint8 indexed idx);
    /// @notice A venue enters (`fenced`) or leaves its fence: it enters at its pool's `lockVenue`, out of the priority
    ///         orders with both switches off (`VenueFlagsSet`, `PrioritiesSet`), and leaves at the pool's lift, back in
    ///         the orders last with its switches still off (`PrioritiesSet`), or at its own retirement (`retireVenue`).
    event VenueFenced(address indexed pool, uint16 indexed id, bool fenced);
    /// @notice `pool` lists credit pair `idx`, which borrows `debt` against `coll`, with its pin, gap and oracle band,
    ///         each WAD ({addPair}).
    event PairAdded(address indexed pool, uint8 indexed idx, uint8 coll, uint8 debt, uint64 pin, uint64 gap, uint64 band);
    /// @notice `pool` sets pair `idx`'s debt cap, in debt-token base units, and its borrow switch ({setPairCaps}).
    event PairCapsSet(address indexed pool, uint8 indexed idx, uint128 debtCap, bool borrowEnabled);
    /// @notice `pool` retires pair `idx` ({retirePair}).
    event PairRetired(address indexed pool, uint8 indexed idx);
    /// @notice `pool` sets how many tokens it may owe at once ({setMaxDrawnTokens}).
    event MaxDrawnTokensSet(address indexed pool, uint8 maxDrawnTokens);
    /// @notice A venue of `pair` at `kind` deploys `account`, the first there under the kind's deployer of the day: the
    ///         pair's own, or a frame's (`FRAME_VENUE`), which answers no collateral token and its frame as its loan
    ///         token. The venues that find the account later announce nothing.
    event AccountDeployed(address indexed pool, uint8 indexed pair, uint8 indexed kind, address account);
    /// @notice `pool` admits venue `id` of `pair` at `kind`, `venueId` its id at its account ({addVenue}); the venue
    ///         joins the priority orders, last, with no `PrioritiesSet`.
    event VenueAdded(address indexed pool, uint16 indexed id, uint8 kind, uint8 pair, bytes32 venueId);
    /// @notice A venue's two switches as they stand after {addVenue}, {setVenueFlags}, or a fence that turned one off.
    event VenueFlagsSet(address indexed pool, uint16 indexed id, bool borrowEnabled, bool supplyEnabled);
    /// @notice `pool` sets venue `id`'s two caps, in debt-token base units, and its rate ceiling, per second, WAD
    ///         ({setVenueCaps}).
    event VenueCapsSet(address indexed pool, uint16 indexed id, uint128 debtCap, uint128 supplyCap, uint64 maxBorrowRateWad);
    /// @notice `pool` retires venue `id`, whose slot the next admission may reuse ({retireVenue}); a live venue leaves
    ///         the priority orders with no `PrioritiesSet`.
    event VenueRetired(address indexed pool, uint16 indexed id);
    /// @notice The four priority orders as they stand after {setPriorities}, or a fence's lock or lift ({lockVenue}).
    event PrioritiesSet(address indexed pool, uint16[] borrow, uint16[] supply, uint16[] withdraw, uint16[] repay);
    /// @notice `pool` sets `pair`'s pin, WAD ({setPin}).
    event PinSet(address indexed pool, uint8 indexed pair, uint64 pinLtvWad);
    /// @notice `pool` turns `fund`'s per-slice re-check on or off ({setFundRecheck}).
    event FundRecheckSet(address indexed pool, bool on);
    /// @notice `pool` sets `pair`'s venue-oracle band, WAD ({setOracleBand}).
    event OracleBandSet(address indexed pool, uint8 indexed pair, uint64 oracleBandWad);
    /// @notice The protocol owner sets or clears the global pause ({setGlobalPaused}).
    event GlobalPauseSet(bool paused);
    /// @notice Venue `id` lends `assets` of its debt token to `to` ({borrow}, {fund}'s borrow phase).
    event Borrowed(address indexed pool, uint16 indexed id, uint256 assets, address to);
    /// @notice Venue `id` takes a repay of `assets` of its debt token ({repay}, {repayCascade}).
    event Repaid(address indexed pool, uint16 indexed id, uint256 assets);
    /// @notice Venue `id` takes a supply of `assets` of its debt token ({supply}, {supplyCascade}).
    event Supplied(address indexed pool, uint16 indexed id, uint256 assets);
    /// @notice Venue `id` pays `assets` of its supply to `to` ({withdrawSupplied}, {withdrawCascade}, {fund}'s
    ///         withdrawal phase).
    event SuppliedWithdrawn(address indexed pool, uint16 indexed id, uint256 assets, address to);
    /// @notice Venue `id` takes a post of `assets` of its collateral token ({postCollateral}, {fund}'s borrow phase).
    event CollateralPosted(address indexed pool, uint16 indexed id, uint256 assets);
    /// @notice Venue `id` releases `assets` of its collateral token to the pool ({withdrawCollateral}, {reclaim}).
    event CollateralWithdrawn(address indexed pool, uint16 indexed id, uint256 assets);
    /// @notice `assets` of debt and `collateralMoved` of collateral move from venue `src` to venue `dst`
    ///         ({refinanceDebt}).
    event DebtRefinanced(address indexed pool, uint16 indexed src, uint16 indexed dst, uint256 assets, uint256 collateralMoved);
    /// @notice Supply moves from venue `src` to venue `dst`, `assets` what the source paid ({migrateSupply}).
    event SupplyMigrated(address indexed pool, uint16 indexed src, uint16 indexed dst, uint256 assets);

    /// @notice {registerPool}'s caller is not the Factory that constructed this Router.
    error NotFactory();
    /// @notice {setGlobalPaused}'s caller is not `protocolSafe`.
    error NotProtocolSafe();
    /// @notice A pool-scoped call's caller is no registered pool.
    error NotRegistered();
    /// @notice {registerPool} names a pool registered before.
    error AlreadyRegistered();
    /// @notice The pool {registerPool} names does not answer the Factory, this Router and the pool asset as its own.
    error PoolBindingMismatch();
    /// @notice {addVenue}'s account is not at its deployer's CREATE2 address, or its bindings read back otherwise.
    error AccountCodeMismatch();
    /// @notice {addVenue} names a kind with no account deployer at the Factory.
    error KindUnknown();
    /// @notice {addVenue}'s kind declares a capability outside `KNOWN_CAPABILITIES`.
    error UnknownCapability();
    /// @notice A token index past the pool's list.
    error BadTokenIndex();
    /// @notice A pair index past the pool's list.
    error BadPairIndex();
    /// @notice The call names a retired token where a live one is needed.
    error TokenIsRetired();
    /// @notice The call names a retired pair where a live one is needed.
    error PairIsRetired();
    /// @notice {retireToken} names a token a live pair still names.
    error TokenInUse();
    /// @notice {retirePair} names a pair a venue of which is not retired or still holds something.
    error PairNotEmpty();
    /// @notice {addToken} names a token listed before, a retired one included.
    error DuplicateToken();
    /// @notice {addPair} names a pair added before, a retired one included.
    error DuplicatePair();
    /// @notice {addToken} past `MAX_TOKENS`.
    error TooManyTokens();
    /// @notice {addPair} past `MAX_PAIRS`.
    error TooManyPairs();
    /// @notice A priced call's `usd` is not `tokenCount` long.
    error BadPriceVector();
    /// @notice A draw at a venue that owes nothing would make a token owed and backing at once, or pass
    ///         `maxDrawnTokens`; also a fence's lift that would make a token owed and backing at once ({lockVenue}).
    error DrawOutsideDrawnSet();
    /// @notice A leg the global pause stops ({setGlobalPaused}).
    error GlobalPaused();
    /// @notice A venue's tokens are not its pair's ({addVenue}), or the two ends of a move are one venue, or do not
    ///         share the pair ({refinanceDebt}) or the debt token ({migrateSupply}).
    error VenueMismatch();
    /// @notice {addVenue} names a position a live or fenced slot already names.
    error DuplicateVenue();
    /// @notice {addVenue} past `MAX_VENUES`, with no retired slot to reuse.
    error TooManyVenues();
    /// @notice A venue id past the pool's list.
    error BadVenueId();
    /// @notice The call needs a venue that is not retired.
    error VenueIsRetired();
    /// @notice The call asks of a fenced venue what it does not take (a leg, a switch on), or {addVenue} joins an
    ///         account with a fenced venue.
    error VenueIsFenced();
    /// @notice {retireVenue} names a venue that owes or recognizes something.
    error VenueNotEmpty();
    /// @notice The venue's switch for the leg, or its pair's, is off.
    error VenueDisabled();
    /// @notice {setPriorities} is handed an order that does not list every live, unfenced venue exactly once.
    error BadPriorities();
    /// @notice A setting or an amount outside what the call takes (each call states its bounds).
    error InvalidConfig();
    /// @notice The pair's price is unchecked, or the venue's oracle sits outside the pair's band or does not read.
    error OracleBand();
    /// @notice A borrow would pass the venue's or the pair's debt cap.
    error DebtCapExceeded();
    /// @notice A supply would pass the venue's or the token's supply cap, or what the venue takes now.
    error SupplyCapExceeded();
    /// @notice A borrow would leave the venue's borrow rate over its ceiling, or the rate does not read.
    error RateCeiling();
    /// @notice The venue's threshold sits under its pair's pin plus the gap, so it lends nothing.
    error VenueOverPinned();
    /// @notice A leg would leave the venue past the LTV it is held to: a borrow's or a priced release's bound, or a
    ///         proportional release past what the repay freed.
    error Unhealthy();
    /// @notice A fund, a refinance or a supply withdrawal finds too little, `shortfall` base units. The pool raises it
    ///         too, for an entry's leg under a lender's minimum and a quote's payout past what the Router can fund.
    error InsufficientLiquidity(uint256 shortfall);
    /// @notice {reclaim} comes short by `shortfall`, or {withdrawCollateral} names zero or more than the Router
    ///         recognizes (`shortfall` its `assets` then), base units.
    error InsufficientCollateral(uint256 shortfall);
    /// @notice A refinance's bridge needs an allowance of `needed` of the debt token, base units.
    error InsufficientBridge(uint256 needed);
    /// @notice A refinance's atomic move, or its bridge's repay, took other than its amount.
    error ExactDelta();
    /// @notice A move's two ends do not sum to what they held, past the rounding the move allows ({refinanceDebt},
    ///         {migrateSupply}).
    error Conservation();
    /// @notice A refinance or a migration with nothing to move.
    error NothingToMove();
    /// @notice A proportional release at an indebted venue with no repay of the same transaction to read.
    error NoRepaySnapshot();
    /// @notice A leg's receiver is not the caller.
    error BadReceiver();

    // ---- factory / protocol
    /// @notice Lists the pool asset as token 0, with `maxDrawnTokens` 1. Factory-only (`NotFactory`), once
    ///         (`AlreadyRegistered`); the pool must answer the Factory, this Router and `poolAsset` as its own
    ///         (`PoolBindingMismatch` otherwise).
    /// @param pool The pool to register.
    /// @param poolAsset Its pool asset.
    function registerPool(address pool, address poolAsset) external;
    /// @notice Sets the global pause, which stops the legs that add credit risk (a borrow, a funding's borrow phase, a
    ///         supply, the supply cascade, a refinance, a migration) and leaves every leg that unwinds open (a repay,
    ///         a post, a release, a supply withdrawal). The protocol owner (`protocolSafe`) sets and clears it; where
    ///         `protocolSafe` is `FactoryAdmin`, the pauser named there may set it through `FactoryAdmin.pauseRouter`;
    ///         anyone else, `NotProtocolSafe`.
    /// @param paused The pause asked for.
    function setGlobalPaused(bool paused) external;
    /// @notice The protocol owner's address on chain, the Factory's `PROTOCOL_SAFE` at deployment, which no call
    ///         changes ({IMMRouter}).
    function protocolSafe() external view returns (address);

    // ---- pool-scoped token and pair set (msg.sender = pool)
    /// @notice Appends a token: not zero, at most 18 decimals (`InvalidConfig`), not listed before, retired ones
    ///         included (`DuplicateToken`), at most `MAX_TOKENS` in all (`TooManyTokens`).
    /// @param token The token to list.
    /// @return idx Its index in the pool's list.
    function addToken(address token) external returns (uint8 idx);
    /// @notice The supply of the token the pool's venues may hold at once, across every pair that lends it; refused
    ///         while the token is retired (`TokenIsRetired`).
    /// @param idx The token's index (`BadTokenIndex` past the list).
    /// @param supplyCap The cap, in the token's base units; zero: none.
    function setTokenSupplyCap(uint8 idx, uint128 supplyCap) external;
    /// @notice Terminal: retires a token, never the pool asset (`InvalidConfig`) nor one already retired, and only once
    ///         every pair naming it is retired (`TokenInUse` otherwise). A retired token takes no pair and no supply
    ///         cap (`TokenIsRetired`).
    /// @param idx The token's index (`BadTokenIndex` past the list).
    function retireToken(uint8 idx) external;
    /// @notice Appends a credit pair that borrows `debt` against `coll`: two live listed tokens, distinct, a pair not
    ///         added before (retired ones included, whose accounts keep their addresses), `pinLtvWad` above zero,
    ///         `pinLtvWad + safetyGapWad` under one, `oracleBandWad` at most 20 % (zero: no venue oracle is read for
    ///         it). Born with its borrowing off. No venue of the pair lends while its threshold is under the pin plus
    ///         the gap; the gap is written once. Refused `BadTokenIndex`, `TokenIsRetired`, `DuplicatePair`,
    ///         `TooManyPairs`, and `InvalidConfig` past the bounds above.
    /// @param coll The collateral token's index.
    /// @param debt The debt token's index.
    /// @param pinLtvWad The pin, WAD ({setPin}).
    /// @param safetyGapWad The room a borrowing venue's threshold keeps over the pin, WAD.
    /// @param oracleBandWad The venue-oracle band, WAD ({setOracleBand}).
    /// @return idx The pair's index.
    function addPair(uint8 coll, uint8 debt, uint64 pinLtvWad, uint64 safetyGapWad, uint64 oracleBandWad) external returns (uint8 idx);
    /// @notice The pair's debt cap across its venues and its borrow switch; refused once the pair is retired
    ///         (`PairIsRetired`).
    /// @param pair The pair's index (`BadPairIndex` past the list).
    /// @param debtCap The cap, in debt-token base units; zero: none.
    /// @param borrowEnabled The pair's borrow switch.
    function setPairCaps(uint8 pair, uint128 debtCap, bool borrowEnabled) external;
    /// @notice A lower pin always passes, so the pool can follow a lender's cut at once; any other pin plus the pair's
    ///         gap must stay within the pair's `minLltv` (one, where no venue of the pair binds), else `InvalidConfig`.
    /// @param pair The pair's index (`BadPairIndex` past the list).
    /// @param pinLtvWad The new pin, WAD, above zero (`InvalidConfig`).
    function setPin(uint8 pair, uint64 pinLtvWad) external;
    /// @notice The pair's venue-oracle band, at most 20 % (`InvalidConfig` past it): how far a venue's own oracle may
    ///         sit from the pair's price on every band-gated path (admission of a priced or borrowing venue, borrows,
    ///         a priced release, refinance). Zero turns it off: no venue oracle is read and only an unchecked price is
    ///         refused.
    /// @param pair The pair's index (`BadPairIndex` past the list).
    /// @param oracleBandWad The band, WAD.
    function setOracleBand(uint8 pair, uint64 oracleBandWad) external;
    /// @notice Terminal: every venue of the pair must be retired, owe nothing and recognize no supply or collateral
    ///         (`PairNotEmpty` otherwise); its borrow switch goes off for good.
    /// @param pair The pair's index (`BadPairIndex` past the list, `PairIsRetired` for one retired).
    function retirePair(uint8 pair) external;
    /// @notice How many tokens may be owed at once, at least one and at most the token count less one
    ///         (`InvalidConfig`); a borrow that would add an owed token past it is refused. Lowering it unwinds
    ///         nothing.
    /// @param maxDrawnTokens The limit.
    function setMaxDrawnTokens(uint8 maxDrawnTokens) external;

    // ---- pool-scoped venue configuration
    /// @notice Registers a venue of `kind` for `pair` from protocol-specific `venueParams`, in the pair's own (pair,
    ///         kind) account or, where the params open with `FRAME_VENUE`, in a frame's account at the kind.
    /// @dev Which account:
    ///      - Plain params: the pair's own (pair, kind) account, bound to the pair's (collateral, debt) tokens, under
    ///        the kind's deployer of the day. The first venue there deploys it and the others find it at its address
    ///        after its bindings read back, so once the Factory replaces a kind's deployer the pair's next plain venue
    ///        opens its own account under the new one, and its venues at the old one stay there until they move.
    ///      - Params that open with `FRAME_VENUE` (`abi.encode(FRAME_VENUE, frame, params)`): the frame's account at
    ///        the kind, bound to (zero, `frame`) and shared by the venues of every pair the pool puts in the frame,
    ///        found or deployed the same way. It takes `abi.encode(collateral, debt, params)` with the pair's two
    ///        tokens and must name them back for the venue's id (`IFrameAccount.tokensOf`; `VenueMismatch` where it
    ///        names others), which a kind that holds no frame does not answer, so it takes no such venue.
    ///      - No venue joins a frame's account while a venue there is fenced (`VenueIsFenced`): the Router refuses that
    ///        join alone, and the pool fences a frame's venues together.
    ///      - A pair may hold venues at several accounts of one kind (its own, its own under a later deployer,
    ///        frames'), and moves between them by a new venue and `refinanceDebt` or `migrateSupply` (a debt's move
    ///        between them needs room under its lender's collateral cap: `refinanceDebt`). It may borrow at several of
    ///        them at once, as a plan holds what it posts through them within the one room their lender has (`fund`).
    ///
    ///      Slots:
    ///      - A pool holds at most `MAX_VENUES` venues (`TooManyVenues` past it), and the Router bounds nothing else of
    ///        an exit's gas, nor a releasing swap's: a pro-rata exit repays and releases every live position, and a
    ///        releasing swap reads the venues, repays the pool's debt in the token it takes in and walks those that
    ///        hold the token it pays out as collateral, so the gas of each grows with them (`MAX_VENUES`), and the
    ///        curator keeps a pool's positions within what one exit and one releasing swap carry.
    ///      - A retired slot is reused before the record grows: the one that already names this position, else the
    ///        first, so no two slots ever name one position.
    ///
    ///      Admission:
    ///      - A venue whose borrowing is off may come unpriced: it is admitted with no band check and lends nothing
    ///        until a path that borrows checks its band at a checked price, as each does.
    ///      - A venue that can borrow needs a threshold of at least the pair's pin plus its gap (`InvalidConfig`); one
    ///        whose borrowing is off is admitted whatever its threshold, as it lends nothing and binds no pin, and
    ///        turns its borrowing on only once the pin plus the gap is within it (`setVenueFlags`).
    ///      - A kind that declares a capability outside `KNOWN_CAPABILITIES` (every bit the Router admits) is refused
    ///        (`UnknownCapability`), and so is a retired pair (`PairIsRetired`).
    ///      - One kind number is one lender, whose reserve every account of the kind shares or none does
    ///        (`IFinancingAccount` ADMISSION): a venue that declares `CAP_SHARED_LIQUIDITY` otherwise than the pool's
    ///        live venues of its kind, as a later deployer at the number might, is refused (`InvalidConfig`), so a
    ///        plan's posts there stay netted across the accounts (`fund`).
    ///      - A venue whose kind can refuse an action (`CAP_ACTION_GATES`) and whose account answers
    ///        `IActionsOf.actionsOf` as its `actions` here has its gates read through it, one action at a time; any
    ///        other, through `actions`.
    ///      - Refused also `BadPriceVector`, `BadPairIndex`, `KindUnknown` (no deployer at `kind`),
    ///        `AccountCodeMismatch` (an account off its pinned address or bindings), `DuplicateVenue` (a live or fenced
    ///        slot names the position) and `OracleBand` (a borrowing venue or a priced one outside the pair's band).
    /// @param kind The venue kind, which names the deployer at the Factory.
    /// @param pair The pair's index.
    /// @param venueParams The kind's parameters, or `abi.encode(FRAME_VENUE, frame, params)` for a frame's account.
    /// @param borrowEnabled The venue's borrow switch.
    /// @param supplyEnabled The venue's supply switch.
    /// @param usd The pool's checked USD prices ({IMMRouter}); a zero at either of the pair's tokens leaves the venue
    ///        unpriced, which only a venue whose borrowing is off may be.
    /// @return id The venue's slot, its id in every by-id call.
    function addVenue(
        uint8 kind,
        uint8 pair,
        bytes calldata venueParams,
        bool borrowEnabled,
        bool supplyEnabled,
        uint256[] calldata usd
    ) external returns (uint16 id);
    /// @notice Sets a live venue's two switches (`BadVenueId`, `VenueIsRetired` otherwise). Turning a venue's borrowing
    ///         on is refused (`InvalidConfig`) while its threshold is under its pair's pin plus the gap. A fenced venue
    ///         turns neither switch on (`VenueIsFenced`).
    /// @param id The venue's slot.
    /// @param borrowEnabled The venue's borrow switch.
    /// @param supplyEnabled The venue's supply switch.
    function setVenueFlags(uint16 id, bool borrowEnabled, bool supplyEnabled) external;
    /// @notice Fences a live venue (`fenced`): both switches go off and stay off, and it leaves the four priority
    ///         orders, the others keeping their order; or lifts a fence, the venue back in the orders, last,
    ///         its switches still off. Refused (`InvalidConfig`) where the venue is fenced already or not fenced to
    ///         lift, and (`DrawOutsideDrawnSet`) where the lift would leave the unfenced venues holding a token owed
    ///         and backing at once; the drawn-token limit binds new draws alone, as when it is lowered. Only the pool
    ///         that holds the venue sets it, as every pool-scoped call.
    ///         The venues of a frame's account share one position at its lender, so the pool fences, lifts and gives
    ///         them up together: the Router refuses only a venue joining the account while one there is fenced.
    /// @param id The venue's slot.
    /// @param fenced True to fence, false to lift.
    function lockVenue(uint16 id, bool fenced) external;
    /// @notice Sets a venue's caps and rate ceiling, a fenced one's too (`BadVenueId`, `VenueIsRetired` otherwise). A
    ///         cap under what the venue holds refuses new legs and unwinds nothing.
    /// @param id The venue's slot.
    /// @param debtCap The venue's debt cap, in debt-token base units; zero: none.
    /// @param supplyCap The venue's supply cap, in debt-token base units; zero: none.
    /// @param maxBorrowRateWad The highest borrow rate a borrow there may leave, per second, WAD; zero: none.
    function setVenueCaps(uint16 id, uint128 debtCap, uint128 supplyCap, uint64 maxBorrowRateWad) external;
    /// @notice The four cascade orders, each listing every live, unfenced venue once (`BadPriorities` otherwise).
    /// @param borrow_ The order `fund` borrows in; {reclaim} walks it in reverse.
    /// @param supply_ The order {supplyCascade} lends in.
    /// @param withdraw_ The order `fund` and {withdrawCascade} withdraw supply in.
    /// @param repay_ The order {repayCascade} repays in.
    function setPriorities(
        uint16[] calldata borrow_,
        uint16[] calldata supply_,
        uint16[] calldata withdraw_,
        uint16[] calldata repay_
    ) external;
    /// @notice Terminal. The venue must owe nothing on its raw position and recognize no collateral and no supplied
    ///         assets (a withdrawal's share dust, worth none, is none); a position donated to the account, and that
    ///         dust, survive retirement, unrecognized. A live venue leaves the four priority orders, the others keeping
    ///         their order; a fenced one, in none, retires as any other, and its fence ends with it (`VenueFenced`).
    ///         Refused `VenueNotEmpty` otherwise, and `BadVenueId` or `VenueIsRetired` for no such venue.
    /// @param id The venue's slot, which the next admission may reuse.
    function retireVenue(uint16 id) external;
    /// @notice On (the default), `fund` re-checks each borrow slice against its venue just before borrowing, as
    ///         the plan's withdrawals and the slice's collateral post left the venue. Off, the plan's checks of the
    ///         same bounds stand alone and each slice costs less gas: a venue that moves between plan and borrow
    ///         against the plan's projection (a threshold or rate that a post or withdrawal changes) is then caught
    ///         only by the venue's own checks. Cash is never re-checked: the venue's borrow refuses a shortfall itself.
    /// @param on Whether `fund` re-checks.
    function setFundRecheck(bool on) external;
    /// @notice Clamps one live venue's managed trackers down to its actual position, after the pool's emergency path
    ///         moved it outside the Router; a retired venue's are zero already, and `VenueIsRetired` refuses it.
    /// @param id The venue's slot.
    function syncManaged(uint16 id) external;
    /// @notice Raises one live venue's managed collateral by the `units` the pool's emergency path posted directly,
    ///         capped at the actual position; `VenueIsRetired` refuses a retired venue, whose slot a later admission
    ///         may reuse.
    /// @param id The venue's slot.
    /// @param units The collateral units posted, in the account's own units ({IFinancingAccount.positionOf}).
    function recognizeCollateral(uint16 id, uint256 units) external;

    // ---- pool-scoped primitives (msg.sender = pool)
    /// @notice Pulls `assets` of the venue's collateral token and posts it; refused at a fenced venue
    ///         (`VenueIsFenced`). The global pause leaves it open, as a post only reduces risk.
    /// @param id The venue's slot.
    /// @param assets The amount, in the collateral token's base units, above zero (`InvalidConfig`).
    function postCollateral(uint16 id, uint256 assets) external;
    /// @notice Releases up to `assets` of the venue's collateral token to the pool and returns what it released: what
    ///         the venue cannot release now (`IFinancingAccount.collateralReleasable`: collateral it lent out, a
    ///         release it refuses, or under `CAP_PRICED_RELEASE` any release while its oracle cannot be read) stays
    ///         posted and recognized, and waits. A venue that owes nothing reads no price and no repay.
    /// @dev Proportional, it reads no price and releases at most the collateral the same transaction's repay freed, the
    ///      lender's rounding of that repay aside:
    ///      - Where the repay lowered the debt, up to four base units of debt over the exact rest are not held against
    ///        the release (`MMRouterLib.RELEASE_SLACK`).
    ///      - At a venue whose collateral accrues (`CAP_ACCRUING_COLLATERAL`), neither is the rounding a market whose
    ///        rate every holder's redemption moves may pass on from the flow's earlier legs: up to one unit's worth and
    ///        one for each venue of the pool, at most a millionth of one whole collateral token and one, and at most
    ///        four base units and a millionth of the release.
    ///      - The allowance answers no particular leg, and each repay that lowers the debt grants it once.
    ///
    ///      Priced, an indebted venue releases no further than `reclaim` would take it; an indebted fenced venue
    ///      releases proportionally alone (`VenueIsFenced`).
    /// @param id The venue's slot.
    /// @param assets The most to release, in the collateral token's base units: zero, or more than the Router
    ///        recognizes there, reverts `InsufficientCollateral`.
    /// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`); zeros serve a proportional
    ///        release.
    /// @param proportional True for what the same transaction's repay freed (`NoRepaySnapshot` with no repay,
    ///        `Unhealthy` past it), false for a priced release (`OracleBand` off the band, `Unhealthy` past its bound).
    /// @return released What it released, at most `assets`; zero where the venue can release nothing now.
    function withdrawCollateral(uint16 id, uint256 assets, uint256[] calldata usd, bool proportional)
        external
        returns (uint256 released);
    /// @notice Borrows `assets` of the venue's debt token at a live venue with its switch and its pair's on. Refused
    ///         `GlobalPaused`, `VenueDisabled`, `DrawOutsideDrawnSet` (a venue that owes nothing, under the
    ///         no-circularity rule), `OracleBand`, `VenueOverPinned`, `DebtCapExceeded` (the venue's or the pair's),
    ///         `Unhealthy` (past the pin on the collateral posted there) and `RateCeiling`.
    /// @param id The venue's slot.
    /// @param assets The amount, in debt-token base units, above zero (`InvalidConfig`).
    /// @param to The receiver, which must be the caller (`BadReceiver`).
    /// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
    function borrow(uint16 id, uint256 assets, address to, uint256[] calldata usd) external;
    /// @notice Pulls up to `assets` of the venue's debt token and repays, at a fenced or retired venue too; what the
    ///         lender does not take goes straight back to the pool. It records the venue's (debt, collateral) for a
    ///         proportional release in the same transaction.
    /// @param id The venue's slot.
    /// @param assets The most to repay, in debt-token base units, capped at the venue's debt.
    /// @return repaid What the lender took.
    function repay(uint16 id, uint256 assets) external returns (uint256 repaid);
    /// @notice Pulls `assets` of the venue's debt token and lends it at the venue. Refused `GlobalPaused`,
    ///         `VenueDisabled`, and `SupplyCapExceeded` past the venue's cap, what the venue takes now or the token's
    ///         cap.
    /// @param id The venue's slot.
    /// @param assets The amount, in debt-token base units, above zero (`InvalidConfig`).
    /// @return shares The supply shares the account minted.
    function supply(uint16 id, uint256 assets) external returns (uint256 shares);
    /// @notice Withdraws `assets` of the venue's lent debt token to the pool (`to` the caller), every managed share for
    ///         `type(uint256).max`. A leg over what the venue recognizes as the pool's supply is refused
    ///         (`InsufficientLiquidity`), save at a venue whose units accrue (`CAP_ACCRUING_COLLATERAL`) and that
    ///         recognizes some: there a leg over it by the rounding a shared market's rate may pass on from the flow's
    ///         earlier legs still leaves, up to one unit's worth and one for each venue of the pool, at most a
    ///         millionth of one whole token and one, and at most four base units and a millionth of the leg.
    /// @param id The venue's slot.
    /// @param assets The amount, in debt-token base units, above zero (`InsufficientLiquidity`).
    /// @param to The receiver, which must be the caller (`BadReceiver`).
    /// @return withdrawn What the venue paid; zero for `type(uint256).max` with no managed share.
    function withdrawSupplied(uint16 id, uint256 assets, address to) external returns (uint256 withdrawn);
    /// @notice Accrues interest at each live, unfenced venue of the caller's own pool but those in `skipVenues` (bit i:
    ///         venue i) that do not lend token `kept`, so the reads that follow in the block take the accrued state: a
    ///         swap passes its idle venues and the token it pays, whose venues alone it reads a rate at; zero accrues
    ///         them all. Any caller, its own venues only (none unless a registered pool): accrual is permissionless and
    ///         idempotent at the venue. Best effort per venue: an account whose accrual reverts is skipped.
    /// @param skipVenues The venues to pass over, bit i for venue i.
    /// @param kept A token whose venues accrue whatever `skipVenues` says.
    function accrueExcept(uint64 skipVenues, uint8 kept) external;

    // ---- pool-scoped cascades (each passes fenced venues)
    /// @notice Pays `assets` of the pair's debt token to `to`: first by withdrawing that token's supply at any venue
    ///         lending it (withdraw order), then by borrowing at the pair's venues (borrow order), posting up to
    ///         `collateralIn` of the pair's collateral token: at each venue what its pin needs, and where its
    ///         collateral accrues one unit's assets and one more, which the venue's rounding may keep. It never borrows
    ///         more than `assets`.
    /// @dev The borrow phase runs only while the pair can draw (its switch, the global pause, the no-circularity rule)
    ///      and within the pair's debt cap.
    ///
    ///      A venue whose kind holds a minimum position (`CAP_HELD_REPAY`) takes no slice that leaves its debt under
    ///      that minimum (`IHeldRepay.minimumDebt`), or over it by less than the lenders' rounding
    ///      (`MMRouterLib.RELEASE_SLACK`) where it owes already: the plan passes it over, as it does one whose minimum
    ///      cannot be read (a read that reverts, answers short or runs past `MMRouterLib.MINIMUM_READ_GAS`), and `fund`
    ///      reverts `InsufficientLiquidity` by what no venue takes.
    ///
    ///      Each post stays within its venue's post room:
    ///      - Where the pair's venues at a kind that shares one reserve per token (`CAP_SHARED_LIQUIDITY`) sit at
    ///        several of its accounts (its own, its own under a later deployer, frames'), each account reports that
    ///        lender's room for its own venues alone, and a slice whose post passes what the plan's posts through the
    ///        others left of it is sized again within it, so the plan's posts there fit the lender's room together, as
    ///        at one account, whose report parts it among the account's venues.
    ///      - A report nets what its own account holds for the venue's next post, which that post mints with its own,
    ///        and no other report does, so where collateral accrues the plan counts each post through another account
    ///        with one unit's assets more, the most that account can hold for it: the posts fit the lender's room at
    ///        its very edge too.
    ///      - They can come short of it, never past it: by that unit for each such post, and where an account parts the
    ///        room among `k` of its venues there, by up to `k - 1` times the plan's posts through the others, as each
    ///        part is held to its share less those posts whole; a later plan posts what is left.
    ///      - One kind number is one lender (`IFinancingAccount` ADMISSION): a lender listed under two numbers would
    ///        have its posts counted apart and its room taken twice.
    /// @param pair The pair's index (`BadPairIndex`).
    /// @param assets What to pay, in debt-token base units.
    /// @param to The receiver, which must be the caller (`BadReceiver`).
    /// @param collateralIn The most to post, in collateral-token base units, pulled from the pool's allowance.
    /// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`). An unchecked pair runs the
    ///        withdrawal phase alone.
    function fund(uint8 pair, uint256 assets, address to, uint256 collateralIn, uint256[] calldata usd) external;
    /// @notice Repays up to `assets` of `token` at every unfenced venue that lends it to the pool, in repay order; each
    ///         repay records its venue's (debt, collateral) for a proportional release in the same transaction. It
    ///         pulls at most `assets` in all: what a venue does not take of its pull comes straight back to the pool,
    ///         and the cascade does not offer it to the next venue. A venue whose gate refuses a repay is passed over.
    /// @param token The debt token's index (`BadTokenIndex`).
    /// @param assets The most to pull, in the token's base units.
    /// @return repaid What the lenders took.
    function repayCascade(uint8 token, uint256 assets) external returns (uint256 repaid);
    /// @notice Supplies up to `assets` of `token` at venues that lend it with supply on, in supply order. A venue whose
    ///         kind holds a minimum position takes no supply that leaves its position under that minimum or over it by
    ///         less than the lenders' rounding (`MMRouterLib.RELEASE_SLACK`: the lender mints a supply's shares
    ///         rounded down), nor any while its minimum cannot be read: the cascade passes it over, and what no venue
    ///         takes stays with the pool, all of it while the global pause holds.
    /// @param token The token's index (`BadTokenIndex`; the global pause returns zero before it reads the index).
    /// @param assets The most to lend, in the token's base units.
    /// @return supplied What the venues took.
    function supplyCascade(uint8 token, uint256 assets) external returns (uint256 supplied);
    /// @notice Withdraws up to `assets` of supplied `token` from the unfenced venues that lend it, in withdraw order,
    ///         to `to`, which must be the pool, as for `withdrawSupplied` (`BadReceiver` otherwise). A venue whose
    ///         withdrawal reverts at the lender is passed over.
    /// @param token The token's index (`BadTokenIndex`).
    /// @param assets The most to withdraw, in the token's base units.
    /// @param to The receiver.
    /// @return withdrawn What the venues paid, which may fall short of `assets`.
    function withdrawCascade(uint8 token, uint256 assets, address to) external returns (uint256 withdrawn);
    /// @notice Releases collateral `token` across the unfenced venues whose collateral it is, in reverse borrow order.
    ///         An indebted venue releases down to its pair's pin, or, once its threshold has fallen under the pin plus
    ///         the gap, down to that threshold less the gap; one whose pair is unchecked, or whose oracle is off the
    ///         pair's band, releases nothing. A venue that refuses its release is passed over, so the rest still pay:
    ///         only a shortfall over all of them reverts (`InsufficientCollateral`, by the shortfall). A release that
    ///         fails with under an eighth of the gas it began with left may have run out of gas: the walk reverts
    ///         `VenueReads.ReadStarved` where it began with under three million, and ends where it began with more, as
    ///         the lender burnt it. A starved read, the venue's oracle read for its band among them, reverts
    ///         `ReadStarved` as well.
    /// @param token The collateral token's index.
    /// @param assets What to release, in the token's base units.
    /// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
    /// @return got What it released: `assets`.
    function reclaim(uint8 token, uint256 assets, uint256[] calldata usd) external returns (uint256 got);
    /// @notice As {reclaim}, with no revert on a shortfall: a starved read or release still reverts
    ///         `VenueReads.ReadStarved`.
    /// @param token The collateral token's index.
    /// @param assets The most to release, in the token's base units.
    /// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
    /// @return got What it released, which may fall short of `assets`.
    function reclaimBestEffort(uint8 token, uint256 assets, uint256[] calldata usd) external returns (uint256 got);
    /// @notice Moves debt between two venues of one pair: atomically inside one account that supports it, else bridged
    ///         through the pool's granted debt token (`InsufficientBridge` when the allowance is short). The collateral
    ///         moves in proportion to the debt, all that the source recognizes on a full move. Refused at a fenced
    ///         venue at either end (`VenueIsFenced`).
    /// @dev Where either end holds a minimum position (`CAP_HELD_REPAY`), a move that would leave it under that minimum
    ///      reverts, as no plan passes it over: the destination's lender refuses the borrow, and the source takes a
    ///      partial repay short of the move (`ExactDelta`). The curator's or keeper's move is refused, and its caller
    ///      sizes it again.
    ///
    ///      Between two accounts of one lender whose collateral market is capped (a pair's own and a frame's, or its
    ///      own under two deployers), the bridge releases at the source before it posts at the destination, so the
    ///      lender's market ends holding what it held, but the post needs room under the cap for the moved collateral
    ///      and, where collateral accrues, for what the destination account holds for its next post: while the lender's
    ///      cap sits under what its market holds (a cap its governance lowered), such a move reverts at the lender, and
    ///      the pair stays at its account until the cap leaves room.
    ///
    ///      Refused also:
    ///      - `GlobalPaused`.
    ///      - `VenueMismatch`: one venue, or two pairs.
    ///      - `VenueDisabled`: the destination's switch.
    ///      - `NothingToMove`.
    ///      - `InsufficientLiquidity`: the source cannot release the collateral, or the destination has not the cash.
    ///      - `OracleBand`, `VenueOverPinned`, `DebtCapExceeded` (the destination's) and `RateCeiling`.
    ///      - `Unhealthy`: either end past the pin.
    ///      - `Conservation`: the two venues' summed debt moved by more than `MMRouterLib.REFINANCE_SLACK`.
    /// @param src The source venue's slot.
    /// @param dst The destination venue's slot, live.
    /// @param assets The debt to move, in debt-token base units; at or past the source's debt it moves all of it.
    /// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
    function refinanceDebt(uint16 src, uint16 dst, uint256 assets, uint256[] calldata usd) external;
    /// @notice Moves supply between two venues that lend the same token; refused at a fenced venue at either end
    ///         (`VenueIsFenced`).
    /// @dev The destination must recognize what the source paid it, less the rounding of its supply (`Conservation`
    ///      otherwise):
    ///      - That rounding is up to four base units, or up to one of its shares' worth and one where that is more, but
    ///        past four never more than a millionth of the amount moved nor a millionth of one whole token.
    ///      - A refused read of that share refuses the move.
    ///      - The bound is the destination's rounding alone: what the source charges to pay the move (a redemption fee)
    ///        is outside it.
    ///
    ///      A move that would leave a destination holding a minimum position (`CAP_HELD_REPAY`) under that minimum
    ///      reverts at its lender, which refuses the supply: the curator's or keeper's move is refused, not passed
    ///      over, and its caller sizes it again. The source's withdrawal meets no minimum, as such a lender checks none
    ///      on a withdrawal.
    ///
    ///      Refused also `GlobalPaused`, `VenueMismatch` (one venue, or two tokens), `NothingToMove`, `VenueDisabled`
    ///      and `SupplyCapExceeded` (the destination's switch and room).
    /// @param src The source venue's slot.
    /// @param dst The destination venue's slot, live.
    /// @param assets What to move, in the token's base units, within what the source recognizes.
    function migrateSupply(uint16 src, uint16 dst, uint256 assets) external;

    // ---- views (any caller; `pool` explicit)
    /// @notice The tokens the pool lists, retired ones included; zero for an unregistered pool.
    function tokenCount(address pool) external view returns (uint256);
    /// @notice The pool's token `idx`, retired or not (`BadTokenIndex` past the list).
    /// @return The token's record ({TokenView}), its cap in the token's base units.
    function token(address pool, uint8 idx) external view returns (TokenView memory);
    /// @notice The pool's pairs, retired ones included; zero for an unregistered pool.
    function pairCount(address pool) external view returns (uint256);
    /// @notice The pool's pair `idx`, retired or not (`BadPairIndex` past the list).
    /// @return The pair's record ({PairView}): its pin, gap and band in WAD, its debt cap in debt-token base units.
    function pair(address pool, uint8 idx) external view returns (PairView memory);
    /// @notice The pair's first own (pair, kind) account, which its first plain venue of the kind deployed: zero until
    ///         then, and for a pair not added. Its later plain venues land at its own account under the kind's deployer
    ///         of the day, another once the Factory replaces that deployer, and a frame venue at its frame's account:
    ///         each venue's is `venue(pool, id).account`.
    /// @return The account's address, or zero.
    function accountOf(address pool, uint8 pair, uint8 kind) external view returns (address);
    /// @notice The pool the Router deployed or joined `account` for; zero for any other address.
    function poolOf(address account) external view returns (address);
    /// @notice The slots of the pool's venue record, retired ones included; zero for an unregistered pool.
    function venueCount(address pool) external view returns (uint256);
    /// @notice The pool's venue `id`, retired or not (`BadVenueId` past the record).
    /// @return The venue's record ({VenueView}): its threshold read live, WAD; its caps in debt-token base units.
    function venue(address pool, uint16 id) external view returns (VenueView memory);
    /// @notice The pool's four cascade orders ({setPriorities}).
    /// @param pool The pool.
    /// @return borrow_ The borrow order.
    /// @return supply_ The supply order.
    /// @return withdraw_ The withdraw order.
    /// @return repay_ The repay order.
    function priorities(address pool)
        external
        view
        returns (uint16[] memory borrow_, uint16[] memory supply_, uint16[] memory withdraw_, uint16[] memory repay_);
    /// @notice The most tokens the pool's owed set may hold ({setMaxDrawnTokens}); registration sets one.
    function maxDrawnTokens(address pool) external view returns (uint8);
    /// @notice The owed set (bit t: some unfenced venue lends token t to the pool) and the backing set (bit t: token t
    ///         is the collateral of an unfenced venue that lends to the pool).
    /// @param pool The pool.
    /// @return owed The owed set, a mask over the pool's token indices.
    /// @return backing The backing set, a mask over the pool's token indices.
    function drawn(address pool) external view returns (uint16 owed, uint16 backing);
    /// @notice Venue `id`'s position as its account reports it, and the parts the Router recognizes as the pool's: a
    ///         gift to the account sits in the raw reads alone. Reads a fenced or retired venue too (`BadVenueId` past
    ///         the record).
    /// @param pool The pool.
    /// @param id The venue's slot.
    /// @return collateral The collateral the account holds, in collateral-token base units.
    /// @return recognizedCollateral The part the Router's tracker recognizes, in the same units.
    /// @return supplied The account's supply at its worth, in debt-token base units.
    /// @return recognizedSupplied The part the Router's tracker recognizes, in the same units.
    /// @return debt The venue's debt at the accrued state, in debt-token base units.
    function venuePosition(address pool, uint16 id)
        external
        view
        returns (uint256 collateral, uint256 recognizedCollateral, uint256 supplied, uint256 recognizedSupplied, uint256 debt);
    /// @notice The pool's positions per token in one walk of its venues, skipping retired and fenced ones and those in
    ///         `skipVenues` (bit i: venue i): each venue's recognized collateral credited to its collateral token, its
    ///         recognized supply and its debt to its debt token, each array `tokenCount` long. A fenced venue is read
    ///         by id alone (`venuePosition`). `emptyVenues` marks the venues read that owe nothing, carry no managed
    ///         collateral and hold no recognized supply: only the pool's own calls through the Router move those, so a
    ///         gift posted or supplied on the account's behalf leaves a venue empty, a withdrawal's share dust (worth
    ///         nothing) does too, and a venue a lender seized collateral from is not empty until its tracker is synced
    ///         down or it retires.
    /// @param pool The pool.
    /// @param skipVenues The venues to pass over, bit i for venue i.
    /// @return posted Recognized collateral per token, in its base units.
    /// @return supplied Recognized supply per token, in its base units.
    /// @return owed Debt per token, in its base units.
    /// @return emptyVenues The venues read that hold nothing of the pool's, bit i for venue i.
    function book(address pool, uint64 skipVenues)
        external
        view
        returns (uint256[] memory posted, uint256[] memory supplied, uint256[] memory owed, uint64 emptyVenues);
    /// @notice The lowest threshold, read live, of the pair's venues that can borrow or still owe: the pair pin's and
    ///         its LTV's bound. A zero threshold binds like any other; `NO_VENUE_LLTV` where none binds, and for a pair
    ///         not added.
    function minLltv(address pool, uint8 pair) external view returns (uint256);
    /// @notice What `fund` would find for `pair`, up to `cap` (`type(uint256).max`: all of it), with `collateralIn`
    ///         of its collateral token to post. `assumeRepaid` (bit t) reads the drawn-set test alone (which tokens are
    ///         owed and which back a debt) as if every venue lending token t had been repaid in full, so a plan that
    ///         repays one side first can pass that test for a draw on the other; the debt caps and each slice's pin
    ///         read the debt as it stands. The plan stops at `cap`, so a small cap reads less, and as it passes over a
    ///         slice that leaves a venue holding a minimum position under it (`fund`), a smaller cap can read nothing
    ///         at such a venue where a larger one reads all of it.
    /// @param pool The pool; an unregistered one reads zero.
    /// @param pair The pair's index (`BadPairIndex`).
    /// @param cap The most to read, in debt-token base units.
    /// @param collateralIn The most to post, in collateral-token base units.
    /// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
    /// @param assumeRepaid The tokens read as repaid in the drawn-set test, bit t for token t.
    /// @return What the plan pays, at most `cap`, in debt-token base units.
    function fundingCeiling(
        address pool,
        uint8 pair,
        uint256 cap,
        uint256 collateralIn,
        uint256[] calldata usd,
        uint16 assumeRepaid
    ) external view returns (uint256);
    /// @notice The collateral `fund(pair, assets, …, collateralIn, usd)` posts now: the sum of its plan's posts at the
    ///         pair's venues, at most `collateralIn`, with the Router's own rounding and placement. A borrow that first
    ///         withdraws its collateral token's supply withdraws what this reads past the custody it holds, then funds
    ///         at the custody the withdrawal leaves: `fund` plans anew after the withdrawal, which can free room under
    ///         the posting market's supply cap and lower its collateral reads, and `collateralIn` bounds what it posts.
    /// @param pool The pool; an unregistered one reads zero.
    /// @param pair The pair's index (`BadPairIndex`).
    /// @param assets What `fund` would pay, in debt-token base units.
    /// @param collateralIn The most to post, in collateral-token base units.
    /// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
    /// @return posted The plan's posts, summed, in collateral-token base units.
    function fundingCollateral(address pool, uint8 pair, uint256 assets, uint256 collateralIn, uint256[] calldata usd)
        external
        view
        returns (uint256 posted);
    /// @notice The most venue `id` would lend now once `collateralIn` is posted, by every gate a borrow passes
    ///         (switches, the drawn set, band, pin, free cash, both debt caps, rate ceiling); zero when one is shut,
    ///         and where a venue holding a minimum position would be left under it by all of that room (`fund`). There
    ///         a positive room does not mean every smaller borrow is taken: one that leaves the position under the
    ///         minimum is refused.
    /// @param pool The pool.
    /// @param id The venue's slot (`BadVenueId` past the record).
    /// @param collateralIn The collateral to read as posted, in collateral-token base units.
    /// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
    /// @return The room, in debt-token base units.
    function borrowRoom(address pool, uint16 id, uint256 collateralIn, uint256[] calldata usd)
        external
        view
        returns (uint256);
    /// @notice The most venue `id` would take as supply now (switches, the venue's and the token's supply caps); zero
    ///         when one is shut.
    /// @param pool The pool.
    /// @param id The venue's slot (`BadVenueId` past the record).
    /// @return The room, in debt-token base units.
    function supplyRoom(address pool, uint16 id) external view returns (uint256);
    /// @notice What `reclaim` of `token` would release now. A venue whose release would revert at the lender still
    ///         counts, so this reads a ceiling on what the walk pays.
    /// @param pool The pool.
    /// @param token The collateral token's index.
    /// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
    /// @return The release, in the token's base units.
    function reclaimable(address pool, uint8 token, uint256[] calldata usd) external view returns (uint256);
    /// @notice Venue `id`'s health against its threshold, at the caller's prices, which are not checked against the
    ///         venue's oracle: the collateral's worth at the threshold over the debt, carried through the pair's pin
    ///         and rounded down. No flow reads it; the pool's flows read `venueHealthy`.
    /// @param pool The pool.
    /// @param id The venue's slot (`BadVenueId` past the record).
    /// @param usd USD prices, `tokenCount` long (`BadPriceVector`).
    /// @return healthWad The health, WAD, so 1e18 sits at the threshold; `type(uint256).max` with no debt, and zero at
    ///         an unchecked pair.
    function venueHealth(address pool, uint16 id, uint256[] calldata usd) external view returns (uint256 healthWad);
    /// @notice The venue's `IFinancingAccount.healthy`, at the market's own price, which the pool's flows read. Not
    ///         `venueHealth`, which prices the position at the caller's prices.
    function venueHealthy(address pool, uint16 id) external view returns (bool);
    /// @notice The actions venue `id` allows now, as its account reports them (`IFinancingAccount.actions`):
    ///         `venueCapacity`'s `actions` alone, with none of the liquidity and caps that view builds.
    function venueActions(address pool, uint16 id) external view returns (uint8);
    /// @notice What venue `id` can move now, as its account reports it: each leg's liquidity, caps and rate limits,
    ///         and the actions the venue allows.
    function venueCapacity(address pool, uint16 id) external view returns (IFinancingAccount.Capacity memory);
}

src/interfaces/utils/integrations/IVenus.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited

pragma solidity ^0.8.26;

/// @notice A Compound-style market token as `CTokenAccount` uses it: Venus's VBep20 on BNB Chain. Its mutators return
///         an error code (0: done) where a failure does not revert. `getCash` is the market's tracked cash, which a
///         transfer to it does not move.
interface IVToken {
    function underlying() external view returns (address);
    function comptroller() external view returns (address);
    function interestRateModel() external view returns (address);
    function accrualBlockNumber() external view returns (uint256);
    function borrowIndex() external view returns (uint256);
    function getCash() external view returns (uint256);
    function totalBorrows() external view returns (uint256);
    function totalReserves() external view returns (uint256);
    function totalSupply() external view returns (uint256);
    function reserveFactorMantissa() external view returns (uint256);
    function exchangeRateStored() external view returns (uint256);
    function balanceOf(address owner) external view returns (uint256);
    function borrowBalanceStored(address account) external view returns (uint256);
    /// @notice (error, vToken balance, stored borrow balance, stored exchange rate); a nonzero error zeroes the rest.
    function getAccountSnapshot(address account) external view returns (uint256, uint256, uint256, uint256);

    function accrueInterest() external returns (uint256);
    function exchangeRateCurrent() external returns (uint256);
    function borrowBalanceCurrent(address account) external returns (uint256);
    function mintBehalf(address receiver, uint256 mintAmount) external returns (uint256);
    function redeem(uint256 redeemTokens) external returns (uint256);
    function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
    function borrow(uint256 borrowAmount) external returns (uint256);
    function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
}

/// @notice The Venus Core Pool comptroller (a diamond) as `CTokenAccount` reads and drives it. `action` is Venus's
///         `Action` (0 mint, 1 redeem, 2 borrow, 3 repay, 7 enter market, 8 exit market); `weighting` 0 reads the
///         collateral factor, 1 the liquidation threshold. `markets` and `poolMarkets` answer (listed, collateral
///         factor, isVenus, liquidation threshold, liquidation incentive, pool id, borrow allowed).
interface IVenusComptroller {
    /// @notice Enters `vToken` for `onBehalf`, the caller itself or one it approved as a delegate.
    function enterMarketBehalf(address onBehalf, address vToken) external returns (uint256);
    function exitMarket(address vToken) external returns (uint256);
    /// @notice Pays `holder` the XVS it accrued in `vTokens`, as supplier and borrower.
    function claimVenus(address holder, address[] calldata vTokens) external;
    function getXVSAddress() external view returns (address);
    function enterPool(uint96 poolId) external;

    function protocolPaused() external view returns (bool);
    function actionPaused(address market, uint8 action) external view returns (bool);
    function supplyCaps(address vToken) external view returns (uint256);
    function borrowCaps(address vToken) external view returns (uint256);
    function treasuryPercent() external view returns (uint256);
    function checkMembership(address account, address vToken) external view returns (bool);
    /// @notice The markets `account` has entered, each of which a liquidity check Venus makes for it prices.
    function getAssetsIn(address account) external view returns (address[] memory);
    function pools(uint96 poolId) external view returns (string memory label, bool isActive, bool allowCorePoolFallback);
    function markets(address vToken) external view returns (bool, uint256, bool, uint256, uint256, uint96, bool);
    function poolMarkets(uint96 poolId, address vToken)
        external
        view
        returns (bool, uint256, bool, uint256, uint256, uint96, bool);
    function getEffectiveLtvFactor(address account, address vToken, uint8 weighting) external view returns (uint256);
    function isForcedLiquidationEnabled(address vToken) external view returns (bool);
    function isForcedLiquidationEnabledForUser(address account, address vToken) external view returns (bool);
    function deviationBoundedOracle() external view returns (address);
    /// @notice (error, liquidity, shortfall) at the collateral factor and the bounded prices, `redeemTokens` of
    ///         `vTokenModify` redeemed and `borrowAmount` of it borrowed.
    function getHypotheticalAccountLiquidity(
        address account,
        address vTokenModify,
        uint256 redeemTokens,
        uint256 borrowAmount
    ) external view returns (uint256, uint256, uint256);
}

/// @notice Venus's deviation-bounded oracle: per market, the price its collateral-factor checks value collateral at
///         and the price they value debt at, each in USD per base unit scaled by 1e36 (a whole token's USD price
///         times 10^(36 - decimals)). Reverts while the resilient oracle behind it cannot price.
interface IVenusBoundedOracle {
    function getBoundedPricesView(address vToken) external view returns (uint256 collateralPrice, uint256 debtPrice);
}

/// @notice A Venus rate model: the borrow rate per block, and its blocks per year under one of two names.
interface IVenusRateModel {
    function getBorrowRate(uint256 cash, uint256 borrows, uint256 reserves) external view returns (uint256);
    function blocksPerYear() external view returns (uint256);
    function BLOCKS_PER_YEAR() external view returns (int256);
}

src/libraries/Constants.sol

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

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

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

// ---------------------------------------------------------------- delays
/// @dev The least delay a pool may take for its operator's own changes: a pool's `governanceDelaySec` at birth, a
///      launched pool's delay, its authority's delay, and the least a listing's change reads as the pool's own.
uint32 constant POOL_DELAY_FLOOR_SEC = 1 hours;
/// @dev What a protocol-level loosening waits: the front's timelock, a feed's replacement, a protocol fee's rise, a
///      band ceiling's raise, the beacon delay a cheap lane asks for, a credit door's config, and a listing's change
///      where its pool's own delay cannot be read.
uint32 constant PROTOCOL_DELAY_SEC = 10 days;
/// @dev How long a due change stays applicable outside the pool, whose own window is its delay or a day, whichever
///      is longer: past it the change has lapsed.
uint32 constant CHANGE_WINDOW_SEC = 7 days;
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {
    "src/core/mm/MMRouterLib.sol": {
      "MMRouterLib": "0xA4749766934833DfBeaF4Fc0d79c150A1Dd2B4E5"
    },
    "src/core/flamm/FLAMMLane.sol": {
      "FLAMMLane": "0x0988077AB06F1efd8cFa3f08FC60CAf3e6d22e98"
    },
    "src/core/flamm/FLAMMRoute.sol": {
      "FLAMMRoute": "0x312ee92ecd113F925dD513d450b062C8740fDaA9"
    },
    "src/periphery/FLAMMMaxima.sol": {
      "FLAMMMaxima": "0x4A997343D91c981BF63274fc222AA96D32d6259c"
    },
    "src/core/flamm/FLAMMLawLib.sol": {
      "FLAMMLawLib": "0x5D473B15E032756Cd81fc66B8F1e9BE2f427cc62"
    },
    "src/core/flamm/FLAMMOpsLib.sol": {
      "FLAMMOpsLib": "0x0BFe60fB1f5223F1A2b7B02Ef18f5C33fb043753"
    },
    "src/core/mm/AaveV3ReadsLib.sol": {
      "AaveV3ReadsLib": "0xD53F6170226A74D453e84414Ffc2FFcE5ded5983"
    },
    "src/core/flamm/FLAMMFlowLib.sol": {
      "FLAMMFlowLib": "0x2577D707D41209489b2EF53101a4f6baDd4E3473"
    },
    "src/core/flamm/FLAMMGateLib.sol": {
      "FLAMMGateLib": "0xF0BE115A2D6F27274F2e9EE50B89Ed42db2B9555"
    },
    "src/core/flamm/FLAMMKeptLib.sol": {
      "FLAMMKeptLib": "0x7a11899232dd9F17c28bF062Ec2ee2267158517b"
    },
    "src/core/mm/CTokenMarketLib.sol": {
      "CTokenMarketLib": "0x18c53F2aCAbcDEEdb575A136f49fa4C43EB2071c"
    },
    "src/core/flamm/FLAMMAdmitLib.sol": {
      "FLAMMAdmitLib": "0xA6dBD8cD5Cd10F8a5857cbeD54a28405ffbDcBCb"
    },
    "src/core/flamm/FLAMMBlindLib.sol": {
      "FLAMMBlindLib": "0x0b8d436F1a7AE25C5d16955ed4CDa781E42e7E5C"
    },
    "src/core/flamm/FLAMMClaimLib.sol": {
      "FLAMMClaimLib": "0x02b4354a56630ab165A880B1198a603E62731cCE"
    },
    "src/core/flamm/FLAMMFenceLib.sol": {
      "FLAMMFenceLib": "0xA16ddA83f47a42F875f141b6954595D584a201e8"
    },
    "src/core/flamm/FLAMMFloatLib.sol": {
      "FLAMMFloatLib": "0x539EfC2b17cF0fdF254AAaB925b3A7c360A79737"
    },
    "src/core/flamm/FLAMMQuoteLib.sol": {
      "FLAMMQuoteLib": "0xa4D34f4882a529574840881e755BCFae2bd5ce2e"
    },
    "src/core/flamm/FLAMMTopUpLib.sol": {
      "FLAMMTopUpLib": "0x7C55a535Ce298b1e5e6d00F645088F777ad233DF"
    },
    "src/core/mm/CTokenRewardsLib.sol": {
      "CTokenRewardsLib": "0xcda63d7eCCF838F2732Bff676706BDE5abA4DcF7"
    },
    "src/core/mm/MMRouterAdminLib.sol": {
      "MMRouterAdminLib": "0x8423744b3F304ED0B43043d7ad4E7d8A247aDc96"
    },
    "src/core/flamm/FLAMMPolicyLib.sol": {
      "FLAMMPolicyLib": "0xa6B495B2BdcDcf4F327844d9aaA0eD4C550c67F9"
    },
    "src/core/flamm/FLAMMSettleLib.sol": {
      "FLAMMSettleLib": "0xB4890a27205505BDAA05717B6c3aB38b2dd3C7Cb"
    },
    "src/core/flamm/FLAMMSharedLib.sol": {
      "FLAMMSharedLib": "0xFaAEd38962aEb6c282Ac36E0cdE9313AbA2511ba"
    },
    "src/periphery/FLAMMExitMaxima.sol": {
      "FLAMMExitMaxima": "0x480f51866554e92649c9d3502bA31AA4234e0a81"
    },
    "src/hooks/everlong/LeverageLib.sol": {
      "LeverageLib": "0x1B1D1C42d26c169dB59D8681d0FD4C9a2840Ad11"
    },
    "src/core/flamm/FLAMMMaintainLib.sol": {
      "FLAMMMaintainLib": "0x94998f13fc5d5D2271c90b835c6a805dad409cC2"
    },
    "src/core/flamm/FLAMMPairQuoteLib.sol": {
      "FLAMMPairQuoteLib": "0x077523D1427aE408105fe8592F907ECDa0D94cbE"
    },
    "src/hooks/everlong/EverlongOpsLib.sol": {
      "EverlongOpsLib": "0xAbe4447C954E3C7a405f8E75116BF9f5787426F7"
    }
  },
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
    "solady/=lib/solady/src/",
    "forge-std/=lib/forge-std/src/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.