Skip to content
Verified contractExactUNLICENSED

FLAMMLens

Address0x870b79f01b2d3c1bcbf844f3dfeaa2f99163ca82
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.35

 

Same code

2 more contracts

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 100 runs
EVM version
cancun
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,396,606
Creation transaction
0x8891e8cc90…1611443822
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

61 files

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

src/periphery/FLAMMLens.sol

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

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {EverlongHook} from "src/hooks/everlong/EverlongHook.sol";
import {LeverageLib} from "src/hooks/everlong/LeverageLib.sol";
import {Mul512} from "src/libraries/math/Mul512.sol";
import {FLAMMStore} from "src/core/flamm/FLAMMStore.sol";
import {IFLAMM, IFLAMMProtocolFee} from "src/interfaces/core/flamm/IFLAMM.sol";
import {IFLAMMFence} from "src/interfaces/core/flamm/IFLAMMFence.sol";
import {PoolContext} from "src/interfaces/core/flamm/IFLAMMHooks.sol";
import {PairFill, PairRequest} from "src/interfaces/core/flamm/IPairHook.sol";
import {IMMRouter, pairPrice36, VENUE_RETIRED, VENUE_FENCED} from "src/interfaces/core/mm/IMMRouter.sol";
import {IFinancingAccount} from "src/interfaces/core/mm/IFinancingAccount.sol";
import {IPriceFeed} from "src/interfaces/core/IPriceFeed.sol";
import {IEverlongCore} from "src/interfaces/core/IEverlongCore.sol";
import {WAD} from "src/libraries/Constants.sol";

/// @notice What a core that schedules its owner and its guardian (`DelayedAuthority`) answers beside `IEverlongCore`:
///         each scheduled successor and when it may take office, zero for none or a lapsed one.
interface IScheduledCore {
    /// @notice The scheduled owner.
    function pendingOwner() external view returns (address);
    /// @notice When the scheduled owner may take office, in unix seconds.
    function ownerDueAt() external view returns (uint64);
    /// @notice The scheduled guardian.
    function pendingGuardian() external view returns (address);
    /// @notice When the scheduled guardian may take office, in unix seconds.
    function guardianDueAt() external view returns (uint64);
}

