Skip to content
Verified contractExactUNLICENSED

MMRouterLib

Address0xa4749766934833dfbeaf4fc0d79c150a1dd2b4e5
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,572
Creation transaction
0x872b5fa0a5…489c08757f
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/MMRouterLib.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 {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "src/interfaces/core/mm/IFinancingAccount.sol";
import "src/interfaces/core/mm/IMMRouter.sol";
import {IHeldRepay} from "src/interfaces/core/mm/IHeldRepay.sol";
import {VenueReads} from "src/core/mm/VenueReads.sol";
import {SafeTransferLib} from "src/libraries/SafeTransferLib.sol";

/// @notice The Router's storage shapes, shared risk arithmetic, and the multi-venue bodies (allocator, cascades,
///         refinance, aggregate views) that run by delegatecall against the Router. The cold bodies that admit and
///         retire tokens, pairs and venues, and the supply migration, are `MMRouterAdminLib`'s.
library MMRouterLib {
    /// @dev Conservation slack of a two-venue move, in base units of the moved token: the rounding a refinance's
    ///      repay and borrow together, or a migration's supply, may leave between the two venues. A lender rounds each
    ///      leg by under one of its debt or share units; Morpho Blue's units are worth under a base unit, and Aave's
    ///      scaled debt rounds a leg by up to its borrow index, so four covers both legs below an index of 2.0. A
    ///      refinance at a kind that rounds coarser is refused (`Conservation`). A migration may always lose four; into
    ///      a kind that rounds coarser it may lose up to one of its shares' worth and one, but past four never more
    ///      than a millionth of what it moves nor a millionth of one whole token (`MMRouterAdminLib.migrateSupply`).
    uint256 internal constant REFINANCE_SLACK = 4;
    /// @dev Past {REFINANCE_SLACK}, a supply migration loses at most this part of what it moves, and of one whole token
    ///      of the moved token: one millionth. The allowance for a shared market's rounding (a proportional release's,
    ///      a supply leg's) is held to the same part of one whole token and of the leg ({_roundingSlack}).
    uint256 internal constant MIGRATION_LOSS_DIVISOR = 1e6;
    /// @dev Debt a proportional release does not hold against it once the same transaction's repay has lowered the
    ///      debt. A lender burns a partial repay's debt units rounded down and reads the debt left rounded up, so the
    ///      venue may owe up to one of its units over the exact rest, and a pro-rata exit, which repays its debt leg
    ///      and releases its collateral leg, would be refused by units it cannot control. Four covers a lender whose
    ///      one debt unit is worth under four base units: Morpho Blue's repay by assets leaves at most one, and Aave's
    ///      floored burn and rounded-up read leave up to its borrow index rounded up, so it covers indices under 4.0.
    ///      It comes off the debt after the repay, not off the snapshot's, so it covers an exit of any size (a slack on
    ///      the snapshot's debt shrinks with the collateral the release leaves). The collateral that stays carries at
    ///      most this much debt over its exact share, the lender's own health check still binds, and a repay that
    ///      lowered nothing earns none. Where collateral accrues, that collateral may also fall short of its exact
    ///      share by a shared market's rounding ({_roundingSlack}), on the same terms.
    uint256 internal constant RELEASE_SLACK = 4;
    /// @dev The gas a venue's read of its minimum position may take (`IHeldRepay.minimumDebt`): twice Moolah's, whose
    ///      one guarded read of its core takes at most 500,000 (`MoolahAccount`).
    uint256 internal constant MINIMUM_READ_GAS = 1_000_000;
    /// @dev Gas well past what one venue's release takes at any listed kind, whose dearest is Venus's: a release of
    ///      {reclaim} begun with this much that fails with under an eighth of it left was burnt by the lender, never
    ///      starved by the caller's limit.
    uint256 internal constant RELEASE_GAS = 3_000_000;
    /// @dev One venue as the Router acts on it: the raw position and the part the Router recognizes as the pool's.
    ///      `collateral` and `recognizedCollateral` are base units of the pair's collateral token, `supplied`,
    ///      `recognizedSupplied` and `debt` of its debt token. The two recognized fields are what the managed trackers
    ///      hold of `collateral` and `supplied`; `debt` is the venue's whole debt, which no tracker bounds.
    struct Read {
        uint256 collateral;
        uint256 recognizedCollateral;
        uint256 supplied;
        uint256 recognizedSupplied;
        uint256 debt;
    }

    /// @dev A listed token: its address, its decimals (read once, at listing), its retirement and whether a supply cap
    ///      is set in one slot; the supply the pool's venues may hold of it, across every pair that lends it, in its
    ///      base units, in the next, which a flow reads only while one is set.
    struct Token {
        address token;
        uint8 decimals;
        bool retired;
        bool supplyCapped; // `supplyCap != 0`, written with it
        uint128 supplyCap;
    }

    /// @dev A credit pair, which borrows its debt token against its collateral token: both tokens (indices in the
    ///      pool's list) and their decimals, its switch, its retirement, whether a debt cap is set and its risk in the
    ///      one slot a priced path reads: the pin (the LTV a borrow is sized to), the safety gap (how far above the pin
    ///      a venue's threshold must sit) and the band (how far a venue's oracle may sit from the pair's price), all
    ///      WAD. The pair's debt cap across its venues, in base units of the debt token, sits in the next slot, which a
    ///      path reads only while one is set. `accounts` keeps the pair's first own account at each kind, bound to its
    ///      two tokens (`MMRouterAdminLib.deployAccount`); its venues may sit at others, each naming its own.
    struct Pair {
        uint8 coll;
        uint8 debt;
        uint8 collDecimals;
        uint8 debtDecimals;
        bool borrowEnabled;
        bool retired;
        bool debtCapped; // `debtCap != 0`, written with it
        uint64 pinLtvWad;
        uint64 safetyGapWad;
        uint64 oracleBandWad;
        uint128 debtCap;
        mapping(uint8 kind => address) accounts;
    }

    /// @dev Five slots, grouped by what a swap reads together: the account with every flag a cascade tests and the
    ///      venue's pair and two tokens, copied from the pair at admission and never changed; the venue id at its
    ///      account; a borrow slice's limits (the venue's debt cap in debt-token base units and its rate ceiling, per
    ///      second, WAD, each zero for none, and its threshold, WAD); the two managed trackers; the supply cap, in
    ///      debt-token base units, zero for none. A sell touches the first four, a repay and its release the first,
    ///      second and fourth. The trackers are uint128 and raised only through `SafeCast`: Morpho Blue bounds
    ///      collateral and supply shares to uint128, and a leg of any other kind that would carry a tracker past
    ///      2^128 - 1 reverts; a burn only lowers one. The status byte holds the `VENUE_RETIRED` and `VENUE_FENCED`
    ///      bits, so a walk of the venues that passes either tests one byte. A fenced venue has both switches off, and
    ///      they stay off while it stays fenced (`setVenueFlags`), so a path gated on a switch passes it over with no
    ///      test of its own; it is in no priority order, so no cascade or plan acts on it, while the caps ({capRoom})
    ///      and the binding threshold ({minLltv}) still count it.
    struct Venue {
        IFinancingAccount account;
        uint8 kind;
        uint8 pair;
        uint8 coll; // the pair's collateral token: what the venue holds of the pool's as collateral
        uint8 debt; // the pair's debt token: what the venue lends the pool and takes as supply
        uint16 capabilities; // the account's, read once at admission: `KNOWN_CAPABILITIES` alone
        bool borrowEnabled;
        bool supplyEnabled;
        uint8 status; // `VENUE_RETIRED`, `VENUE_FENCED`; zero: live, in every priority order
        bool actionsOf; // the account answered `IActionsOf.actionsOf` as its `actions` at admission
        bytes32 id;
        uint128 debtCap;
        uint64 maxBorrowRateWad;
        uint64 lltvWad; // at admission; read live instead for a kind whose threshold can fall
        uint128 managedCollateralUnits; // units the Router posted (assets for a kind that never accrues)
        uint128 managedSupplyShares;
        uint128 supplyCap;
    }

    /// @dev The pool asset, the drawn-set limit, the recheck switch and both counts in one slot, so no access to a
    ///      token or a pair reads a length. `venues` is indexed by venue id, and a retired slot may be reused; each of
    ///      the four priority orders lists every live, unfenced venue once.
    struct PoolRecord {
        address poolAsset;
        uint8 maxDrawnTokens;
        bool fundRecheckOff; // `fund` borrows on its plan's checks alone
        uint8 tokenCount;
        uint8 pairCount;
        mapping(uint8 => Token) tokens;
        mapping(uint8 => Pair) pairs;
        Venue[] venues;
        uint16[] borrowOrder;
        uint16[] supplyOrder;
        uint16[] withdrawOrder;
        uint16[] repayOrder;
    }

    /// @dev A funding plan, its three lists indexed by venue id: `withdrawTake` the supply to withdraw, `borrowSlice`
    ///      the debt to borrow, both in base units of the pair's debt token, and `post` the collateral to post for that
    ///      slice, in base units of its collateral token. `remaining`: what no leg covers, in debt-token base units.
    ///      `price`: the pair's price the borrow phase sized its slices at ({maxDebtAtPin}), zero where the plan
    ///      borrows nothing.
    struct Plan {
        uint256[] withdrawTake;
        uint256[] borrowSlice;
        uint256[] post;
        uint256 remaining;
        uint256 price;
    }

    // ------------------------------------------------------------------ delegatecalled bodies
    /// @dev Releases what the venue lets go of now (`releasable`) and returns it; the rest stays posted, recognized and
    ///      waiting, and a release of nothing reads no snapshot and no price.
    function withdrawCollateral(
        PoolRecord storage p,
        uint16 id,
        uint256 assets,
        uint256[] calldata usd,
        bool proportional
    ) public returns (uint256) {
        checkPrices(p, usd);
        Venue storage v = venueAt(p, id);
        // One read of the position: its collateral and debt are `collateralOf` and `debtOf` in the same state, which
        // the release check alone (a view) does not move.
        (uint256 coll,,, uint256 debt) = v.account.position(v.id);
        if (assets == 0 || assets > recognizedFrom(v, coll)) revert IMMRouter.InsufficientCollateral(assets);
        uint256 rel = releasable(v);
        if (rel < assets) assets = rel;
        if (assets == 0) return 0;
        if (debt != 0) {
            if (proportional) {
                (uint256 debtBefore, uint256 collBefore) = repaySnapshot(msg.sender, id);
                if (collBefore == 0) revert IMMRouter.NoRepaySnapshot();
                // The lender's rounding of a repay that lowered the debt is not held against the release, nor, where
                // the exact proof fails, the rounding a shared market's rate passed on ({_requireSharedRounding}).
                uint256 held = debt < debtBefore ? debt - Math.min(debt, RELEASE_SLACK) : debt;
                if (held * collBefore > debtBefore * (coll - assets)) _requireSharedRounding(p, v, id, assets);
            } else {
                // A fenced venue's debt is unwound by id: what a repay frees, never what a price allows.
                if (v.status & VENUE_FENCED != 0) revert IMMRouter.VenueIsFenced();
                Pair storage pr = p.pairs[v.pair];
                uint256 price = priceOf(pr, usd);
                if (!bandOk(pr, v, price)) revert IMMRouter.OracleBand();
                if (debt > maxDebtAt(releaseLtv(pr, v), coll - assets, price)) revert IMMRouter.Unhealthy();
            }
        }
        burnUnits(v, v.account.withdrawCollateral(v.id, assets, msg.sender));
        emit IMMRouter.CollateralWithdrawn(msg.sender, id, assets);
        return assets;
    }

    /// @dev Executes `buildPlan`. Unless the pool turned it off, each slice is re-checked against its venue as the
    ///      plan's withdrawals and the slice's own post left it, just before it borrows.
    function fund(PoolRecord storage p, bool paused, uint8 pairIdx, uint256 assets, uint256 collateralIn, uint256[] calldata usd)
        public
    {
        Plan memory plan = buildPlan(p, paused, pairIdx, assets, collateralIn, usd, 0);
        if (plan.remaining != 0) revert IMMRouter.InsufficientLiquidity(plan.remaining);
        uint16[] storage wo = p.withdrawOrder;
        for (uint256 i; i < wo.length; ++i) {
            uint256 take = plan.withdrawTake[wo[i]];
            if (take == 0) continue;
            withdrawTracked(p.venues[wo[i]], take, 0, msg.sender);
            emit IMMRouter.SuppliedWithdrawn(msg.sender, wo[i], take, msg.sender);
        }
        if (plan.price == 0) return; // no slice: the plan borrows nothing
        Pair storage pr = p.pairs[pairIdx];
        uint16[] storage bo = p.borrowOrder;
        for (uint256 i; i < bo.length; ++i) {
            uint16 id = bo[i];
            uint256 slice = plan.borrowSlice[id];
            if (slice == 0) continue;
            Venue storage v = p.venues[id];
            uint256 post = plan.post[id];
            if (post != 0) {
                pull(tokenOf(p, pr.coll), address(v.account), post);
                mintUnits(v, v.account.supplyCollateral(v.id, post));
                emit IMMRouter.CollateralPosted(msg.sender, id, post);
            }
            if (!p.fundRecheckOff) {
                (uint256 coll,,, uint256 debt) = v.account.position(v.id);
                requireSliceFits(pr, v, debt, coll, slice, plan.price);
            }
            v.account.borrow(v.id, slice, msg.sender);
            emit IMMRouter.Borrowed(msg.sender, id, slice, msg.sender);
        }
    }

    /// @dev A venue that takes less than its pay (a minimum position, a held full exit) returns the rest to the pool
    ///      ({repayInto}), and the cascade does not spend it again: it pulls at most `assets` from the pool's
    ///      allowance in all, so a short repay never leaves a later pull without one.
    function repayCascade(PoolRecord storage p, uint8 token, uint256 assets) public returns (uint256 repaid) {
        address t = tokenAt(p, token).token;
        uint16[] storage ro = p.repayOrder;
        uint256 remaining = assets;
        for (uint256 i; i < ro.length && remaining != 0; ++i) {
            Venue storage v = p.venues[ro[i]];
            if (v.debt != token) continue;
            (uint256 coll,,, uint256 debt) = v.account.position(v.id);
            // A venue that owes nothing is passed before its gate is read.
            if (debt == 0 || !canAct(v, CAN_REPAY)) continue;
            uint256 pay = remaining < debt ? remaining : debt;
            _snapshot(ro[i], debt, coll);
            uint256 got = repayInto(v, t, pay);
            repaid += got;
            remaining -= pay;
            emit IMMRouter.Repaid(msg.sender, ro[i], got);
        }
    }

    /// @dev Walks the venues lending `token` with supply on, in supply order, within each one's room and the token's
    ///      cap, and returns what they took; nothing while `paused`. A venue that holds a minimum position takes no
    ///      leg that leaves it under that minimum ({_underMinimum}); what no venue takes stays with the pool.
    function supplyCascade(PoolRecord storage p, bool paused, uint8 token, uint256 assets) public returns (uint256 supplied) {
        if (paused) return 0;
        Token storage t = tokenAt(p, token);
        uint256 remaining = assets;
        uint256 tokenRoom = capRoom(p, t.supplyCapped ? t.supplyCap : 0, token, false);
        uint16[] storage so = p.supplyOrder;
        for (uint256 i; i < so.length && remaining != 0 && tokenRoom != 0; ++i) {
            Venue storage v = p.venues[so[i]];
            if (v.debt != token || !v.supplyEnabled) continue;
            uint256 room = supplyRoom(v);
            if (room > tokenRoom) room = tokenRoom;
            uint256 take = remaining < room ? remaining : room;
            if (take == 0) continue;
            if (uint256(v.capabilities) & CAP_HELD_REPAY != 0 && _underMinimum(v, read(v).supplied, take, true)) continue;
            pull(t.token, address(v.account), take);
            mintShares(v, v.account.supply(v.id, take));
            supplied += take;
            remaining -= take;
            tokenRoom -= take;
            emit IMMRouter.Supplied(msg.sender, so[i], take);
        }
    }

    /// @dev Each venue lending `token` gives what it recognizes as the pool's supply and has the cash to pay, in
    ///      withdraw order; one whose withdrawal reverts at the lender (a pause, a freeze, a cash shortfall) is passed
    ///      over, so the rest still pay. One whose supply tracker is zero recognizes none and is not read.
    function withdrawCascade(PoolRecord storage p, uint8 token, uint256 assets, address to)
        public
        returns (uint256 withdrawn)
    {
        tokenAt(p, token);
        uint16[] storage wo = p.withdrawOrder;
        uint256 remaining = assets;
        for (uint256 i; i < wo.length && remaining != 0; ++i) {
            uint16 id = wo[i];
            Venue storage v = p.venues[id];
            if (v.debt != token || v.managedSupplyShares == 0) continue;
            uint256 avail = read(v).recognizedSupplied;
            if (avail == 0) continue;
            uint256 cash = v.account.supplyWithdrawable(v.id);
            if (cash < avail) avail = cash;
            uint256 take = remaining < avail ? remaining : avail;
            if (take == 0) continue;
            try v.account.withdraw(v.id, take, 0, to) returns (uint256, uint256 burned) {
                v.managedSupplyShares = _less(v.managedSupplyShares, burned);
            } catch {
                continue;
            }
            withdrawn += take;
            remaining -= take;
            emit IMMRouter.SuppliedWithdrawn(msg.sender, id, take, to);
        }
    }

    /// @dev Walks the venues whose collateral is `token`, in reverse borrow order. A venue whose release reverts at the
    ///      lender (a check at its own price, a pause) is passed over, so a payout out of collateral still draws on
    ///      the others; one whose collateral tracker is zero recognizes none and is not read. A release that fails with
    ///      under an eighth of the gas it began with left may have run out of gas some calls down, which a refusal
    ///      with gas to spare cannot: begun under {RELEASE_GAS}, that is the caller's limit, and the walk reverts
    ///      `VenueReads.ReadStarved` rather than let the limit pick what stays posted; begun with more, the lender
    ///      burnt it, and the walk ends there with what it released ({_burnt}). A band read that fails so reverts as
    ///      well ({freeCollateral}); every other read of the walk reverts by itself when starved, at its kind's guard
    ///      (`IFinancingAccount` ADMISSION) or out of gas in the walk.
    function reclaim(PoolRecord storage p, uint8 token, uint256 assets, uint256[] calldata usd) public returns (uint256 got) {
        checkPrices(p, usd);
        uint16[] storage bo = p.borrowOrder;
        uint256 remaining = assets;
        for (uint256 i = bo.length; i > 0 && remaining != 0; --i) {
            uint16 id = bo[i - 1];
            Venue storage v = p.venues[id];
            if (v.coll != token || v.managedCollateralUnits == 0) continue;
            uint256 free = freeCollateral(p, v, usd, true);
            uint256 take = remaining < free ? remaining : free;
            if (take == 0) continue;
            uint256 g = gasleft();
            try v.account.withdrawCollateral(v.id, take, msg.sender) returns (uint256 units) {
                burnUnits(v, units);
            } catch {
                if (_burnt(g)) break;
                continue;
            }
            got += take;
            remaining -= take;
            emit IMMRouter.CollateralWithdrawn(msg.sender, id, take);
        }
    }

    /// @dev Whether a failed release of {reclaim} begun with `g` gas left under an eighth of it, which the lender burnt
    ///      where `g` is at least {RELEASE_GAS}; under it, the caller's limit may have starved the release, and it
    ///      reverts `VenueReads.ReadStarved` instead.
    function _burnt(uint256 g) private view returns (bool) {
        if (gasleft() >= g / 8) return false;
        if (g < RELEASE_GAS) revert VenueReads.ReadStarved();
        return true;
    }

    /// @dev Within one pair: the destination's pair already owes, as the source does, so the move starts no debt and
    ///      changes neither the owed set nor the backing set.
    function refinanceDebt(PoolRecord storage p, bool paused, uint16 src, uint16 dst, uint256 assets, uint256[] calldata usd) public {
        if (paused) revert IMMRouter.GlobalPaused();
        checkPrices(p, usd);
        if (src == dst) revert IMMRouter.VenueMismatch();
        Venue storage vs = venueAt(p, src);
        Venue storage vd = live(p, dst);
        if ((vs.status | vd.status) & VENUE_FENCED != 0) revert IMMRouter.VenueIsFenced();
        if (vs.pair != vd.pair) revert IMMRouter.VenueMismatch();
        if (!vd.borrowEnabled) revert IMMRouter.VenueDisabled();
        uint256 debtSrc = vs.account.debtOf(vs.id);
        if (debtSrc == 0) revert IMMRouter.NothingToMove();
        bool full = assets >= debtSrc;
        uint256 move = full ? debtSrc : assets;
        if (move == 0) revert IMMRouter.NothingToMove();
        uint256 collSrc = vs.account.collateralOf(vs.id);
        uint256 recognized = recognizedFrom(vs, collSrc);
        uint256 collMove = full ? recognized : Math.mulDiv(recognized, move, debtSrc);
        if (collMove > releasable(vs)) revert IMMRouter.InsufficientLiquidity(collMove);
        uint256 debtDst = vd.account.debtOf(vd.id);
        Pair storage pr = p.pairs[vs.pair];
        uint256 price = priceOf(pr, usd);
        if (!bandOk(pr, vd, price)) revert IMMRouter.OracleBand();
        if (overPinned(pr, vd)) revert IMMRouter.VenueOverPinned();
        if (!full && !bandOk(pr, vs, price)) revert IMMRouter.OracleBand();
        if (vd.account.borrowable(vd.id) < move) revert IMMRouter.InsufficientLiquidity(move);
        if (vd.debtCap != 0 && debtDst + move > vd.debtCap) revert IMMRouter.DebtCapExceeded();
        requireRate(vd, move);
        if (debtDst + move > maxDebtAtPin(pr, vd.account.collateralOf(vd.id) + collMove, price)) revert IMMRouter.Unhealthy();
        if (!full && debtSrc - move > maxDebtAtPin(pr, collSrc - collMove, price)) revert IMMRouter.Unhealthy();
        // The atomic primitive counts one unit per asset moved, true only where collateral never accrues; the bridge
        // reports what each leg burned and minted.
        uint256 unitsOut = collMove;
        uint256 unitsIn = collMove;
        if (
            address(vs.account) == address(vd.account)
                && uint256(vs.capabilities) & (CAP_ATOMIC_REFINANCE | CAP_ACCRUING_COLLATERAL) == CAP_ATOMIC_REFINANCE
        ) {
            if (vs.account.refinance(vs.id, vd.id, full ? 0 : move, collMove) != move) revert IMMRouter.ExactDelta();
        } else {
            (unitsOut, unitsIn) = _bridge(p, vs, vd, move, collMove);
        }
        burnUnits(vs, unitsOut);
        mintUnits(vd, unitsIn);
        uint256 totalAfter = vs.account.debtOf(vs.id) + vd.account.debtOf(vd.id);
        uint256 totalBefore = debtSrc + debtDst;
        if (totalAfter + REFINANCE_SLACK < totalBefore || totalAfter > totalBefore + REFINANCE_SLACK) revert IMMRouter.Conservation();
        emit IMMRouter.DebtRefinanced(msg.sender, src, dst, move, collMove);
    }

    /// @dev Between two accounts of one pair: the pool's granted debt token repays `src`, the collateral crosses
    ///      account to account, and `dst` borrows the same amount back to the pool.
    function _bridge(PoolRecord storage p, Venue storage vs, Venue storage vd, uint256 move, uint256 collMove)
        private
        returns (uint256 unitsOut, uint256 unitsIn)
    {
        address token = tokenOf(p, vs.debt);
        if (IERC20(token).allowance(msg.sender, address(this)) < move) revert IMMRouter.InsufficientBridge(move);
        if (repayInto(vs, token, move) != move) revert IMMRouter.ExactDelta();
        if (collMove != 0) {
            unitsOut = vs.account.withdrawCollateral(vs.id, collMove, address(vd.account));
            unitsIn = vd.account.supplyCollateral(vd.id, collMove);
        }
        vd.account.borrow(vd.id, move, msg.sender);
    }

    /// @dev Shared by quote and execution: withdrawals of the pair's debt token at every unfenced venue lending it, in
    ///      withdraw order, then borrow slices at the pair's venues, in borrow order, each bounded by cash, caps, rate
    ///      ceiling, oracle band and what `collateralIn` can post at the pair's pin within the venue's post room
    ///      (`Capacity.collateralPostable`).
    ///      - The borrow phase runs only while the pair may draw: its switch, the global pause and the drawn set
    ///        ({drawable}, read with `assumeRepaid`).
    ///      - A venue's cash and rate are taken net of its own withdrawal and of the legs at venues whose kind shares
    ///        its cash (`CAP_SHARED_LIQUIDITY`); such a venue's own are net of every earlier leg of the plan, and it
    ///        gives no withdrawal where those leave its cash under one unit's payout (`supplySharesToAssets(id, 1)`),
    ///        which a slice there redeems whole: the kind's own read reports none then, but not past legs it does not
    ///        see.
    ///      - Such a venue's post room is net, too, of the plan's posts through the pair's other accounts at its kind
    ///        and of what those accounts may hold for them ({_postRoom}), which its account's report does not see: a
    ///        slice whose post passes it is sized again within it, so one plan never posts past the room its lender
    ///        has, wherever the pair's venues there sit; at one account the kind's own report parts that room among the
    ///        account's venues, each part net of those posts whole, so a plan may leave a part's room to a later plan.
    ///      - Another pair's venue whose supply tracker is zero is not read: it recognizes no supply, and only the
    ///        pair's own venues' reads serve the borrow phase.
    ///      - An unchecked pair borrows nothing, as no slice passes its band at a zero price, so its plan ends there.
    function buildPlan(
        PoolRecord storage p,
        bool paused,
        uint8 pairIdx,
        uint256 assets,
        uint256 collateralIn,
        uint256[] calldata usd,
        uint16 assumeRepaid
    ) public view returns (Plan memory plan) {
        checkPrices(p, usd);
        Pair storage pr = pairAt(p, pairIdx);
        uint8 lent = pr.debt;
        uint256 n = p.venues.length;
        plan.withdrawTake = new uint256[](n);
        plan.borrowSlice = new uint256[](n);
        plan.post = new uint256[](n);
        plan.remaining = assets;
        Read[] memory rds = new Read[](n);
        uint256 have; // bit `id`: `rds[id]` holds the venue's read (a view: the state cannot move in between)
        uint256 wShared; // withdrawn, then borrowed, at venues that share their cash
        uint256 bShared;
        uint16[] storage wo = p.withdrawOrder;
        for (uint256 i; i < wo.length && plan.remaining != 0; ++i) {
            Venue storage v = p.venues[wo[i]];
            if (v.debt != lent || (v.pair != pairIdx && v.managedSupplyShares == 0)) continue;
            rds[wo[i]] = read(v);
            have |= uint256(1) << wo[i];
            uint256 avail = rds[wo[i]].recognizedSupplied;
            if (avail == 0) continue;
            bool sh = sharesCash(v);
            uint256 used = sh ? assets - plan.remaining : wShared;
            uint256 cash = v.account.supplyWithdrawable(v.id);
            cash = cash > used ? cash - used : 0;
            if (cash < avail) avail = cash;
            uint256 take = plan.remaining < avail ? plan.remaining : avail;
            if (sh) {
                // the earlier legs, netted past the kind's own read, can leave the reserve's cash under one unit's
                // payout, which a slice there redeems whole: such a remainder gives nothing
                if (take != 0 && cash < v.account.supplySharesToAssets(v.id, 1)) take = 0;
                wShared += take;
            }
            plan.withdrawTake[wo[i]] = take;
            plan.remaining -= take;
        }
        if (plan.remaining == 0 || paused) return plan;
        uint256 price = priceOf(pr, usd);
        if (price == 0 || !pr.borrowEnabled || !drawableRead(p, pr, pairIdx, lent, assumeRepaid, rds, have)) {
            return plan;
        }
        uint256 wAll = assets - plan.remaining;
        uint256 debtRoom = capRoom(p, pr.debtCapped ? pr.debtCap : 0, pairIdx, true);
        uint256 collAvail = collateralIn;
        uint16[] storage bo = p.borrowOrder;
        for (uint256 i; i < bo.length && plan.remaining != 0 && debtRoom != 0; ++i) {
            Venue storage v = p.venues[bo[i]];
            if (v.pair != pairIdx || !v.borrowEnabled) continue;
            uint256 want = plan.remaining < debtRoom ? plan.remaining : debtRoom;
            bool sh = sharesCash(v);
            (uint256 slice, uint256 post) = _slice(
                pr,
                v,
                rds[bo[i]],
                (have >> bo[i]) & 1 != 0,
                want,
                collAvail,
                sh ? wAll : plan.withdrawTake[bo[i]] + wShared,
                sh ? assets - plan.remaining - wAll : bShared,
                price,
                true
            );
            if (slice == 0) continue;
            plan.borrowSlice[bo[i]] = slice;
            plan.post[bo[i]] = post;
            plan.remaining -= slice;
            collAvail -= post;
            debtRoom -= slice;
            if (sh) {
                // A post past what the plan's posts through the pair's other accounts at the lender, and what those
                // accounts may hold for them, left of its room ({_postRoom}) is sized again within it, on the same
                // reads; none precedes the plan's first slice at a venue that shares its cash (`bShared` zero), so
                // that one reads no room.
                uint16 id = bo[i];
                uint256 q = plan.post[id];
                uint256 room = q == 0 || bShared == 0 ? q : _postRoom(p, plan.post, p.venues[id]);
                if (q > room) {
                    (uint256 s, uint256 r) = _slice(
                        pr,
                        p.venues[id],
                        rds[id],
                        (have >> id) & 1 != 0,
                        (plan.remaining < debtRoom ? plan.remaining : debtRoom) + slice,
                        room,
                        wAll,
                        assets - plan.remaining - slice - wAll,
                        price,
                        true
                    );
                    (plan.borrowSlice[id], plan.post[id], plan.remaining) = (s, r, plan.remaining + slice - s);
                    (collAvail, debtRoom, slice) = (collAvail + q - r, debtRoom + slice - s, s);
                    if (s == 0) continue;
                }
                bShared += slice;
            }
            plan.price = price;
        }
    }

    /// @dev The post room venue `v` keeps in a plan that posts `posts`: what its account reports, less the plan's posts
    ///      through the pair's other accounts at its kind, which fill the same lender's room (one reserve per token,
    ///      `IFinancingAccount` ADMISSION) while each account parts it among its own venues alone, each with one unit's
    ///      assets where collateral accrues: the most that account may hold for the post (one too small to mint a
    ///      unit), which the post mints with its own and only that account's report nets. No bound where no such post
    ///      precedes it. A kind that caps no post reports no bound either (`Capacity.collateralPostable`).
    function _postRoom(PoolRecord storage p, uint256[] memory posts, Venue storage v) private view returns (uint256) {
        uint256 taken;
        for (uint256 j; j < posts.length; ++j) {
            if (posts[j] == 0) continue;
            Venue storage w = p.venues[j];
            if (w.kind == v.kind && address(w.account) != address(v.account)) {
                taken += posts[j];
                if (uint256(w.capabilities) & CAP_ACCRUING_COLLATERAL != 0) {
                    taken += w.account.collateralUnitsToAssets(w.id, 1);
                }
            }
        }
        if (taken == 0) return type(uint256).max;
        uint256 room = v.account.collateralPostable(v.id);
        return room > taken ? room - taken : 0;
    }

    /// @dev {drawable} for `buildPlan`, whose withdraw phase read the unfenced venues lending `lent`, the pair's debt
    ///      token (`have`, `rds`): where one of the pair's own venues owes and `assumeRepaid` reads none of `lent`
    ///      repaid, the pair may draw, with no scan of every venue. That venue puts `lent` in the owed set and the
    ///      pair's collateral token in the backing set, so, no token being both, the collateral token is owed nowhere
    ///      and `lent` backs no debt, and `lent`, owed already, adds no owed token: {drawable}'s answer.
    function drawableRead(
        PoolRecord storage p,
        Pair storage pr,
        uint8 pairIdx,
        uint8 lent,
        uint16 assumeRepaid,
        Read[] memory rds,
        uint256 have
    ) internal view returns (bool) {
        if (p.pairCount == 1) return true;
        if ((assumeRepaid >> lent) & 1 == 0) {
            for (uint256 i; have >> i != 0; ++i) {
                if ((have >> i) & 1 != 0 && rds[i].debt != 0 && p.venues[i].pair == pairIdx) return true;
            }
        }
        return drawable(p, pr, assumeRepaid);
    }

    /// @dev `buildPlan`'s `remaining` alone, so `MMRouter.fundingCeiling` takes one word back across the call, not the
    ///      plan's three venue-length arrays. Its selector sorts last in this library's dispatcher, so no other entry
    ///      pays one more compare for it.
    function fundingRest(
        PoolRecord storage p,
        bool paused,
        uint8 pairIdx,
        uint256 assets,
        uint256 collateralIn,
        uint256[] calldata usd,
        uint16 assumeRepaid
    ) public view returns (uint256) {
        return buildPlan(p, paused, pairIdx, assets, collateralIn, usd, assumeRepaid).remaining;
    }

    /// @dev The sum of {freeCollateral} over the venues {reclaim} walks: live, unfenced, with `token` as collateral and
    ///      a collateral tracker. A venue whose release would revert at the lender still counts here.
    function reclaimable(PoolRecord storage p, uint8 token, uint256[] calldata usd) public view returns (uint256 total) {
        checkPrices(p, usd);
        uint256 n = p.venues.length;
        for (uint256 i; i < n; ++i) {
            Venue storage v = p.venues[i];
            if (v.status == 0 && v.coll == token && v.managedCollateralUnits != 0) {
                total += freeCollateral(p, v, usd, false);
            }
        }
    }

    /// @dev The venue's position, from one read of it, with the parts the Router recognizes ({Read}): collateral
    ///      through {recognizedFrom}, supply as the tracked shares the venue still holds, at their worth there.
    function read(Venue storage v) internal view returns (Read memory r) {
        uint256 shares;
        (r.collateral, shares, r.supplied, r.debt) = v.account.position(v.id);
        r.recognizedCollateral = recognizedFrom(v, r.collateral);
        uint256 managed = shares < v.managedSupplyShares ? shares : v.managedSupplyShares;
        r.recognizedSupplied = managed == shares ? r.supplied : v.account.supplySharesToAssets(v.id, managed);
    }

    /// @dev `cashUsed` and `borrowUsed`: what the plan's earlier legs withdraw from and borrow out of the venue's cash,
    ///      which execute before its borrow. Where collateral accrues (`CAP_ACCRUING_COLLATERAL`) the venue credits a
    ///      post in its own units, rounded down, and checks its own factor on what it credits: a plan's post (`pad`,
    ///      which `fund` makes) carries one unit's assets and one past what the pin needs, so the venue reads at least
    ///      that need (`IFinancingAccount` ADMISSION), and the slice is sized on the collateral left to post past
    ///      them. A post of the need alone could be credited a unit short, and a draw whose need is a unit or two
    ///      (dust) refused by the venue though the plan allowed it. `MMRouterAdminLib.borrowRoom` pads none: the pool
    ///      posts its own leg there (`postCollateral`) and `borrow` allows the rounding.
    function _slice(
        Pair storage pr,
        Venue storage v,
        Read memory rd,
        bool readDone,
        uint256 want,
        uint256 collAvail,
        uint256 cashUsed,
        uint256 borrowUsed,
        uint256 price,
        bool pad
    ) internal view returns (uint256 slice, uint256 post) {
        if (!bandOk(pr, v, price) || overPinned(pr, v)) return (0, 0);
        uint256 caps = uint256(v.capabilities);
        uint256 cash;
        if (caps & (CAP_PROTOCOL_CAPS | CAP_ACTION_GATES) == 0) {
            cash = v.account.borrowable(v.id);
        } else {
            // One read of what the venue can move now (`IFinancingAccount.capacity`), whose fields are its single
            // views in the same state but at the one exception `IFinancingAccount`'s ADMISSION names. A post is at
            // most what the venue still takes, nothing while it refuses posts, its cap's room otherwise, whatever
            // room a later kind reports beside a refusal.
            IFinancingAccount.Capacity memory k = v.account.capacity(v.id);
            uint256 postable = k.collateralPostable;
            if (caps & CAP_ACTION_GATES != 0 && k.actions & CAN_POST_COLLATERAL == 0) postable = 0;
            if (postable < collAvail) collAvail = postable;
            cash = k.borrowable;
        }
        uint256 extra;
        if (pad && caps & CAP_ACCRUING_COLLATERAL != 0) (extra, collAvail) = _postSlack(pr, v, collAvail);
        if (!readDone) rd = read(v);
        uint256 debt = rd.debt;
        uint256 coll = rd.collateral;
        uint256 used = cashUsed + borrowUsed;
        cash = cash > used ? cash - used : 0;
        slice = want < cash ? want : cash;
        if (v.debtCap != 0) {
            uint256 room = v.debtCap > debt ? v.debtCap - debt : 0;
            if (room < slice) slice = room;
        }
        uint256 maxDebt = maxDebtAtPin(pr, coll + collAvail, price);
        uint256 byColl = maxDebt > debt ? maxDebt - debt : 0;
        if (byColl < slice) slice = byColl;
        if (slice == 0) return (0, 0);
        uint256 ceiling = v.maxBorrowRateWad;
        if (ceiling != 0) {
            // Priced after the plan's earlier legs (`cashUsed`, `borrowUsed`), which execute before the borrow.
            (bool ok, uint256 rate) = v.account.borrowRateAfter(v.id, borrowUsed + slice, cashUsed);
            if (!ok) return (0, 0);
            if (rate > ceiling) {
                // Over the ceiling, trimmed to the largest part under it, not dropped; the account's search errs low,
                // and no answer of it widens the slice past the bounds already taken.
                uint256 trimmed = v.account.ceilingBorrowSlice(v.id, borrowUsed, cashUsed, slice, ceiling);
                if (trimmed < slice) slice = trimmed;
            }
            if (slice == 0) return (0, 0);
        }
        // At most `collAvail` with `extra`: `slice` is within `byColl`, and the pin's two roundings never need more
        // than the collateral that sized it.
        if (caps & CAP_HELD_REPAY != 0 && _underMinimum(v, debt, slice, false)) return (0, 0);
        uint256 need = requiredCollateral(pr.pinLtvWad, debt + slice, price);
        post = need > coll ? need - coll + extra : 0;
    }

    /// @dev Whether `add` more at a venue whose kind holds a minimum position (`CAP_HELD_REPAY`) leaves its position
    ///      `held` under the minimum it values now (`IHeldRepay.minimumDebt`), or over it by less than {RELEASE_SLACK}
    ///      where the lender's check can read the position under what the Router counts: a `supply`, whose shares the
    ///      lender mints rounded down, so that even a first supply of exactly the minimum reads a unit under it, and a
    ///      borrow where the venue owes, whose debt the Router reads rounded up. A first borrow mints its shares
    ///      rounded up and reads at least what it borrowed, so it needs the minimum alone. The lender refuses a borrow
    ///      or a supply that leaves the position under its minimum, so the plan's slice and the cascade's take pass
    ///      the venue over, as they do within the slack, where a lender may still take them. The read is a static call
    ///      of at most {MINIMUM_READ_GAS} (`VenueReads.peekData`): one that reverts, runs out of that gas or answers
    ///      short passes the venue over, as no leg there can be sized, and one its caller left short of that gas
    ///      reverts `VenueReads.ReadStarved`, so no caller makes a venue look unreadable by starving it. False while
    ///      the venue cannot value its minimum (`ok` false), where it reports nothing borrowable or suppliable.
    function _underMinimum(Venue storage v, uint256 held, uint256 add, bool supply) private view returns (bool) {
        bytes memory data = abi.encodeCall(IHeldRepay.minimumDebt, (v.id));
        if (!VenueReads.peekData(MINIMUM_READ_GAS, address(v.account), data, 2)) return true;
        if (VenueReads.word(0) == 0) return false;
        uint256 floor = VenueReads.word(1);
        uint256 after_ = held + add;
        return after_ < floor || ((held != 0 || supply) && after_ - floor < RELEASE_SLACK);
    }

    /// @dev {_slice}'s post slack at venue `v`, whose collateral accrues: one unit's assets, at most a millionth of one
    ///      whole collateral token as {_roundingSlack} holds the release side, so a unit a donation raised cannot widen
    ///      it, and one; at most the `collAvail` the pool can post (none while it can post none), and what that leaves
    ///      to post past it.
    function _postSlack(Pair storage pr, Venue storage v, uint256 collAvail)
        private
        view
        returns (uint256 s, uint256 left)
    {
        if (collAvail == 0) return (0, 0);
        s = v.account.collateralUnitsToAssets(v.id, 1);
        // A listed token has at most 18 decimals, so `most` is at most 1e12: no overflow.
        unchecked {
            uint256 most = 10 ** uint256(pr.collDecimals) / MIGRATION_LOSS_DIVISOR;
            s = (s < most ? s : most) + 1;
        }
        if (s > collAvail) s = collAvail;
        left = collAvail - s;
    }

    /// @dev The lesser of the venue's and its debt token's supply rooms; zero while supply is off.
    function supplyRoomOf(PoolRecord storage p, bool paused, uint16 id) public view returns (uint256 room) {
        Venue storage v = venueAt(p, id);
        if (v.status != 0 || paused || !v.supplyEnabled) return 0;
        room = supplyRoom(v);
        Token storage t = p.tokens[v.debt];
        uint256 tokenRoom = capRoom(p, t.supplyCapped ? t.supplyCap : 0, v.debt, false);
        if (tokenRoom < room) room = tokenRoom;
    }

    /// @dev The binding threshold of pair `pairIdx`: every borrow-enabled venue of the pair and every one that still
    ///      carries debt, so disabling borrow on an indebted venue cannot let the pair's pin step past its gap. A zero
    ///      threshold binds like any other; `NO_VENUE_LLTV` where none binds, a pair not added among them.
    function minLltv(PoolRecord storage p, uint8 pairIdx) public view returns (uint256 lltv) {
        lltv = NO_VENUE_LLTV;
        uint256 n = p.venues.length;
        for (uint256 i; i < n; ++i) {
            Venue storage v = p.venues[i];
            if (v.status & VENUE_RETIRED != 0 || v.pair != pairIdx) continue;
            if (!v.borrowEnabled && v.account.debtOf(v.id) == 0) continue;
            uint256 l = threshold(v);
            if (l < lltv) lltv = l;
        }
    }

    // ------------------------------------------------------------------ shared internal helpers
    /// @dev Token `idx`'s record, retired or not; `BadTokenIndex` past the list.
    function tokenAt(PoolRecord storage p, uint8 idx) internal view returns (Token storage) {
        if (idx >= p.tokenCount) revert IMMRouter.BadTokenIndex();
        return p.tokens[idx];
    }

    /// @dev Pair `idx`'s record, retired or not; `BadPairIndex` past the list.
    function pairAt(PoolRecord storage p, uint8 idx) internal view returns (Pair storage) {
        if (idx >= p.pairCount) revert IMMRouter.BadPairIndex();
        return p.pairs[idx];
    }

    /// @dev Token `idx`'s address: the pool asset's from the record's first slot, which every pool call reads first.
    function tokenOf(PoolRecord storage p, uint8 idx) internal view returns (address) {
        return idx == 0 ? p.poolAsset : p.tokens[idx].token;
    }

    /// @dev Venue `id`'s record, whatever its status; `BadVenueId` past the array.
    function venueAt(PoolRecord storage p, uint16 id) internal view returns (Venue storage) {
        if (id >= p.venues.length) revert IMMRouter.BadVenueId();
        return p.venues[id];
    }

    /// @dev Venue `id`'s record, `VenueIsRetired` for a retired one. A fenced venue passes: a path that refuses one
    ///      does so itself, and the by-id legs that unwind one or set its caps take it.
    function live(PoolRecord storage p, uint16 id) internal view returns (Venue storage v) {
        v = venueAt(p, id);
        if (v.status & VENUE_RETIRED != 0) revert IMMRouter.VenueIsRetired();
    }

    /// @dev Every priced call's vector holds one USD price per listed token.
    function checkPrices(PoolRecord storage p, uint256[] calldata usd) internal view {
        if (usd.length != p.tokenCount) revert IMMRouter.BadPriceVector();
    }

    /// @dev The pair's price in its venues' price scale, from the pool's USD vector ({pairPrice36}); zero when either
    ///      token is unchecked.
    function priceOf(Pair storage pr, uint256[] calldata usd) internal view returns (uint256) {
        return pairPrice36(usd[pr.coll], usd[pr.debt], pr.collDecimals, pr.debtDecimals);
    }

    /// @dev Pulls exactly `amount` of `token` from the pool's allowance into an account, as OpenZeppelin 4.8's
    ///      `SafeERC20.safeTransferFrom` does (the same call, verdicts and revert data), through `SafeTransferLib`.
    function pull(address token, address to, uint256 amount) internal {
        if (amount != 0) SafeTransferLib.safeTransferFrom(token, msg.sender, to, amount);
    }

    /// @dev Pulls `pay` into the venue's account and repays; a rounding remainder comes straight back.
    function repayInto(Venue storage v, address token, uint256 pay) internal returns (uint256 repaid) {
        pull(token, address(v.account), pay);
        repaid = v.account.repay(v.id, pay);
        if (repaid < pay) v.account.returnToPool(token, pay - repaid);
    }

    /// @dev The owed set (bit `t`: a live, unfenced venue lending token `t` holds borrow shares) and the backing set
    ///      (bit `t`: token `t` is such a venue's collateral), over the live, unfenced venues whose debt token is
    ///      outside `skip`.
    function sets(PoolRecord storage p, uint256 skip) internal view returns (uint256 owed, uint256 backing) {
        uint256 n = p.venues.length;
        for (uint256 i; i < n; ++i) {
            Venue storage v = p.venues[i];
            if (v.status != 0 || (skip >> v.debt) & 1 != 0) continue;
            (, uint256 borrowShares,) = v.account.positionOf(v.id);
            if (borrowShares != 0) {
                owed |= uint256(1) << v.debt;
                backing |= uint256(1) << v.coll;
            }
        }
    }

    /// @dev Whether pair (a -> b) may start a debt, the drawn set read with every venue lending a token of
    ///      `assumeRepaid` as debt-free: refused where a is owed, where b backs a debt, or where b would be an owed
    ///      token past `maxDrawnTokens` (a b already owed adds none). The venues lending b are not read for the first
    ///      two: their debt is never a and their collateral never b. A pool of one pair has nothing else to read.
    function drawable(PoolRecord storage p, Pair storage pr, uint16 assumeRepaid) internal view returns (bool) {
        if (p.pairCount == 1) return true;
        (uint256 a, uint256 b) = (pr.coll, pr.debt);
        (uint256 owed, uint256 backing) = sets(p, uint256(assumeRepaid) | (uint256(1) << b));
        if ((owed >> a) & 1 != 0 || (backing >> b) & 1 != 0) return false;
        uint256 count;
        for (; owed != 0; owed &= owed - 1) {
            ++count;
        }
        if (count < p.maxDrawnTokens) return true;
        // At the limit only a b already owed adds no owed token; a venue lending b read as repaid owes nothing.
        if ((assumeRepaid >> b) & 1 != 0) return false;
        (owed,) = sets(p, ~(uint256(1) << b));
        return owed != 0;
    }

    /// @dev The room under a `cap` (zero: none) on the debt of pair `key` (`debtSide`) or on the recognized supply of
    ///      token `key`, across the live venues it covers; on the supply side a venue whose supply tracker is zero
    ///      recognizes none and is not read. Its callers pass zero while the pair or token has no cap set
    ///      (`Pair.debtCapped`, `Token.supplyCapped`), with no read of the cap's slot.
    function capRoom(PoolRecord storage p, uint256 cap, uint8 key, bool debtSide) internal view returns (uint256) {
        if (cap == 0) return type(uint256).max;
        uint256 used;
        uint256 n = p.venues.length;
        for (uint256 i; i < n; ++i) {
            Venue storage v = p.venues[i];
            if (v.status & VENUE_RETIRED != 0) continue;
            if ((debtSide ? v.pair : v.debt) != key || (!debtSide && v.managedSupplyShares == 0)) continue;
            used += debtSide ? v.account.debtOf(v.id) : read(v).recognizedSupplied;
        }
        return cap > used ? cap - used : 0;
    }

    /// @dev The Router's bounds a post or a withdrawal can move (threshold, debt room, rate, health at the pin), and
    ///      all `fund` re-checks: the pause flag it was handed, the switches and drawn set no leg writes, and a venue
    ///      oracle no leg moves stay as its plan checked them within the call (`IMMRouter.setFundRecheck`). The venue's
    ///      cash is not read: its borrow reverts on a shortfall itself, and the plan and the quote size every slice to
    ///      it. `debt` and `coll`: the venue's position as its caller read it (`position`), after any post of its own.
    function requireSliceFits(Pair storage pr, Venue storage v, uint256 debt, uint256 coll, uint256 assets, uint256 price)
        internal
        view
    {
        if (overPinned(pr, v)) revert IMMRouter.VenueOverPinned();
        if (v.debtCap != 0 && debt + assets > v.debtCap) revert IMMRouter.DebtCapExceeded();
        requireRate(v, assets);
        // Where collateral accrues, a post's two roundings can keep one unit's assets and one: every borrow allows it.
        if (uint256(v.capabilities) & CAP_ACCRUING_COLLATERAL != 0) coll += v.account.collateralUnitsToAssets(v.id, 1) + 1;
        if (debt + assets > maxDebtAtPin(pr, coll, price)) revert IMMRouter.Unhealthy();
    }

    /// @dev Supply delta zero on purpose: `fund` has already executed its withdrawals (`refinanceDebt` makes none), so
    ///      the plan's delta would count twice and refuse the slice `buildPlan` approved.
    function requireRate(Venue storage v, uint256 assets) internal view {
        if (v.maxBorrowRateWad == 0) return;
        (bool ok, uint256 rate) = v.account.borrowRateAfter(v.id, assets, 0);
        if (!ok || rate > v.maxBorrowRateWad) revert IMMRouter.RateCeiling();
    }

    /// @dev Reverts `GlobalPaused` while paused, `VenueDisabled` with the venue's supply switch off and
    ///      `SupplyCapExceeded` past {supplyRoom}.
    function requireSuppliable(Venue storage v, bool paused, uint256 assets) internal view {
        if (paused) revert IMMRouter.GlobalPaused();
        if (!v.supplyEnabled) revert IMMRouter.VenueDisabled();
        if (assets > supplyRoom(v)) revert IMMRouter.SupplyCapExceeded();
    }

    /// @dev The supply the venue takes now: the lesser of the room under its cap in the Router and what a kind that
    ///      caps or gates supply reports; unbounded with neither.
    function supplyRoom(Venue storage v) internal view returns (uint256 room) {
        room = type(uint256).max;
        if (v.supplyCap != 0) {
            uint256 sup = read(v).recognizedSupplied;
            room = v.supplyCap > sup ? v.supplyCap - sup : 0;
        }
        // The venue's own cap and a refused supply, for a kind that reports either.
        if (uint256(v.capabilities) & (CAP_PROTOCOL_CAPS | CAP_ACTION_GATES) != 0) {
            uint256 venueRoom = v.account.suppliable(v.id);
            if (venueRoom < room) room = venueRoom;
        }
    }

    /// @dev A leg over the venue's recognized supply is refused, unless `leg` (the pool's own withdrawal by id,
    ///      `IMMRouter.withdrawSupplied`, whose leg a flow may size from a read that an earlier leg's rounding at the
    ///      same market has since lowered) and {_sharedSupplyRounding} allows it; a migration's never is. `assets` at
    ///      `type(uint256).max` withdraws every recognized share, by shares; with none it withdraws nothing.
    function withdrawSupplied(PoolRecord storage p, Venue storage v, uint256 assets, address to, bool leg)
        internal
        returns (uint256 withdrawn)
    {
        if (assets == type(uint256).max) {
            uint256 shares = managedShares(v);
            if (shares == 0) return 0;
            return withdrawTracked(v, 0, shares, to);
        }
        uint256 rec = recognizedSupplied(v);
        if ((assets == 0 || assets > rec) && !(leg && _sharedSupplyRounding(p, v, assets, rec))) {
            revert IMMRouter.InsufficientLiquidity(assets);
        }
        return withdrawTracked(v, assets, 0, to);
    }

    /// @dev The withdrawal and its tracker, once the caller has bounded it by the recognized supply (`fund`: its plan,
    ///      same call, same state; `addVenue` keeps (account, id) unique, so another venue's leg cannot move it).
    function withdrawTracked(Venue storage v, uint256 assets, uint256 shares, address to) internal returns (uint256 withdrawn) {
        uint256 burned;
        (withdrawn, burned) = v.account.withdraw(v.id, assets, shares, to);
        v.managedSupplyShares = _less(v.managedSupplyShares, burned);
    }

    /// @dev Retirement emptiness: no raw debt, whether or not the venue sits in an order (a retired venue leaves them,
    ///      and its slot reads nothing again), no recognized collateral and no recognized supplied assets, so a
    ///      third-party gift cannot block retirement. Supply counts in assets, as {read}'s recognized supply and the
    ///      emptiness `book` reports do: the share dust a full withdrawal leaves on the tracker, worth no asset and
    ///      past any withdrawal's reach, is none.
    function holdsNothing(Venue storage v) internal view returns (bool) {
        (uint256 supplyShares, uint256 borrowShares, uint256 collateral) = v.account.positionOf(v.id);
        if (borrowShares != 0 || (collateral != 0 && v.managedCollateralUnits != 0)) return false;
        uint256 managed = supplyShares < v.managedSupplyShares ? supplyShares : v.managedSupplyShares;
        return managed == 0 || v.account.supplySharesToAssets(v.id, managed) == 0;
    }

    /// @dev The supply shares the Router recognizes: its tracker, at most the shares the venue holds.
    function managedShares(Venue storage v) internal view returns (uint256) {
        (uint256 actual,,) = v.account.positionOf(v.id);
        return actual < v.managedSupplyShares ? actual : v.managedSupplyShares;
    }

    /// @dev Those shares' worth at the venue, in assets.
    function recognizedSupplied(Venue storage v) internal view returns (uint256) {
        return v.account.supplySharesToAssets(v.id, managedShares(v));
    }

    /// @dev Of `collateral` (assets), what the Router posted: all of it up to the units it posted, so accrual on
    ///      its own collateral counts and a donation never does. Where collateral accrues, the units it posted are
    ///      valued at the accrued state: the position's collateral is its units' value there, by a conversion that
    ///      never falls as units grow (`IFinancingAccount` ADMISSION), so the lesser of the two is what they hold.
    function recognizedFrom(Venue storage v, uint256 collateral) internal view returns (uint256) {
        uint256 managed = v.managedCollateralUnits;
        if (managed == 0) return 0;
        if (uint256(v.capabilities) & CAP_ACCRUING_COLLATERAL != 0) {
            managed = v.account.collateralUnitsToAssets(v.id, managed);
        }
        return collateral < managed ? collateral : managed;
    }

    /// @dev The collateral tracker less what a release burned ({_less}).
    function burnUnits(Venue storage v, uint256 units) internal {
        v.managedCollateralUnits = _less(v.managedCollateralUnits, units);
    }

    /// @dev A tracker less what a leg burned of it, floored at zero: what the leg burned past the tracker was no
    ///      venue's own (a gift's).
    function _less(uint128 managed, uint256 burned) private pure returns (uint128) {
        return burned > managed ? 0 : managed - uint128(burned);
    }

    /// @dev The collateral tracker plus what a post minted; a tracker past 2^128 - 1 reverts.
    function mintUnits(Venue storage v, uint256 units) internal {
        v.managedCollateralUnits = SafeCast.toUint128(v.managedCollateralUnits + units);
    }

    /// @dev The supply tracker plus what a supply minted; a tracker past 2^128 - 1 reverts.
    function mintShares(Venue storage v, uint256 shares) internal {
        v.managedSupplyShares = SafeCast.toUint128(v.managedSupplyShares + shares);
    }

    /// @dev Recognized collateral above the requirement at {releaseLtv}, at the venue's pair's price, and at most what
    ///      the venue lets go of now ({releasable}); zero if indebted and the pair is unchecked (either USD price
    ///      zero), out of band, or with its threshold at or under the gap. `guarded`, as {reclaim} reads it: a band
    ///      read that fails with under an eighth of the gas it began with left reverts `VenueReads.ReadStarved`, as
    ///      the one kind that answers a starved read as unreadable (`MorphoBlueAccount`) would let the caller's limit
    ///      skip the venue.
    function freeCollateral(PoolRecord storage p, Venue storage v, uint256[] calldata usd, bool guarded)
        internal
        view
        returns (uint256)
    {
        Read memory rd = read(v);
        uint256 free = rd.recognizedCollateral;
        if (rd.debt != 0) {
            Pair storage pr = p.pairs[v.pair];
            uint256 price = priceOf(pr, usd);
            uint256 g = gasleft();
            if (price == 0 || !bandOk(pr, v, price)) {
                if (guarded && gasleft() < g / 8) revert VenueReads.ReadStarved();
                return 0;
            }
            uint256 ltv = releaseLtv(pr, v);
            if (ltv == 0) return 0;
            uint256 required = requiredCollateral(ltv, rd.debt, price);
            uint256 over = rd.collateral > required ? rd.collateral - required : 0;
            if (over < free) free = over;
        }
        uint256 rel = releasable(v);
        return free < rel ? free : rel;
    }

    /// @dev Whether the venue allows `action` now: always, for a kind that never refuses one (a refusing venue is
    ///      skipped, never written down); read for that action alone where the account answers `IActionsOf`.
    function canAct(Venue storage v, uint8 action) internal view returns (bool) {
        if (uint256(v.capabilities) & CAP_ACTION_GATES == 0) return true;
        uint8 allowed = v.actionsOf ? IActionsOf(address(v.account)).actionsOf(v.id, action) : v.account.actions(v.id);
        return allowed & action != 0;
    }

    /// @dev Whether the venue's legs can move other venues' cash and rate, and theirs its own: one reserve behind them.
    function sharesCash(Venue storage v) internal view returns (bool) {
        return uint256(v.capabilities) & CAP_SHARED_LIQUIDITY != 0;
    }

    /// @dev What the venue lets this position release now: unbounded for a kind that neither lends collateral, refuses
    ///      a release nor reads its oracle on a release at zero debt, else as its account reports it, owing or not.
    ///      Every release the Router asks for is bounded by it (`withdrawCollateral`, `reclaim` through
    ///      {freeCollateral}, a refinance's move), so it never asks a venue for more than it reports it can release;
    ///      the venue's own health check on an indebted release still stands.
    function releasable(Venue storage v) internal view returns (uint256) {
        if (uint256(v.capabilities) & (CAP_LENT_COLLATERAL | CAP_ACTION_GATES | CAP_PRICED_RELEASE) == 0) {
            return type(uint256).max;
        }
        return v.account.collateralReleasable(v.id);
    }

    /// @dev `withdrawCollateral`'s proportional proof where the exact one fails: the release stands if the venue's
    ///      collateral accrues, the same transaction's repay lowered the debt and the collateral that stays is short of
    ///      its exact share by no more than {RELEASE_SLACK} of debt and {_roundingSlack} of collateral allow. It reads
    ///      the debt, the collateral and the repay's snapshot again, in the same state, so the exact proof's passing
    ///      path, which every release at an indebted venue takes, keeps none of them for it. Where collateral does not
    ///      accrue the allowance is zero and the exact proof's refusal stands.
    function _requireSharedRounding(PoolRecord storage p, Venue storage v, uint16 id, uint256 assets) private view {
        if (uint256(v.capabilities) & CAP_ACCRUING_COLLATERAL == 0) revert IMMRouter.Unhealthy();
        (uint256 debtBefore, uint256 collBefore) = repaySnapshot(msg.sender, id);
        IFinancingAccount a = v.account;
        bytes32 vid = v.id;
        uint256 debt = a.debtOf(vid);
        // A repay that lowered nothing earns no allowance.
        if (debt >= debtBefore) revert IMMRouter.Unhealthy();
        uint256 held = debt > RELEASE_SLACK ? debt - RELEASE_SLACK : 0;
        uint256 slack = _roundingSlack(p, a.collateralUnitsToAssets(vid, 1), v.coll, assets);
        if (held * collBefore > debtBefore * (a.collateralOf(vid) - assets + slack)) revert IMMRouter.Unhealthy();
    }

    /// @dev Whether `IMMRouter.withdrawSupplied` takes a leg over the venue's recognized supply, read only where the
    ///      leg is over it (or zero): it does if the venue's units accrue at a market other positions hold, it
    ///      recognizes some supply, and the leg is over it by no more than {_roundingSlack} of the token. The venue's
    ///      own units then pay it, the market's rounding the rest, as a redemption by amount burns the units it gives
    ///      rounded down. It takes the recognized supply its caller read (`rec`), so a leg reads it once.
    function _sharedSupplyRounding(PoolRecord storage p, Venue storage v, uint256 assets, uint256 rec)
        private
        view
        returns (bool)
    {
        if (rec == 0 || assets == 0 || uint256(v.capabilities) & CAP_ACCRUING_COLLATERAL == 0) return false;
        return assets <= rec + _roundingSlack(p, v.account.supplySharesToAssets(v.id, 1), v.debt, assets);
    }

    /// @dev What a leg at a venue whose units accrue may ask past what its exact proof allows (a release) or what the
    ///      venue recognizes (a supply withdrawal): a market whose rate takes every holder's rounding.
    ///      - A redemption by amount burns the units it gives rounded down (Compound-style), so the market pays up to a
    ///        unit's worth over what it burns, out of every other position's units, the pool's other venues at that
    ///        market among them.
    ///      - A pool's flow sizes its legs from one read before its first, so the exact share of a later venue's
    ///        position, asked after an earlier leg moved that rate, is a little over what the venue now gives it.
    ///      - An exit moves a market at most once for each other venue (a venue posts the token there or lends it, not
    ///        both), each time taking under one unit's worth, rounded up, off this venue's units, which are part of
    ///        that market.
    ///
    ///      So the slack is:
    ///      - one unit's worth (`unit`, read from the kind) and one, for each venue of the pool;
    ///      - never more than a millionth of one whole token `token` and one, so a rate raised by a donation cannot
    ///        widen it;
    ///      - never more than four base units and a millionth of the leg (`assets`), as a migration may lose: rounding
    ///        beside the leg, so a flow that repeats a repay and a release gains four base units a cycle at most, as
    ///        {RELEASE_SLACK} lets it gain four units of debt's worth.
    ///
    ///      The allowance answers no particular sibling leg: at a kind whose rate no other position's leg moves (Aave's
    ///      index), it widens the proof by rounding alone, which the last bound holds to four base units and a
    ///      millionth of the leg.
    function _roundingSlack(PoolRecord storage p, uint256 unit, uint8 token, uint256 assets)
        private
        view
        returns (uint256 slack)
    {
        uint256 most;
        // A listed token has at most 18 decimals, and `unit` under `most` (at most 1e12 + 1) and one, for each of at
        // most `MAX_VENUES`, fits a word: no overflow, and no checked power shared with the price scale.
        unchecked {
            most = 10 ** uint256(p.tokens[token].decimals) / MIGRATION_LOSS_DIVISOR + 1;
            if (unit < most && (unit + 1) * p.venues.length < most) most = (unit + 1) * p.venues.length;
        }
        slack = RELEASE_SLACK + assets / MIGRATION_LOSS_DIVISOR;
        if (slack > most) slack = most;
    }

    /// @dev `price` is in the venue's price scale: debt base units per collateral base unit, scaled by 1e36.
    function maxDebtAtPin(Pair storage pr, uint256 collateral, uint256 price) internal view returns (uint256) {
        return maxDebtAt(pr.pinLtvWad, collateral, price);
    }

    /// @dev The most debt `collateral` carries at `ltvWad` and `price`, both steps rounded down, so the debt stays
    ///      within the LTV.
    function maxDebtAt(uint256 ltvWad, uint256 collateral, uint256 price) internal pure returns (uint256) {
        return Math.mulDiv(Math.mulDiv(collateral, price, ORACLE_PRICE_SCALE), ltvWad, WAD);
    }

    /// @dev The least collateral that carries `debt` at `ltvWad` and `price`, both steps rounded up, so the debt stays
    ///      within the LTV; neither `ltvWad` nor `price` may be zero.
    function requiredCollateral(uint256 ltvWad, uint256 debt, uint256 price) internal pure returns (uint256) {
        uint256 value = Math.mulDiv(debt, WAD, ltvWad, Math.Rounding.Up);
        return Math.mulDiv(value, ORACLE_PRICE_SCALE, price, Math.Rounding.Up);
    }

    /// @dev The LTV a priced release may leave an indebted venue at: its pair's pin, or the venue's threshold less the
    ///      pair's gap once that is lower (zero at or under the gap), so a release never takes the venue past what its
    ///      lender now allows. Only a mutable threshold can fall under the pin plus the gap while the venue owes: the
    ///      pin rises only within the pair's `minLltv`, which counts every indebted venue of the pair, and an
    ///      over-pinned venue borrows nothing.
    function releaseLtv(Pair storage pr, Venue storage v) internal view returns (uint256 ltv) {
        ltv = pr.pinLtvWad;
        if (uint256(v.capabilities) & CAP_MUTABLE_THRESHOLD == 0) return ltv;
        uint256 t = v.account.lltv(v.id);
        uint256 gap = pr.safetyGapWad;
        if (t < ltv + gap) ltv = t > gap ? t - gap : 0;
    }

    /// @dev The pair's price and the venue's oracle speak the same price scale, so they compare directly. A zero band
    ///      is off: no venue oracle is read and only a zero price fails.
    function bandOk(Pair storage pr, Venue storage v, uint256 price) internal view returns (bool) {
        uint256 band = pr.oracleBandWad;
        if (band == 0) return price != 0;
        (bool ok, uint256 oracle) = v.account.oraclePrice(v.id);
        if (!ok || price == 0) return false;
        uint256 dev = oracle > price ? oracle - price : price - oracle;
        return dev <= Math.mulDiv(price, band, WAD);
    }

    /// @dev The venue's threshold is below its pair's pin plus the pair's gap: a lender cut it after the checks, or its
    ///      borrowing is off and it owes nothing, which neither its admission nor a pin rise checks. It lends nothing
    ///      while it stays there (a lower pin ends it, as does a raise of a threshold that can move), and a priced
    ///      release of an indebted venue whose threshold can fall stops at the threshold less the gap.
    function overPinned(Pair storage pr, Venue storage v) internal view returns (bool) {
        return threshold(v) < uint256(pr.pinLtvWad) + pr.safetyGapWad;
    }

    /// @dev The venue's threshold now: read from the account for a kind whose threshold can fall, else the one
    ///      registered at admission.
    function threshold(Venue storage v) internal view returns (uint256) {
        return uint256(v.capabilities) & CAP_MUTABLE_THRESHOLD != 0 ? v.account.lltv(v.id) : v.lltvWad;
    }

    /// @dev The pre-repay (debt, collateral) of a venue, kept in transient storage so a proportional collateral
    ///      withdrawal in the same transaction can prove it does not worsen the venue without a price; one read of its
    ///      position, whose debt the repay pays at most.
    function snapshotForProportional(Venue storage v, uint16 id) internal returns (uint256 debt) {
        uint256 coll;
        (coll,,, debt) = v.account.position(v.id);
        _snapshot(id, debt, coll);
    }

    /// @dev `position` answers the same (debt, collateral) as `debtOf` and `collateralOf` in one state. The slot is
    ///      the pool's address over the venue id ({repaySnapshot}).
    function _snapshot(uint16 id, uint256 debt, uint256 coll) private {
        uint256 slot = (uint256(uint160(msg.sender)) << 16) | id;
        uint256 packed = (debt << 128) | coll;
        assembly ("memory-safe") {
            tstore(slot, packed)
        }
    }

    /// @dev Pool `pool`'s snapshot of venue `id`, at transient slot `pool << 16 | id`: distinct pools and ids give
    ///      distinct slots, all at or past 2^16, so none is the reentrancy guard's slot zero.
    function repaySnapshot(address pool, uint16 id) internal view returns (uint256 debt, uint256 coll) {
        uint256 slot = (uint256(uint160(pool)) << 16) | id;
        uint256 packed;
        assembly ("memory-safe") {
            packed := tload(slot)
        }
        debt = packed >> 128;
        coll = packed & type(uint128).max;
    }
}

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

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

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

/// @notice The minimum position of a kind that declares `CAP_HELD_REPAY`, which the pool reads (`IFinancingAccount`
///         ADMISSION): a partial repay that leaves the debt at least `floor`, as the venue values it, is taken whole,
///         and a borrow or a supply that leaves the position under it is refused, so the Router's plan and supply
///         cascade pass over a slice there that would (`MMRouterLib`), with the lenders' rounding past it where the
///         lender's check can read the position low: a supply, whose shares it mints rounded down, and a borrow where
///         the venue owes.
interface IHeldRepay {
    /// @notice The minimum debt at venue `id`, in loan-token base units; `ok` false while the venue cannot value it,
    ///         when a partial repay may take nothing. Never reverts, and answers within `MMRouterLib.MINIMUM_READ_GAS`
    ///         (1,000,000 gas), an admission rule of every kind that declares `CAP_HELD_REPAY`: the Router's plan and
    ///         supply cascade pass over a venue whose read reverts, answers short or runs past it.
    function minimumDebt(bytes32 id) external view returns (bool ok, uint256 floor);
}

/// @notice The bound a kind's lender takes repays up to, which a debt can pass (a Compound-style market's total
///         borrows, which a sole borrower's debt passes by a remainder no repay takes: `CTokenAccount`), and the market
///         it is the bound of, which no capability bit declares: every venue borrowing from that market repays out of
///         the one bound, so a repay there takes at most what the repays before it, at any of the pool's venues, left
///         of it. The pool reads it of a cover pair's venues whose kind can refuse an action and declares no
///         `CAP_HELD_REPAY` (`FLAMMLawLib`'s cover check), and its exit maximum of every indebted venue whose kind
///         declares no `CAP_HELD_REPAY`, each walking the venues in the order the swap or the exit repays them
///         (`FLAMMExitMaxima`); a venue that does not answer is read as taking a repay of its whole debt whole.
interface IRepayable {
    /// @notice The most venue `id`'s lender takes of repays now, in loan-token base units (`type(uint256).max` where it
    ///         reads none), and the market whose bound it is, one address per bound across every account of the
    ///         kind. Never reverts.
    function repayable(bytes32 id) external view returns (uint256 bound, address market);
}

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/libraries/Constants.sol

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

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

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

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

src/libraries/SafeTransferLib.sol

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

/// @notice The token calls of the pool, the Router, the venue kinds, the PropAMM contracts and the periphery:
///         OpenZeppelin 4.8's `SafeERC20.safeTransfer`, `safeTransferFrom` and `safeApprove`, with its calls, verdicts
///         and revert data, built in scratch memory. The pool and the Router both import it, so the Router compiles no
///         pool source and no pool edit reaches its token calls.
/// @dev Scratch memory is the memory at the free-memory pointer, which no function here moves: nothing it writes
///      outlives the call.
library SafeTransferLib {
    /// @notice OpenZeppelin 4.8's `SafeERC20.safeTransfer`: the same call, verdict and revert data (see
    ///         {_callOptionalReturn}), built in scratch memory.
    function safeTransfer(address token, address to, uint256 amount) internal {
        uint256 m;
        assembly ("memory-safe") {
            m := mload(0x40)
            mstore(m, shl(224, 0xa9059cbb)) // transfer(address,uint256)
            mstore(add(m, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(m, 36), amount)
        }
        _callOptionalReturn(token, m, 68);
    }

    /// @notice OpenZeppelin 4.8's `SafeERC20.safeTransferFrom`: the same call, verdict and revert data (see
    ///         {_callOptionalReturn}), built in scratch memory.
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        uint256 m;
        assembly ("memory-safe") {
            m := mload(0x40)
            mstore(m, shl(224, 0x23b872dd)) // transferFrom(address,address,uint256)
            mstore(add(m, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(m, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(m, 68), amount)
        }
        _callOptionalReturn(token, m, 100);
    }

    /// @dev The `len` bytes of call data at `m` sent to `token` as OpenZeppelin 4.8's `SafeERC20._callOptionalReturn`
    ///      sends them (`Address.functionCall`: all gas, no value), with its verdicts: a failed call bubbles its revert
    ///      data, or reverts "SafeERC20: low-level call failed" with none; an empty success needs code at `token`
    ///      ("Address: call to non-contract"); returned data must open with a bool (else an empty revert, as
    ///      `abi.decode` gives) that is true ("SafeERC20: ERC20 operation did not succeed"). A success copies no return
    ///      data but that first word.
    function _callOptionalReturn(address token, uint256 m, uint256 len) private {
        assembly ("memory-safe") {
            // `Error(string)` with the `n`-byte message `w0 ++ w1`, at `p`
            function fail(p, n, w0, w1) {
                mstore(p, shl(224, 0x08c379a0))
                mstore(add(p, 4), 0x20)
                mstore(add(p, 36), n)
                mstore(add(p, 68), w0)
                mstore(add(p, 100), w1)
                revert(p, add(68, mul(0x20, div(add(n, 31), 32))))
            }
            let ok := call(gas(), token, 0, m, len, 0, 0)
            let rds := returndatasize()
            if iszero(ok) {
                if rds {
                    returndatacopy(m, 0, rds)
                    revert(m, rds)
                }
                fail(m, 32, "SafeERC20: low-level call failed", 0)
            }
            switch rds
            case 0 {
                if iszero(extcodesize(token)) { fail(m, 29, "Address: call to non-contract", 0) }
            }
            default {
                if lt(rds, 32) { revert(0, 0) }
                returndatacopy(m, 0, 32)
                let v := mload(m)
                if gt(v, 1) { revert(0, 0) }
                if iszero(v) { fail(m, 42, "SafeERC20: ERC20 operation did n", "ot succeed") }
            }
        }
    }

    /// @notice OpenZeppelin 4.8's `SafeERC20.safeApprove` without its read of the standing allowance: the same call,
    ///         verdict and revert data (see {_callOptionalReturn}), built in scratch memory. Its callers never grant
    ///         over a standing grant: a leg's grant is pulled in full or cleared within the call, and a door's standing
    ///         grant to its front is made once, from zero, each renewal clearing it first. (The Aave kind's standing
    ///         grant takes its own route, `AaveV3ReadsLib`, once per token, from zero.) A token that refuses a grant
    ///         over a nonzero one (Ethereum's USDT; BNB Chain's does not) needs that: every grant there is made from
    ///         zero.
    function safeApprove(address token, address spender, uint256 amount) internal {
        uint256 m;
        assembly ("memory-safe") {
            m := mload(0x40)
            mstore(m, shl(224, 0x095ea7b3)) // approve(address,uint256)
            mstore(add(m, 4), and(spender, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(m, 36), amount)
        }
        _callOptionalReturn(token, m, 68);
    }
}
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.