/// @notice Read-only reporting over any pool: its identity, facts, policy, NAV, every venue and its quotes.
///         Price-dependent answers carry an `ok` flag instead of reverting. The views named for the pool asset and
///         token 1 (`facts`, `config`, `price`, `previewSwap`, the leverage state) report the hook pair; `loans` and
///         `venues` report every token past the pool asset and every venue, and `FLAMMBookLens` every token and credit
///         pair.
contract FLAMMLens {

    /// @notice What a pool is bound to: its two hook-pair tokens, Router, price feed, core, deposit allowlist (zero for
    ///         none), Factory and hooks; then its core's curator, guardian, keeper and fee receiver, and the rest as
    ///         the comments below say.
    struct Identity {
        address poolAsset;
        address loanAsset;
        address router;
        address priceFeed;
        address core;
        address allowlist;
        address factory;
        IFLAMM.HookSet hooks;
        address curator;
        address guardian;
        address keeper;
        address feeReceiver;
        // The Factory's receiver of the protocol's part of the performance fee; zero when the pool's factory does not
        // answer.
        address protocolFeeReceiver;
        // The core's scheduled curator and guardian, and when each may take office: the notice a pool's depositors
        // have of either change. Zero where none is scheduled, the schedule lapsed, or the core answers none; a core
        // whose nominated owner takes office at once (`EverlongCore`) names it with a zero due time.
        address pendingCurator;
        uint64 curatorDueAt;
        address pendingGuardian;
        uint64 guardianDueAt;
    }

    /// @notice The pool asset's custody (`physical`), posted collateral and gross (custody, supply and collateral);
    ///         token 1's custody (`liquid`), supply and debt; the share supply and the pause. The short side follows:
    ///         what the pool owes of the pool asset and posts of token 1.
    struct Facts {
        uint256 physical;
        uint256 posted;
        uint256 gross;
        uint256 liquid;
        uint256 supplied;
        uint256 debt;
        uint256 totalSupply;
        bool paused;
        uint256 owedPoolAsset;
        uint256 postedLoan;
    }

    /// @notice A venue's Router record as `IMMRouter.venue` returns it, then its position, borrowable cash and health.
    ///         A slot the pool's walks skip (`IFLAMM.retiredVenues`) reads as its id and its `venue.status` alone, a
    ///         fenced one's (`VENUE_FENCED`, `IFLAMMFence.fencedVenues`) or a retired one's: the pool reads nothing of
    ///         it, as a retired venue's lender may not answer and a fenced one's takes no leg.
    struct Venue {
        uint16 id;
        IMMRouter.VenueView venue;
        uint256 collateral;
        uint256 recognizedCollateral;
        uint256 supplied;
        uint256 recognizedSupplied;
        uint256 debt;
        uint256 freeLiquidity;
        bool healthOk;
        uint256 healthWad;
    }

    /// @notice What `nav` answers: the checked price as `price` reads it, with the feed's older source stamp and token
    ///         1's peg verdict, and the pool's NAV in poolAsset; `ok` false when `nav` says.
    struct Nav {
        bool ok;
        uint256 priceN36; // token 1's value at 36 decimals per poolAsset base unit (the hooks' price scale)
        uint48 observedAt;
        bool pegOk;
        uint256 totalAssets;
    }

    /// @notice A pool's policy on the hook pair: the comments below name each part.
    struct Config {
        // the forward pair's record (token 1 borrowed against the pool asset, whatever its index), its dials and
        // envelope; empty where the pool lists none, its index then `type(uint8).max` (`pairIndex`, last)
        IFLAMM.PairConfig pair;
        // `limits.peakSharePriceWad`: the last crystallized high-water mark, poolAsset base units per share-wei, WAD;
        // on a cheap-lane pool whose deposit basket is set, the fee mark of NAV per share against the basket's value,
        // a WAD ratio (1e18 at the basket's record).
        IFLAMM.Limits limits;
        // token 1's own record: its notional cap on a swap, its swap band (WAD) and its reserve target
        uint256 maxSwapNotionalLoan;
        uint64 swapPriceBandWad;
        uint256 reserveTargetLoan;
        // The protocol fee's scheduled rise at the Factory, beside the curator's in `limits`; zero when none. The rate
        // itself is the pool's own `limits.protocolFeeBp`, which the Factory mirrors in `protocolFeeBpOf`.
        uint16 pendingProtocolFeeBp;
        uint48 protocolFeeExecutableAt;
        // The committed ceilings on every token's swap band and on the fee cap (`IFLAMM.ceilings`), and their
        // scheduled raise with when it applies; zero when none.
        uint64 bandCeilingWad;
        uint64 feeCapCeilingWad;
        uint64 pendingBandCeilingWad;
        uint64 pendingFeeCapCeilingWad;
        uint48 ceilingsExecutableAt;
        // the forward pair's index among the pool's pairs
        uint8 pairIndex;
    }

    /// @notice The pool's bindings and authorities, as `Identity` describes them.
    function identity(address pool) external view returns (Identity memory r) {
        IFLAMM p = IFLAMM(pool);
        r.poolAsset = p.asset();
        r.loanAsset = p.loanAsset();
        r.router = p.router();
        r.priceFeed = p.priceFeed();
        r.core = p.core();
        r.allowlist = p.depositAllowlist();
        r.factory = p.factory();
        r.hooks = p.hooks();
        IEverlongCore c = IEverlongCore(r.core);
        r.curator = c.owner();
        r.guardian = c.guardian();
        r.keeper = c.keeper();
        r.feeReceiver = c.feeReceiver();
        r.pendingCurator = address(uint160(_word(r.core, IScheduledCore.pendingOwner.selector)));
        r.curatorDueAt = uint64(_word(r.core, IScheduledCore.ownerDueAt.selector));
        r.pendingGuardian = address(uint160(_word(r.core, IScheduledCore.pendingGuardian.selector)));
        r.guardianDueAt = uint64(_word(r.core, IScheduledCore.guardianDueAt.selector));
        if (r.factory.code.length == 0) return r;
        try IFLAMMProtocolFee(r.factory).protocolFeeReceiver() returns (address to) {
            r.protocolFeeReceiver = to;
        } catch {}
    }

    /// @dev The one word `target` answers to `selector`, zero where it answers nothing.
    function _word(address target, bytes4 selector) internal view returns (uint256 v) {
        (bool ok, bytes memory ret) = target.staticcall(abi.encodeWithSelector(selector));
        if (ok && ret.length >= 32) v = abi.decode(ret, (uint256));
    }

    /// @notice The pool book on the hook pair, as `Facts` describes it.
    function facts(address pool) external view returns (Facts memory f) {
        IFLAMM p = IFLAMM(pool);
        uint256 supplied0;
        (f.physical, supplied0, f.posted, f.owedPoolAsset) = p.position(0);
        f.gross = f.physical + supplied0 + f.posted;
        (f.liquid, f.supplied, f.postedLoan, f.debt) = p.position(1);
        f.totalSupply = p.totalSupply();
        f.paused = p.paused();
    }

    /// @notice The pool's forward pair and policy, as `Config` describes them.
    function config(address pool) external view returns (Config memory c) {
        IFLAMM p = IFLAMM(pool);
        c.pairIndex = type(uint8).max;
        // The Router lists a pair's two tokens in the same roles once, retired or not, so the forward pair (0 -> 1) is
        // one pair or none. Token 1's `pairId` names the lowest-index live pair that owes it: the forward pair where it
        // is that one, else another collateral's pair, when the pairs are scanned for it.
        IFLAMM.TokenConfig memory t1 = p.tokenConfig(1);
        uint256 m = p.pairCount();
        if (t1.pairId < m) {
            IFLAMM.PairConfig memory pc = p.pairConfig(t1.pairId);
            if (pc.coll == 0 && pc.debt == 1) (c.pair, c.pairIndex) = (pc, t1.pairId);
            else (c.pair, c.pairIndex) = _forwardPair(p, m, t1.pairId);
        } else {
            (c.pair, c.pairIndex) = _forwardPair(p, m, t1.pairId);
        }
        c.limits = p.limits();
        (c.swapPriceBandWad, c.maxSwapNotionalLoan, c.reserveTargetLoan) =
            (t1.swapPriceBandWad, t1.maxSwapNotional, t1.reserveTarget);
        (c.bandCeilingWad, c.feeCapCeilingWad, c.pendingBandCeilingWad, c.pendingFeeCapCeilingWad, c.ceilingsExecutableAt) =
            p.ceilings();
        address factory = p.factory();
        if (factory.code.length == 0) return c;
        try IFLAMMProtocolFee(factory).pendingProtocolFee(pool) returns (uint16 feeBp, uint48 due) {
            (c.pendingProtocolFeeBp, c.protocolFeeExecutableAt) = (feeBp, due);
        } catch {}
    }

    /// @dev The forward pair (0 -> 1) among the pool's `m` pairs but `skip`, and its index; `type(uint8).max` for none.
    function _forwardPair(IFLAMM p, uint256 m, uint8 skip)
        private
        view
        returns (IFLAMM.PairConfig memory pc, uint8 index)
    {
        for (uint8 i; i < m; ++i) {
            if (i == skip) continue;
            pc = p.pairConfig(i);
            if (pc.coll == 0 && pc.debt == 1) return (pc, i);
        }
        delete pc;
        index = type(uint8).max;
    }

    /// @dev The selectors of the fee floors' setters (`FLAMMPolicyLib.setFeeBounds`, `FLAMMPolicyLib.setTokenConfig`).
    bytes4 internal constant SET_FEE_BOUNDS = bytes4(keccak256("setFeeBounds(uint64,uint64)"));
    bytes4 internal constant SET_TOKEN_CONFIG =
        bytes4(keccak256("setTokenConfig(uint8,uint64,uint64,uint256,uint256)"));

    /// @notice A hook-pair fill's fee bounds and one scheduled change of a floor: the comments below name each part.
    struct FeeFloor {
        // The least fee rate a hook-pair fill takes, WAD: the higher of the pool's floor (`limits.feeFloorWad`) and
        // token 1's (`tokenConfig(1).feeFloorWad`), each named after it; then the most (`limits.feeCapWad`). On a pool
        // whose cheap lane is off a call that cuts either floor waits the pool's delay, its other values with it, and
        // one that cuts neither applies at once.
        uint64 floorWad;
        uint64 poolFloorWad;
        uint64 loanFloorWad;
        uint64 feeCapWad;
        // The change `call` schedules, as its `AdmissionScheduled` event names it: its setter (`setFeeBounds`, the
        // pool's floor, or `setTokenConfig`, token `token`'s), the floor it sets, when the identical call may apply it
        // (`dueAt`) and the last second it may (`lapsesAt`, one execution window later: the pool delay or one day, if longer). The times are zero where it is not
        // pending (applied, replaced, dropped, cancelled or lapsed), and every field here zero where `call` is neither
        // setter's.
        bytes4 setter;
        uint8 token;
        uint64 scheduledFloorWad;
        uint48 dueAt;
        uint48 lapsesAt;
    }

    /// @notice The pool's fee bounds on the hook pair and the scheduled change `call` names, as `FeeFloor` describes
    ///         them: `call` is the `call` of the pool's `AdmissionScheduled` event, empty for the bounds alone. A cut
    ///         of a floor shows from its scheduling event, a pool delay before the identical call may apply it.
    function feeFloor(address pool, bytes calldata call) external view returns (FeeFloor memory f) {
        IFLAMM p = IFLAMM(pool);
        IFLAMM.Limits memory l = p.limits();
        (f.poolFloorWad, f.feeCapWad, f.loanFloorWad) = (l.feeFloorWad, l.feeCapWad, p.tokenConfig(1).feeFloorWad);
        f.floorWad = f.poolFloorWad > f.loanFloorWad ? f.poolFloorWad : f.loanFloorWad;
        if (call.length < 4) return f;
        bytes4 setter = bytes4(call[:4]);
        // the setter's selector and arguments, abi-encoded as one tuple, as the pool schedules them
        if (setter == SET_FEE_BOUNDS && call.length == 96) {
            (, f.scheduledFloorWad,) = abi.decode(call, (bytes4, uint64, uint64));
        } else if (setter == SET_TOKEN_CONFIG && call.length == 192) {
            (, f.token,, f.scheduledFloorWad,,) = abi.decode(call, (bytes4, uint8, uint64, uint64, uint256, uint256));
        } else {
            return f;
        }
        f.setter = setter;
        uint256 due = p.pending(keccak256(call));
        if (due == 0) return f;
        (, uint32 delay) = p.switches();
        (f.dueAt, f.lapsesAt) = (uint48(due), uint48(due + FLAMMStore.executionWindow(delay)));
    }

    /// @notice The poolAsset's price in token 1 at 36 decimals per poolAsset base unit (the hooks' price scale), from
    ///         the feed's two USD prices with one floor; `ok` false when unchecked.
    function price(address pool) public view returns (bool ok, uint256 priceN36, uint48 observedAt, bool pegOk) {
        IFLAMM p = IFLAMM(pool);
        IPriceFeed feed = IPriceFeed(p.priceFeed());
        address poolAsset = p.asset();
        try feed.peekPair(poolAsset, p.loanAsset()) returns (bool ok_, uint256 poolUsd, uint256 loanUsd, uint48 ts) {
            if (ok_) priceN36 = _scaled(poolUsd, loanUsd, 10 ** (36 - IERC20Metadata(poolAsset).decimals()));
            (ok, observedAt) = (priceN36 != 0, ts);
        } catch {}
        try feed.pegOk(p.loanAsset()) returns (bool peg) {
            pegOk = peg;
        } catch {}
    }

    /// @notice The checked price and the pool's NAV in poolAsset; `ok` false when the price is unchecked, on the hooks'
    ///         price scale or the Router's, or the NAV does not read.
    function nav(address pool) external view returns (Nav memory n) {
        IFLAMM p = IFLAMM(pool);
        (n.ok, n.priceN36, n.observedAt, n.pegOk) = price(pool);
        if (!n.ok || _price36(IPriceFeed(p.priceFeed()), p.asset(), p.loanAsset()) == 0) {
            n.ok = false;
            return n;
        }
        try p.totalAssets() returns (uint256 ta) {
            n.totalAssets = ta;
        } catch {
            n.ok = false;
        }
    }

    /// @notice One token's binding, policy, position and price, for each token past the pool asset: entry `index` is
    ///         token `index + 1`, the pool's own index, which `tokenIndex` (last) names. `liquid` is its held custody,
    ///         `posted` what the pool posts of it as collateral; `price36` is its price on the Router's price scale
    ///         (its base units per poolAsset base unit, scaled by 1e36) and `crossWad` its cross with token 1, the
    ///         numeraire (`WAD` for token 1 itself); `ok` false means the feed is unchecked.
    struct Loan {
        uint8 index;
        address token;
        uint8 decimals;
        uint64 swapPriceBandWad;
        uint64 feeFloorWad;
        uint256 maxSwapNotional;
        uint256 reserveTarget;
        uint256 liquid;
        uint256 supplied;
        uint256 debt;
        bool ok;
        uint256 price36;
        uint256 crossWad;
        bool pegOk;
        uint8 tokenIndex;
        uint256 posted;
    }

    /// @notice Every token past the pool asset, as `Loan` describes it. Each entry is sixteen words, back to back, so a
    ///         decoder of any other shape misreads every entry after the first. Decode with this ABI.
    function loans(address pool) external view returns (Loan[] memory out) {
        IFLAMM p = IFLAMM(pool);
        IMMRouter r = IMMRouter(p.router());
        IPriceFeed feed = IPriceFeed(p.priceFeed());
        address poolAsset = p.asset();
        (bool okBase, uint256 usdBase,) = feed.peekUsd(p.loanAsset());
        uint256 n = p.tokenCount() - 1;
        out = new Loan[](n);
        // the Router's book in one read: entry `i` is token `i + 1` there
        (uint256[] memory pst, uint256[] memory sup, uint256[] memory owed,) = r.book(pool, 0);
        for (uint8 i; i < n; ++i) {
            Loan memory l = out[i];
            (l.index, l.tokenIndex, l.posted) = (i, i + 1, pst[i + 1]);
            IFLAMM.TokenConfig memory t = p.tokenConfig(i + 1);
            (l.token, l.decimals, l.swapPriceBandWad, l.feeFloorWad, l.maxSwapNotional, l.reserveTarget, l.liquid) =
                (t.token, t.decimals, t.swapPriceBandWad, t.feeFloorWad, t.maxSwapNotional, t.reserveTarget, t.held);
            (l.supplied, l.debt) = (sup[i + 1], owed[i + 1]);
            l.price36 = _price36(feed, poolAsset, l.token);
            l.ok = l.price36 != 0;
            (bool okI, uint256 usdI,) = feed.peekUsd(l.token);
            if (okBase && okI && usdBase != 0) l.crossWad = Math.mulDiv(usdI, WAD, usdBase);
            try feed.pegOk(l.token) returns (bool peg) {
                l.pegOk = peg;
            } catch {}
        }
    }

    /// @dev `loan`'s checked price on the Router's price scale (its base units per poolAsset base unit, scaled by
    ///      1e36), from the two USD prices with one floor, the pool's own (`pairPrice36`); zero when its feed does not
    ///      answer.
    function _price36(IPriceFeed feed, address poolAsset, address loan) private view returns (uint256) {
        try feed.peekPair(poolAsset, loan) returns (bool ok, uint256 poolUsd, uint256 loanUsd, uint48) {
            if (ok) {
                return pairPrice36(poolUsd, loanUsd, IERC20Metadata(poolAsset).decimals(), IERC20Metadata(loan).decimals());
            }
        } catch {}
        return 0;
    }

    /// @dev `usd * m / loanUsd` floored; zero, an unchecked price, when it would not fit a word.
    function _scaled(uint256 usd, uint256 loanUsd, uint256 m) private pure returns (uint256) {
        if (loanUsd == 0 || usd / loanUsd >= type(uint256).max / m) return 0;
        return Math.mulDiv(usd, m, loanUsd);
    }

    /// @dev The Router's USD vector for venue `v`'s pair alone: its two tokens' checked USD prices from one read of the
    ///      pair, zero elsewhere, `tokenCount` long; empty where the pair does not answer or its price is unchecked.
    function _venueUsd(address pool, IMMRouter r, IMMRouter.VenueView memory v) private view returns (uint256[] memory usd) {
        (IMMRouter.TokenView memory c, IMMRouter.TokenView memory d) = (r.token(pool, v.coll), r.token(pool, v.debt));
        try IPriceFeed(IFLAMM(pool).priceFeed()).peekPair(c.token, d.token) returns (
            bool ok, uint256 collUsd, uint256 debtUsd, uint48
        ) {
            if (ok && pairPrice36(collUsd, debtUsd, c.decimals, d.decimals) != 0) {
                usd = new uint256[](r.tokenCount(pool));
                (usd[v.coll], usd[v.debt]) = (collUsd, debtUsd);
            }
        } catch {}
    }

    /// @notice Every venue slot, as `Venue` describes it. `venue.status` carries the Router's fence (`VENUE_FENCED`, a
    ///         venue its pool locked) beside the retirement.
    function venues(address pool) external view returns (Venue[] memory out) {
        IMMRouter r = IMMRouter(IFLAMM(pool).router());
        uint256 retired;
        try IFLAMM(pool).retiredVenues() returns (uint256 m) {
            retired = m;
        } catch {}
        uint256 fenced;
        try IFLAMMFence(pool).fencedVenues() returns (uint256 m) {
            fenced = m;
        } catch {}
        uint256 n = r.venueCount(pool);
        out = new Venue[](n);
        for (uint16 i; i < n; ++i) {
            Venue memory v = out[i];
            v.id = i;
            if ((retired >> i) & 1 != 0) {
                v.venue.status = (fenced >> i) & 1 != 0 ? VENUE_FENCED : VENUE_RETIRED;
                continue;
            }
            v.venue = r.venue(pool, i);
            (v.collateral, v.recognizedCollateral, v.supplied, v.recognizedSupplied, v.debt) = r.venuePosition(pool, i);
            try r.venueCapacity(pool, i) returns (IFinancingAccount.Capacity memory c) {
                v.freeLiquidity = c.borrowable;
            } catch {}
            uint256[] memory usd = _venueUsd(pool, r, v.venue);
            if (usd.length != 0) {
                try r.venueHealth(pool, i, usd) returns (uint256 h) {
                    (v.healthOk, v.healthWad) = (true, h);
                } catch {}
            }
        }
    }

    /// @notice An open fence (`IFLAMMFence`): its index (a venue id, or `32 + t` for token `t`'s custody) and record;
    ///         whether it holds a pool part, written off or not (`parted`: the pool's entries stay closed while an open
    ///         fence does, and NAV, where it reads, leaves that part out, or counts a kept share); whether that part is
    ///         a kept share (`kept`: fence word bit `160 + i`; the senior claims' part is then in `record.fee`'s low
    ///         120 bits, and anyone may clear it with `unwindFence`); and a holder's part of it, of `1e36`, senior and
    ///         junior parts summed, with what settling the whole part moves now (`claimAmounts`; zero once a kept share
    ///         is cleared, when the holder draws its pots with `settleClaim`).
    struct FenceView {
        uint256 index;
        IFLAMMFence.Fence record;
        bool parted;
        bool kept;
        uint256 part;
        uint256 collateralOut;
        uint256 supplyOut;
        uint256 debtIn;
    }

    /// @notice Every open fence of the pool, and `holder`'s claim on each (none read for the zero address); none on a
    ///         pool that serves no fence.
    function fences(address pool, address holder) external view returns (FenceView[] memory out) {
        IFLAMMFence p = IFLAMMFence(pool);
        uint256 w;
        try p.fences() returns (uint256 word) {
            w = word;
        } catch {
            return out;
        }
        uint256 open = (w & 0xffffffff) | (((w >> 32) & 0xffff) << 32);
        (, uint256 parts) = fenceParts(pool);
        uint256 n;
        for (uint256 m = open; m != 0; m &= m - 1) {
            ++n;
        }
        out = new FenceView[](n);
        uint256 j;
        for (uint256 i; i < 48; ++i) {
            if ((open >> i) & 1 == 0) continue;
            FenceView memory f = out[j++];
            (f.index, f.record, f.parted) = (i, p.fenceOf(i), (parts >> i) & 1 != 0);
            if (i < 32 && (w >> (160 + i)) & 1 != 0) (f.parted, f.kept) = (true, true);
            if (holder == address(0)) continue;
            f.part = p.claimOf(f.record.key, holder);
            if (f.part == 0) continue;
            try p.claimAmounts(f.record.key, holder) returns (uint256 c, uint256 s, uint256 d) {
                (f.collateralOut, f.supplyOut, f.debtIn) = (c, s, d);
            } catch {}
        }
    }

    /// @notice Whether the pool's fences leave its entries open, and the fences that close them
    ///         (`IFLAMMFence.partedFences`: bit `i` for venue `i`, `32 + t` for token `t`'s custody, `48 + i` for venue
    ///         `i`'s kept share), each holding a pool part, written off or not, which NAV, where it reads, leaves out
    ///         (a kept share it counts behind the senior claims) though every share owns its slice of it: no share should be issued or handed over at NAV while `parts` is not zero. Open, with none, on a
    ///         pool that serves no fence.
    function fenceParts(address pool) public view returns (bool entriesOpen, uint256 parts) {
        try IFLAMMFence(pool).partedFences() returns (uint256 m) {
            parts = m;
        } catch {}
        entriesOpen = parts == 0;
    }

    /// @notice The pool's quote of the pool book as it stands (the swap hook's curve or leverage fill, whichever
    ///         fills), which is the fill a swap landing now gets: a swap folds no print but the one its hook commits
    ///         itself, which the hook's preview folds in memory, so the quote is the swap's fill on the same state (but
    ///         for a sale the venue cannot fund, see `IFLAMM.previewSwap`, and for a clip of an input the pool found,
    ///         which reverts).
    function previewSwap(address pool, bool poolAssetIn, uint256 amountIn)
        external
        view
        returns (bool ok, uint256 amountInUsed, uint256 amountOut, uint256 feeWad)
    {
        (address a, address l) = (IFLAMM(pool).asset(), IFLAMM(pool).loanAsset());
        try IFLAMM(pool).previewSwap(poolAssetIn ? a : l, poolAssetIn ? l : a, amountIn) returns (
            uint256 used, uint256 out, uint256 fee
        ) {
            return (true, used, out, fee);
        } catch {}
    }

    // ------------------------------------------------------------------ the swap hook's leverage quote
    /// @notice The swap hook's leverage state on the context a swap builds now ({EverlongHook.levState}): its leverage
    ///         CR, the value of the hook's book over `debtWad` (debt plus the curve's stable side), at the hook's
    ///         anchor and at the feed (`crMarkWad`, `crFeedWad`), and each side's top of book. A side is active as the
    ///         hook flags it and while core's fee bounds admit the spread it charges there, which the hook's view does
    ///         not read: the lever-up's `spreadWad`; the lever-down's `spreadDnWad`, and its `spreadWad` too once
    ///         `debtWad` is at or under its value at a leverage CR of 2 on the anchor. It runs no observation, as
    ///         {previewSwap}.
    ///         `ok` false where core would not price a swap (`IFLAMM.hookContext` reverts): the pair does not answer
    ///         (a stale feed, the sequencer) or a price it needs is unchecked; and where the swap hook has no leverage
    ///         state (a hook other than `EverlongHook`).
    function levState(address pool) external view returns (bool ok, LeverageLib.State memory st) {
        PoolContext memory c;
        try IFLAMM(pool).hookContext() returns (PoolContext memory x) {
            c = x;
        } catch {
            return (false, st);
        }
        EverlongHook h = EverlongHook(IFLAMM(pool).hooks().hook);
        EverlongHook.Leverage memory l;
        try h.LOAN_SCALE() returns (uint256 k) {
            try h.levState(_request(pool, k, c)) returns (LeverageLib.State memory x) {
                st = x;
            } catch {
                return (false, st);
            }
            try h.params() returns (EverlongHook.Params memory pr) {
                l = pr.lev;
            } catch {
                return (false, st);
            }
        } catch {
            return (false, st);
        }
        ok = true;
        // Core's fee bounds on the hook pair: the pool's cap, and the higher of the pool's and token 1's floor.
        IFLAMM.Limits memory lim = IFLAMM(pool).limits();
        uint64 floor = IFLAMM(pool).tokenConfig(1).feeFloorWad;
        if (lim.feeFloorWad > floor) floor = lim.feeFloorWad;
        uint256 cap = lim.feeCapWad;
        st.upActive = st.upActive && l.spreadWad >= floor && l.spreadWad <= cap;
        // `d` (`debtWad`) over `t = ceil(B / 3)`, with `B` the greatest integer inside `3 (B + d)^2 = 8 B cv` (the
        // anchor the lever-down's curve takes), exactly when `3 d - 2` is outside it, the law's lower root being
        // under `d`
        uint256 d = st.debtWad;
        st.dnActive = st.dnActive && l.spreadDnWad >= floor && l.spreadDnWad <= cap
            && (l.spreadWad <= cap || Mul512.productGt(3, (4 * d - 2) * (4 * d - 2), 8 * (3 * d - 2), st.cvWad));
    }

    /// @notice The swap hook's leverage fill for a swap of `amountIn` (native units) landing now, on the request core
    ///         builds (`IFLAMM.pairRequest`; {EverlongHook.levQuote}, in the hook's units), and whether the swap fills
    ///         on it: `lev`, the hook's fill ({EverlongHook.quotePair}) is this one, which pays the taker more than the
    ///         curve's. Like the swap it runs no observation, so on the same state it is the swap's. `ok` false where
    ///         core refuses the request, and where the swap hook has no leverage state (a hook other than
    ///         `EverlongHook`).
    function levQuote(address pool, bool poolAssetIn, uint256 amountIn)
        external
        view
        returns (bool ok, bool lev, LeverageLib.Quote memory q)
    {
        PairRequest memory r;
        (address a, address l) = (IFLAMM(pool).asset(), IFLAMM(pool).loanAsset());
        try IFLAMM(pool).pairRequest(poolAssetIn ? a : l, poolAssetIn ? l : a, amountIn) returns (PairRequest memory x) {
            (ok, r) = (true, x);
        } catch {
            return (false, false, q);
        }
        EverlongHook h = EverlongHook(IFLAMM(pool).hooks().hook);
        uint256 k;
        try h.LOAN_SCALE() returns (uint256 x) {
            k = x;
        } catch {
            return (false, false, q);
        }
        try h.levQuote(r) returns (LeverageLib.Quote memory x) {
            q = x;
        } catch {
            return (false, false, q);
        }
        if (q.ok) {
            PairFill memory f = h.quotePair(r);
            // the quote in native units, as the hook converts its fill: a sale's output on token 1's grid, a buy's
            // input rounded up to it
            (uint256 used, uint256 gross, uint256 fee) = poolAssetIn
                ? (q.amountInUsed, q.grossOut / k, q.grossOut / k - (q.grossOut - q.feeOut) / k)
                : (Math.ceilDiv(q.amountInUsed, k), q.grossOut, q.feeOut);
            lev = f.amountInUsed == used && f.grossOut == gross && f.feeOut == fee && f.xAfter == q.book.x;
        }
    }

    /// @dev The pair request the hook reads for the observation context `c` core builds (`IFLAMM.hookContext`), for
    ///      the leverage state, which reads no swap (no amount in, no cap on the amount out, no fee bounds): the
    ///      context in native units (token 1's legs divided by the hook's `LOAN_SCALE`), with two USD prices on which
    ///      the hook rebuilds `c.priceN36` exactly (token 1 at the pool's share scale in WAD, the pool asset at the
    ///      reference) and the rest of the pool book at token 1's price. Its token addresses are not read.
    function _request(address pool, uint256 k, PoolContext memory c) private view returns (PairRequest memory r) {
        uint256 u1 = 10 ** (36 - IERC20Metadata(IFLAMM(pool).asset()).decimals());
        (r.heldOut, r.suppliedOut, r.postedOut, r.owedOut) = (c.baseHeld, c.baseSupplied, c.basePosted, c.baseOwed);
        (r.heldIn, r.suppliedIn, r.postedIn, r.owedIn) =
            (c.quoteHeld / k, c.quoteSupplied / k, c.quotePosted / k, c.quoteOwed / k);
        (r.indexIn, r.usdIn, r.usdOut) = (1, u1, c.priceN36);
        u1 /= WAD;
        (r.restHeldN18, r.restOwedN18) = (c.restHeldN18 * u1, c.restOwedN18 * u1);
        (r.bandWad, r.features) = (c.bandWad, uint16(c.features));
    }
}
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.