Skip to content
Verified contractExactUNLICENSED

FLAMMOpsLib

Address0x3bd2b976e70c0d6ea7eb041e36ad525f66f79a69
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 100 runs
EVM version
cancun
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,446,212
Creation transaction
0x69b6070ebf…105774ec5d
Libraries
src/core/mm/MMRouterLib.sol:MMRouterLib0xa474…d2b4e5src/core/flamm/FLAMMLane.sol:FLAMMLane0x82a0…7f67dfsrc/core/flamm/FLAMMRoute.sol:FLAMMRoute0x312e…0fdaa9src/periphery/FLAMMMaxima.sol:FLAMMMaxima0x4a99…d6259csrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0x5d47…27cc62src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x3bd2…f79a69src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xd53f…ed5983src/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0xac61…6a909dsrc/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0x2291…64f98csrc/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x7a11…58517bsrc/core/mm/CTokenMarketLib.sol:CTokenMarketLib0xfd87…6df060src/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0x4aac…e1aed6src/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x9e50…7eeb41src/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0xc6c9…da2afesrc/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0x739d…5a629fsrc/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0xf128…b16b70src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0xf284…efd526src/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0xd561…60c5a5src/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0xcda6…a4dcf7src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x8423…7adc96src/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0x6fe6…678097src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0x1834…56e060src/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xfaae…2511basrc/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x480f…4e0a81src/hooks/everlong/LeverageLib.sol:LeverageLib0x1b1d…40ad11src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0x5691…f4d380src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0xa0c8…50c3e3src/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xabe4…7426f7

52 files

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

src/core/flamm/FLAMMOpsLib.sol

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

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

import {
    FLAMMStore, NotCurator, Paused, Expired, InvalidConfig, HookInvalid, NoHookSetScheduled, HookSetNotReady,
    NotPaused, HookSetScheduled, HookSetCancelled, HookSetChanged, FeaturesSet, GuardianMayOnlyTighten,
    AnchorOutOfBounds, Observed, Recentered, DialsSet, FeeBoundsSet, TokenConfigSet, MinSupplyBatchSet,
    CeilingBreached, CeilingsSet, CeilingsScheduled, NoBand, BandSet, PriceUnchecked, NotScheduled, HookSetLocked,
    VenueFrozen, VenueReportsLoss, FeeKindsSynced, WAD
} from "src/core/flamm/FLAMMStore.sol";
import {FLAMMGateLib} from "src/core/flamm/FLAMMGateLib.sol";
import {FLAMMTopUpLib} from "src/core/flamm/FLAMMTopUpLib.sol";
import {FLAMMQuoteLib} from "src/core/flamm/FLAMMQuoteLib.sol";
import {FLAMMLane} from "src/core/flamm/FLAMMLane.sol";
import {FLAMMFlowLib} from "src/core/flamm/FLAMMFlowLib.sol";
import {FLAMMKeptLib} from "src/core/flamm/FLAMMKeptLib.sol";
import {IFLAMM} from "src/interfaces/core/flamm/IFLAMM.sol";
import {IMMRouter} from "src/interfaces/core/mm/IMMRouter.sol";
import {
    ObservationContext, PoolContext, IRecenterHook, IHookIdentity, HOOK_INTERFACE_VERSION,
    CONTEXT_PAIR_FORWARD, CONTEXT_PAIR_FORWARD_BORROWS, CONTEXT_PAIR_REVERSE, CONTEXT_PAIR_REVERSE_BORROWS,
    CONTEXT_PAIR_OTHER
} from "src/interfaces/core/flamm/IFLAMMHooks.sol";
import {
    HOOK_CAP_UNPRICED, HOOK_CAP_CUSTODY_FILL, HOOK_CAP_FOLD_ONLY
} from "src/interfaces/core/flamm/IHookCapabilities.sol";
import {IPairHook, HOOK_CAP_ROTATE} from "src/interfaces/core/flamm/IPairHook.sol";
import {ReentrancyGuardLib} from "src/libraries/ReentrancyGuardLib.sol";

/// @notice Governance and observation: the token, pair and pool setters, the dials, the committed ceilings, the
///         market band, the hook-set ceremony, the features, `poke` and `recenter`, the observation they hand the
///         swap hook, and the records' views, which `FLAMMFront`'s fallback routes here with the pool's own selectors.
///         None of it runs on a swap, an entry or an exit.
library FLAMMOpsLib {
    /// @dev `IFLAMMLaneFactory.pegGroupOf`'s selector ({syncKinds}).
    bytes4 private constant PEG_GROUP_OF = bytes4(keccak256("pegGroupOf(address)"));

    // ------------------------------------------------------------------ the entries' callers and the lock
    // Each entry the pool's dispatch table routes here checks its own caller and holds the pool's lock, in the
    // order its modifiers stand.

    /// @dev The curator or the pool's guardian (`NotGuardianOrCurator`).
    modifier curatorOrGuardian() {
        FLAMMStore.curatorOrGuardian(FLAMMStore.s());
        _;
    }

    /// @dev The pool's lock, taken for the entry and cleared when it returns.
    modifier nonReentrant() {
        ReentrancyGuardLib._guard();
        _;
        ReentrancyGuardLib._unlockGuard();
    }

    // ------------------------------------------------------------------ observation lifecycle
    /// @dev Anyone may poke: it forwards the feed's print to the recenter hook, which folds it. A swap runs no
    ///      observation (`EverlongHook` prices a swap on its folds as stored), so the folds follow the feed as far
    ///      as pokes and recenters forward it. Every print goes: the hook dedupes, and a moved price can carry an
    ///      already-consumed stamp. Every swap hook declares `HOOK_CAP_FOLD_ONLY` ({checkHookSet}): its fold moves
    ///      nothing its spot reads, so a poke reprices nothing and core reads no spot around it. A pool with no band
    ///      reads no price, so it has no print to forward: it refuses (`NoBand`), and its anchor moves by `recenter`
    ///      alone. Under the pool's lock, which it takes here (`FLAMMFront`'s fallback reaches it with no check). It
    ///      reads no book: the context it hands carries every leg zero ({observationContext}).
    function poke(FLAMMStore.S storage $) public {
        ReentrancyGuardLib._guard();
        if ($.paused) revert Paused();
        if (FLAMMStore.bandOff($)) revert NoBand();
        ObservationContext memory o = observationContext($, false);
        IRecenterHook($.invariantHook).observe(o);
        emit Observed(o.referenceN36, o.observedAt);
        ReentrancyGuardLib._unlockGuard();
    }

    /// @dev The keeper, the curator or the controller hook (`NotKeeperOrCurator`), then the lock, as a dispatched
    ///      entry's modifiers run them, here (`FLAMMFront`'s fallback reaches it with no check). The caller's anchor
    ///      bounds hold the anchor the hook returns. A pool with no band reads no price: its hook recenters with no
    ///      reference (`referenceN36` and `observedAt` zero), inside those bounds alone.
    function recenter(FLAMMStore.S storage $, uint256 minAnchorN36, uint256 maxAnchorN36, uint256 deadline) public {
        FLAMMStore.requireKeeperOrCurator($, true);
        ReentrancyGuardLib._guard();
        if ($.paused) revert Paused();
        if (block.timestamp > deadline) revert Expired();
        if (minAnchorN36 > maxAnchorN36) revert InvalidConfig();
        // a plain key's own transaction reads the loss marks here where a witnessed reading is due
        // (`FLAMMStore.lossWitness`), so the keeper's frequent call keeps them; any other call reads none here
        if (FLAMMStore.lossWitness($)) FLAMMKeptLib.recordLossMarks();
        ObservationContext memory o = observationContext($, true);
        (bool moved, uint256 anchorN36) = IRecenterHook($.invariantHook).recenter(o);
        if (moved && (anchorN36 < minAnchorN36 || anchorN36 > maxAnchorN36)) revert AnchorOutOfBounds();
        emit Recentered(o.referenceN36, o.observedAt, moved, anchorN36);
        ReentrancyGuardLib._unlockGuard();
    }

    // ------------------------------------------------------------------ the observation
    /// @notice The observation a poke or a recenter hands the recenter hook, priced by one read of the hook pair with
    ///         the reverting `pair` (a stale feed or a downed sequencer reverts with the feed's error): its reference,
    ///         token 1's N36 (its value at 36 decimals per pool-asset base unit, from the two USD prices) and its stamp
    ///         are that read's. With `legs` (a recenter) its context is the book that read prices ({poolContext}),
    ///         every token holding a leg priced (an idle token adds nothing to it); without (a poke) no book is read,
    ///         and the context carries the hook pair's N36, the band, the pairs and the features, every leg zero. A
    ///         pool with no band reads no price: the reference and the stamp are zero.
    function observationContext(FLAMMStore.S storage $, bool legs) internal view returns (ObservationContext memory o) {
        uint256 u0;
        uint256 u1;
        bool unpriced = FLAMMStore.bandOff($);
        if (!unpriced) {
            uint256 stamp;
            (u0, u1, stamp) = FLAMMGateLib.pairRead(address($.priceFeed), $.poolAsset, $.tokens[1].token);
            (o.referenceN36, o.observedAt) = (Math.mulDiv(u0, uint256($.shareScale) * WAD, u1), uint48(stamp));
        }
        if (!legs) {
            _contextTerms($, o.referenceN36, o.pool);
            return o;
        }
        FLAMMGateLib.Book memory b = FLAMMGateLib.bookOf($);
        if (!unpriced) FLAMMGateLib.priceInAt($, b, u0, u1, true);
        poolContext($, b, o.referenceN36, o.pool);
    }

    /// @notice As `IFLAMM.hookContext`.
    /// @dev With no market band it reads no price and hands no reference (`priceN36` zero), as the swaps do.
    ///      The pool context a recenter hands the recenter hook now, reading no price of an
    ///      idle token; a poke hands its print, band, pairs and features with every leg zero.
    function hookContext() public view returns (PoolContext memory) {
        ReentrancyGuardLib._readGuard();
        FLAMMStore.S storage $ = FLAMMStore.s();
        return observationContext($, true).pool;
    }

    /// @notice The pool context into `c`, a zeroed `PoolContext` the caller holds: the pool asset's legs native, token
    ///         1's in N18, every other token summed in N18 at its unrounded USD cross with token 1, holdings rounded
    ///         down and debt up, leg by leg; the hook pair's N36, token 1's band, the listed pairs' `CONTEXT_PAIR_*`
    ///         bits and the features. Reverts `PriceUnchecked` where a token past token 1 holds a leg at an unchecked
    ///         cross.
    function poolContext(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 priceN36, PoolContext memory c)
        internal
        view
    {
        FLAMMGateLib.Leg memory L = b.legs[0];
        (c.baseHeld, c.baseSupplied, c.basePosted, c.baseOwed) = (L.held, L.supplied, L.posted, L.owed);
        L = b.legs[1];
        uint256 sc = L.scale;
        (c.quoteHeld, c.quoteSupplied, c.quotePosted, c.quoteOwed) = (L.held * sc, L.supplied * sc, L.posted * sc, L.owed * sc);
        uint256 den = b.usd[1];
        for (uint256 t = 2; t < b.legs.length; ++t) {
            L = b.legs[t];
            uint256 pos = L.held | L.supplied | L.posted;
            if ((pos | L.owed) == 0) continue;
            uint256 num = b.usd[t];
            if (num == 0 || den == 0) revert PriceUnchecked();
            sc = L.scale;
            c.restHeldN18 += Math.mulDiv(L.held * sc, num, den) + Math.mulDiv(L.supplied * sc, num, den)
                + Math.mulDiv(L.posted * sc, num, den);
            c.restOwedN18 += Math.mulDiv(L.owed * sc, num, den, Math.Rounding.Up);
        }
        _contextTerms($, priceN36, c);
    }

    /// @dev The context's terms beside the legs into `c`: the hook pair's N36, token 1's band, the features and the
    ///      listed pairs' `CONTEXT_PAIR_*` bits.
    function _contextTerms(FLAMMStore.S storage $, uint256 priceN36, PoolContext memory c) private view {
        (c.priceN36, c.bandWad, c.features) = (priceN36, $.tokens[1].swapPriceBandWad, $.features);
        c.pairs = contextPairs($);
    }

    /// @notice The listed pairs' `CONTEXT_PAIR_*` bits: which of the forward and the reverse pair are live and borrow,
    ///         and whether another live pair owes the pool asset or posts a token past it.
    function contextPairs(FLAMMStore.S storage $) internal view returns (uint32 bits) {
        uint256 n = $.pairCount;
        for (uint256 p; p < n; ++p) {
            FLAMMStore.PairCfg storage pc = $.pairs[p];
            if (!pc.live) continue;
            (uint8 a, uint8 c, bool on) = (pc.coll, pc.debt, !pc.borrowOff);
            if (a == 0 && c == 1) {
                bits |= on ? CONTEXT_PAIR_FORWARD | CONTEXT_PAIR_FORWARD_BORROWS : CONTEXT_PAIR_FORWARD;
            } else if (a == 1 && c == 0) {
                bits |= on ? CONTEXT_PAIR_REVERSE | CONTEXT_PAIR_REVERSE_BORROWS : CONTEXT_PAIR_REVERSE;
            } else if (a != 0 || c == 0) {
                bits |= CONTEXT_PAIR_OTHER;
            }
        }
    }

    // ------------------------------------------------------------------ the records' views (the pool's own selectors)
    /// @dev The `FEATURE_*` switches alone: the custody-blind law's bit (`FLAMMStore.CUSTODY_BLIND`) reads through
    ///      `FLAMMFloatLib.custodyBlind`.
    function switches() public view returns (uint256 featureBits, uint32 delaySec) {
        FLAMMStore.S storage $ = FLAMMStore.s();
        return ($.features & FLAMMStore.FEATURES_ALL, $.governanceDelaySec);
    }

    /// @notice Whether the pool is paused (`FLAMM.setPaused`).
    function paused() public view returns (bool) {
        return FLAMMStore.s().paused;
    }

    /// @notice Token `t`'s record (`IFLAMM.TokenConfig`), `held` its tracked custody, the fee kept for the protocol
    ///         included; `BadTokenIndex` past the list.
    function tokenConfig(uint8 t) public view returns (IFLAMM.TokenConfig memory) {
        FLAMMStore.S storage $ = FLAMMStore.s();
        FLAMMStore.checkToken($, t);
        FLAMMStore.TokenCfg storage c = $.tokens[t];
        return IFLAMM.TokenConfig(
            c.token,
            c.decimals,
            c.swapPriceBandWad,
            c.feeFloorWad,
            c.maxSwapNotional,
            c.reserveTarget,
            c.minSupplyBatch,
            FLAMMStore.heldOf($, t),
            c.partner,
            c.pairId,
            c.debtFree
        );
    }

    /// @notice Pair `p`'s record (`IFLAMM.PairConfig`); `BadPairIndex` past the list.
    function pairConfig(uint8 p) public view returns (IFLAMM.PairConfig memory) {
        FLAMMStore.S storage $ = FLAMMStore.s();
        FLAMMStore.checkPair($, p);
        FLAMMStore.PairCfg storage c = $.pairs[p];
        return IFLAMM.PairConfig(
            c.coll,
            c.debt,
            c.ltvWad,
            c.phiWad,
            c.roomEpsilonWad,
            c.ltvMinWad,
            c.ltvMaxWad,
            c.phiMinWad,
            c.phiMaxWad,
            c.ltvMaxStepWad,
            c.minStructDistWad,
            c.ltvCooldownSec,
            c.lastDialMoveTs,
            c.borrowOff,
            c.live
        );
    }

    /// @notice Token `t`'s four legs in base units (`FLAMMGateLib.positionOf`): the custody the pool owns, the fee kept
    ///         for the protocol left out, what it supplies and posts, and what it owes; `BadTokenIndex` past the list.
    function position(uint8 t) public view returns (uint256 held, uint256 supplied, uint256 posted, uint256 owed) {
        return FLAMMGateLib.positionOf(FLAMMStore.s(), t);
    }

    /// @notice Token `t`'s collateral reserve rule (`FLAMMPolicyLib.setCollateralReserve`): the venue it names and its reserve,
    ///         zero while it is off; `BadTokenIndex` past the list.
    function collateralReserve(uint8 t) public view returns (uint16 venueId, uint128 reserve) {
        FLAMMStore.S storage $ = FLAMMStore.s();
        FLAMMStore.checkToken($, t);
        FLAMMStore.CollateralReserve storage r = $.reserves[t];
        return (r.venueId, r.reserve);
    }

    /// @dev An entry past its window has lapsed: none, as the identical call schedules it again.
    function pending(bytes32 h) public view returns (uint48 dueAt) {
        FLAMMStore.S storage $ = FLAMMStore.s();
        uint256 due = $.pending[h];
        if (block.timestamp > due + FLAMMStore.executionWindow($.governanceDelaySec)) due = 0;
        return uint48(due);
    }

    // ------------------------------------------------------------------ the hook-set ceremony
    /// @dev The swap hook is one contract in every role (fails closed): it prices every pair and its own fee, and its
    ///      recenter role moves the anchor of the book it prices; it must declare `HOOK_CAP_FOLD_ONLY`, so no poke
    ///      reprices it ({poke}). The controller is optional and silent-capable.
    function checkHookSet(IFLAMM.HookSet memory hookSet) internal view {
        address hook = hookSet.hook;
        checkIdentity(hook, true);
        if (FLAMMGateLib.capabilities(hook) & HOOK_CAP_FOLD_ONLY == 0) revert HookInvalid();
        if (hookSet.controller != address(0)) checkIdentity(hookSet.controller, false);
    }

    /// @dev Reverts `HookInvalid` unless the hook has code and meets {IHookIdentity}'s rules for its role: a hook that
    ///      prices (`writes`, the swap hook and a pair hook alike) names this pool and answers the interface version.
    function checkIdentity(address hook, bool writes) internal view {
        if (hook.code.length == 0) revert HookInvalid();
        try IHookIdentity(hook).boundPool() returns (address bound) {
            if (bound != address(this) && (writes || bound != address(0))) revert HookInvalid();
        } catch {
            if (writes) revert HookInvalid();
        }
        try IHookIdentity(hook).hookInterfaceVersion() returns (uint16 v) {
            if (v != HOOK_INTERFACE_VERSION) revert HookInvalid();
        } catch {
            if (writes) revert HookInvalid();
        }
    }

    /// @dev Installs the set, records the swap's capability bits ({syncCapabilities}) and asks which pairs each hook
    ///      prices (`FLAMMLane.syncPairs`).
    function install(FLAMMStore.S storage $, IFLAMM.HookSet memory h) public {
        $.invariantHook = h.hook;
        $.controllerHook = h.controller;
        syncCapabilities($);
        FLAMMLane.syncPairs($);
    }

    /// @notice Rewrites which of the pool's pairs are correlated (`FLAMMStore.S.feeRates` from
    ///         `FLAMMStore.KIND_SHIFT`): a pair of two tokens the Factory tags with the same nonzero peg group
    ///         (`IFLAMMLaneFactory.pegGroupOf`, a failed or short answer reading none), which then owes the correlated
    ///         pairs' notional rate. Run where a token is listed, the pool's genesis included, and by anyone after
    ///         (`FLAMMFloatLib.syncFeeKinds`); logs the kinds where they change.
    function syncKinds(FLAMMStore.S storage $) public {
        (address f, uint256 n) = ($.factory, $.tokenCount);
        uint256[] memory g = new uint256[](n);
        uint256 kinds;
        for (uint256 j; j < n; ++j) {
            uint256 gj = _pegGroup(f, FLAMMStore.tokenOf($, j));
            g[j] = gj;
            if (gj == 0) continue;
            for (uint256 i; i < j; ++i) {
                if (g[i] == gj) kinds |= uint256(1) << (j * (j - 1) / 2 + i);
            }
        }
        uint256 w = $.feeRates;
        uint256 next = (w & FLAMMStore.RATES_MASK) | (kinds << FLAMMStore.KIND_SHIFT);
        if (next == w) return;
        $.feeRates = next;
        emit FeeKindsSynced(kinds);
    }

    /// @dev Token `t`'s peg group at the Factory `f` (`IFLAMMLaneFactory.pegGroupOf`): zero where the call fails or
    ///      answers short.
    function _pegGroup(address f, address t) private view returns (uint256 g) {
        bytes4 sel = PEG_GROUP_OF;
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, sel)
            mstore(add(m, 4), t)
            let ok := staticcall(gas(), f, m, 0x24, 0, 0x20)
            if and(ok, gt(returndatasize(), 0x1f)) { g := and(mload(0), 0xffff) }
        }
    }

    /// @notice Records the swap's capability bits from the hooks' declarations, read once here so no swap reads them:
    ///         rotations (`HOOK_CAP_ROTATE`) and fills from custody alone (`HOOK_CAP_CUSTODY_FILL`), each where the
    ///         swap hook declares it and, while a pair hook is set (`SWAP_PAIR_HOOK`), the pair hook too. Run at each
    ///         installation of either hook.
    function syncCapabilities(FLAMMStore.S storage $) public {
        uint8 bits = $.swapBits;
        uint256 caps = FLAMMGateLib.capabilities($.invariantHook);
        if (bits & FLAMMStore.SWAP_PAIR_HOOK != 0) caps &= FLAMMGateLib.capabilities(address(uint160($.pairHookWord)));
        bits &= ~(FLAMMStore.SWAP_HOOK_ROTATE | FLAMMStore.SWAP_HOOK_CUSTODY);
        if (caps & HOOK_CAP_ROTATE != 0) bits |= FLAMMStore.SWAP_HOOK_ROTATE;
        if (caps & HOOK_CAP_CUSTODY_FILL != 0) bits |= FLAMMStore.SWAP_HOOK_CUSTODY;
        $.swapBits = bits;
    }

    // ------------------------------------------------------------------ pair masks
    /// @notice Rebuilds, from the pair records: each token's pair masks (the live pairs that owe it and those that post
    ///         it), the partner cache (the one live pair that owes a token, `MANY` with two or more, its first in
    ///         `pairId`, `NO_PARTNER` with none, each token's word written only where it moves), the live pairs whose
    ///         debt token has another live pair (`S.multiPairs`), and the pool's shape bits: some token with two or
    ///         more live pairs (`POOL_MULTI`), some live pair borrowing (`POOL_BORROWS`), some live pair owing the pool
    ///         asset or posting a token past it (`POOL_TWO_SIDED`). Run at genesis and at each pair's admission,
    ///         retirement and borrow switch, the only paths that move them.
    function syncLanes(FLAMMStore.S storage $) public {
        (uint256 n, uint256 m) = ($.pairCount, $.tokenCount);
        uint256[4] memory lanes;
        uint256[16] memory owing; // per token: how many live pairs owe it, and the first one's coll and index
        uint8 bits;
        for (uint256 p; p < n; ++p) {
            FLAMMStore.PairCfg storage pc = $.pairs[p];
            if (!pc.live) continue;
            (uint8 a, uint8 c, bool off) = (pc.coll, pc.debt, pc.borrowOff);
            lanes[c >> 2] |= (uint256(1) << p) << (64 * (c & 3));
            lanes[a >> 2] |= (uint256(1) << p) << (64 * (a & 3) + 32);
            uint256 o = owing[c];
            owing[c] = o == 0 ? (uint256(1) << 16) | (uint256(a) << 8) | p : o + (uint256(1) << 16);
            if (!off) bits |= FLAMMStore.POOL_BORROWS;
            if (a != 0 || c == 0) bits |= FLAMMStore.POOL_TWO_SIDED;
        }
        uint32 multi;
        for (uint256 p; p < n; ++p) {
            FLAMMStore.PairCfg storage pc = $.pairs[p];
            if (pc.live && owing[pc.debt] >> 16 >= 2) multi |= uint32(1) << p;
        }
        for (uint256 t; t < m; ++t) {
            uint256 o = owing[t];
            FLAMMStore.TokenCfg storage c = $.tokens[t];
            uint8 partner = o == 0 ? FLAMMStore.NO_PARTNER : o >> 16 >= 2 ? FLAMMStore.MANY : uint8(o >> 8);
            if (c.partner != partner) c.partner = partner;
            if (o != 0 && c.pairId != uint8(o)) c.pairId = uint8(o);
        }
        for (uint256 w; w < 4 && w * 4 < m; ++w) {
            if ($.pairLanes[w] != lanes[w]) $.pairLanes[w] = lanes[w];
        }
        if (multi != 0) bits |= FLAMMStore.POOL_MULTI;
        $.multiPairs = multi;
        // only the pairs' shape is this path's: every other bit stays as its own path left it (the pool asset's
        // policy, the reserve switch, the spread fee owed, the record of what exits forfeited)
        uint8 shape = FLAMMStore.POOL_MULTI | FLAMMStore.POOL_BORROWS | FLAMMStore.POOL_TWO_SIDED;
        $.poolBits = ($.poolBits & ~shape) | bits;
    }

    // ------------------------------------------------------------------ the hook-set ceremony's schedule
    /// @dev Validated here and again at execution; a reschedule replaces the pending set and restarts the delay. The
    ///      swap hook must meet the band mode and the pairs listed now, as at execution ({FLAMMGateLib.checkHook}):
    ///      with no band it must declare `HOOK_CAP_UNPRICED`, and while a pair that owes the pool asset or posts
    ///      another token is listed, `HOOK_CAP_TWO_SIDED`. It records the schedule plus `governanceDelaySec`, and its
    ///      event carries {hookSetDue}.
    function scheduleHookSet(IFLAMM.HookSet calldata hookSet) public {
        FLAMMStore.S storage $ = FLAMMStore.s();
        _hookSetOpen($);
        checkHookSet(hookSet);
        FLAMMGateLib.checkHook($, hookSet.hook);
        $.pendingHookSetHash = keccak256(abi.encode(hookSet));
        $.hookSetExecutableAt = uint48(block.timestamp + $.governanceDelaySec);
        emit HookSetScheduled(hookSet, hookSetDue($), msg.sender);
    }

    /// @notice When the scheduled set may execute, zero when none: `governanceDelaySec` after its schedule, and
    ///         `FLAMMStore.MIN_BAND_DELAY_SEC` at least while the band's committed ceiling admits no band or a raise to
    ///         that ceiling is scheduled. The pool then has no band, or may drop it before the set lands, and its swap
    ///         hook would be its only price check. A band attached under that ceiling can go again at once, so it
    ///         shortens nothing until the ceiling is cut.
    /// @dev Read as the band stands, at execution too: a set scheduled with a band waits the longer delay once the band
    ///      may go, and one scheduled without waits `governanceDelaySec` once the ceiling keeps a band.
    ///      `hookSetExecutableAt` holds the schedule plus `governanceDelaySec`, which is write-once, so the schedule
    ///      reads back exactly.
    function hookSetDue(FLAMMStore.S storage $) internal view returns (uint48 due) {
        due = $.hookSetExecutableAt;
        uint256 delay = $.governanceDelaySec;
        if (due == 0 || delay >= FLAMMStore.MIN_BAND_DELAY_SEC) return due;
        uint64 none = FLAMMStore.NO_BAND_CEILING;
        if ($.bandCeilingWad == none || $.pendingBandCeilingWad == none) {
            due += uint48(FLAMMStore.MIN_BAND_DELAY_SEC - delay);
        }
    }

    /// @notice The scheduled hook set, as `keccak256(abi.encode(set))`, and when it executes; a zero hash means none.
    ///         The time is read as the band stands: ten days at least after its schedule while the pool may run with no
    ///         band (`scheduleHookSet`).
    function pendingHookSet() public view returns (bytes32 hookSetHash, uint48 executableAt) {
        FLAMMStore.S storage $ = FLAMMStore.s();
        return ($.pendingHookSetHash, hookSetDue($));
    }

    /// @notice The curator or the guardian cancels the scheduled set.
    /// @dev Drops the scheduled set; `NoHookSetScheduled` where none is.
    function cancelHookSet() public curatorOrGuardian nonReentrant {
        FLAMMStore.S storage $ = FLAMMStore.s();
        if ($.pendingHookSetHash == bytes32(0)) revert NoHookSetScheduled();
        _clearPendingHookSet($);
        emit HookSetCancelled(msg.sender);
    }

    /// @dev Requires the pause so no fill straddles the change. The swap hook it installs must meet the band mode and
    ///      the pairs listed now ({FLAMMGateLib.checkHook}).
    function executeHookSet(IFLAMM.HookSet calldata next) public {
        FLAMMStore.S storage $ = FLAMMStore.s();
        _hookSetOpen($);
        if (keccak256(abi.encode(next)) != $.pendingHookSetHash) revert NoHookSetScheduled();
        if (block.timestamp < hookSetDue($)) revert HookSetNotReady();
        if (!$.paused) revert NotPaused();
        checkHookSet(next);
        FLAMMGateLib.checkHook($, next.hook);
        if (next.hook != $.invariantHook && $.features & FLAMMStore.FEATURE_LEVERAGE != 0) {
            // A new swap hook starts from its constructor book and anchor, not the old hook's: cleared, the bit
            // leaves it unarmed, so it quotes no leverage fill either way until the curator re-arms.
            $.features &= uint16(~FLAMMStore.FEATURE_LEVERAGE);
            emit FeaturesSet($.features, msg.sender);
        }
        install($, next);
        _clearPendingHookSet($);
        emit HookSetChanged(next);
    }

    /// @dev A pool whose cheap lane is on keeps its front as its hook for life (`HookSetLocked`): the front's price
    ///      fence and meter must not sit in a hook its curator can replace.
    function _hookSetOpen(FLAMMStore.S storage $) private view {
        if ($.swapBits & FLAMMStore.SWAP_LANE != 0) revert HookSetLocked();
    }

    function _clearPendingHookSet(FLAMMStore.S storage $) private {
        delete $.pendingHookSetHash;
        delete $.hookSetExecutableAt;
    }

    // ------------------------------------------------------------------ the market band
    /// @notice `FLAMM.setMarketBand`: the market band's switch. `off` drops it (`bandWad` zero): the curator's alone,
    ///         once the band's committed ceiling admits no band (`FLAMMStore.NO_BAND_CEILING`, a raise that waits at
    ///         least `MIN_BAND_DELAY_SEC`), and only with no debt in any token, no fence holding a pool part
    ///         (`FLAMMStore.parted`, whose venue's debt the book leaves out), every pair's borrowing off, two tokens
    ///         and a hook that prices without a reference; while a fee rate is on, only after a skim that read the
    ///         fee mark (`PriceUnchecked` otherwise), so the gain made under the band is charged before the attach
    ///         that follows restarts the mark past it. Else `bandWad`, in (0, MAX], is attached to a pool with none: a
    ///         tightening, the curator's or the guardian's, at once, which admits the prices now, as a priced pool's
    ///         birth does, keeps every live pair's pin within what the band and the protocol's part keep
    ///         (`FLAMMStore.coverSafe`; `InvalidConfig` otherwise), as a wider band does, and restarts the fee mark at
    ///         the share price it finds. A band in force moves through token 1's config. `guardian`: the caller is the
    ///         guardian; `marked`: the caller's skim read the fee mark; `supply`: the share supply after that skim.
    function setMarketBand(FLAMMStore.S storage $, bool off, uint64 bandWad, bool guardian, bool marked, uint256 supply)
        public
    {
        bool none = $.noBand;
        if (off ? (bandWad != 0 || none) : (bandWad == 0 || bandWad > FLAMMStore.MAX_SWAP_PRICE_BAND_WAD || !none)) {
            revert InvalidConfig();
        }
        if (off) {
            if (guardian) revert GuardianMayOnlyTighten();
            if ($.bandCeilingWad != FLAMMStore.NO_BAND_CEILING) revert CeilingBreached();
            // a gain the skim could not read would go uncharged: the next attach restarts the fee mark past it
            if (!marked && ($.performanceFeeBp | $.protocolFeeBp) != 0) revert PriceUnchecked();
            // nor while a fence holds a pool part: the book leaves a fenced venue's debt out, and its lift would
            // bring that debt back into a pool that reads no price
            if ($.tokenCount != 2 || FLAMMStore.parted($) || FLAMMGateLib.owes(FLAMMGateLib.bookOf($))) {
                revert InvalidConfig();
            }
            // no live pair borrows
            if ($.poolBits & FLAMMStore.POOL_BORROWS != 0) revert InvalidConfig();
            FLAMMGateLib.requireCapability($.invariantHook, HOOK_CAP_UNPRICED);
        } else {
            // the fee mark restarts at the share price the attach finds: a frozen venue mark is no price to restart it
            // at while a rate is on, nor one that leaves out a fence's part (its return would read as a gain past the
            // restart); with both off, the first skim that reads the fee mark moves it before any rise applies
            if (($.performanceFeeBp | $.protocolFeeBp) != 0 && (FLAMMStore.parted($) || FLAMMGateLib.isFrozen($))) {
                revert VenueFrozen();
            }
            // A pool with no band has two tokens. The feed prices no unlisted token, which the admission refuses; a
            // live pair is the forward or the reverse one, and both directions of its price are admitted at once.
            FLAMMGateLib.admitToken($, 1);
            if (contextPairs($) & (CONTEXT_PAIR_FORWARD | CONTEXT_PAIR_REVERSE) != 0) FLAMMGateLib.admitPair($, 0, 1);
        }
        ($.noBand, $.tokens[1].swapPriceBandWad) = (off, bandWad);
        if (!off) {
            // the band attached keeps every live pair at an LTV its covers cannot raise past its cap
            FLAMMQuoteLib.pinsWithinBand($, 1);
            _restartMark($, supply);
        }
        emit BandSet(off, bandWad, msg.sender);
    }

    /// @dev The fee abstained while the pool had no band, so its fee mark restarts at the price the band attached to
    ///      it first finds (the share price, or against a cheap-lane pool's deposit basket its ratio,
    ///      `FLAMMGateLib.tryMarkedTotalAssets`), never below the fee mark it had, raised by what exits forfeited at
    ///      frozen venue marks since it last read, which leaves the record: value the pool held before it had a price
    ///      is not a gain.
    function _restartMark(FLAMMStore.S storage $, uint256 supply) private {
        (bool ok, uint256 assets, uint256 forfeit) = FLAMMGateLib.tryMarkedTotalAssets($);
        if (!ok || supply == 0) return;
        uint256 cur = Math.mulDiv(assets, WAD, supply);
        if (forfeit != 0) {
            uint256 peak = $.peakSharePriceWad + forfeit;
            FLAMMStore.takeForfeit($, cur > peak ? cur : peak);
        } else if (cur > $.peakSharePriceWad && cur <= type(uint128).max) {
            $.peakSharePriceWad = uint128(cur);
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {
    "src/core/mm/MMRouterLib.sol": {
      "MMRouterLib": "0xA4749766934833DfBeaF4Fc0d79c150A1Dd2B4E5"
    },
    "src/core/flamm/FLAMMLane.sol": {
      "FLAMMLane": "0x82a048459DF53186031Fd66507B260EeaC7F67df"
    },
    "src/core/flamm/FLAMMRoute.sol": {
      "FLAMMRoute": "0x312ee92ecd113F925dD513d450b062C8740fDaA9"
    },
    "src/periphery/FLAMMMaxima.sol": {
      "FLAMMMaxima": "0x4A997343D91c981BF63274fc222AA96D32d6259c"
    },
    "src/core/flamm/FLAMMLawLib.sol": {
      "FLAMMLawLib": "0x5D473B15E032756Cd81fc66B8F1e9BE2f427cc62"
    },
    "src/core/flamm/FLAMMOpsLib.sol": {
      "FLAMMOpsLib": "0x3Bd2B976e70C0D6ea7eb041e36ad525F66F79A69"
    },
    "src/core/mm/AaveV3ReadsLib.sol": {
      "AaveV3ReadsLib": "0xD53F6170226A74D453e84414Ffc2FFcE5ded5983"
    },
    "src/core/flamm/FLAMMFlowLib.sol": {
      "FLAMMFlowLib": "0xAC619698656d47651EF67a050859578e176A909D"
    },
    "src/core/flamm/FLAMMGateLib.sol": {
      "FLAMMGateLib": "0x2291F5e012B0740468E2e2E9AeA37F7Fea64F98c"
    },
    "src/core/flamm/FLAMMKeptLib.sol": {
      "FLAMMKeptLib": "0x7a11899232dd9F17c28bF062Ec2ee2267158517b"
    },
    "src/core/mm/CTokenMarketLib.sol": {
      "CTokenMarketLib": "0xfD87dcDDdc9b4eCe3F2413A858B265D8Ec6dF060"
    },
    "src/core/flamm/FLAMMAdmitLib.sol": {
      "FLAMMAdmitLib": "0x4AAcA346B9430656eB1316094cea0Df0f2e1AED6"
    },
    "src/core/flamm/FLAMMBlindLib.sol": {
      "FLAMMBlindLib": "0x9E5010D8393EB299b6FEce8EB160b3826f7eEb41"
    },
    "src/core/flamm/FLAMMClaimLib.sol": {
      "FLAMMClaimLib": "0xC6C94A120AC43f689BD8D8444dFf300eb9Da2aFe"
    },
    "src/core/flamm/FLAMMFenceLib.sol": {
      "FLAMMFenceLib": "0x739D84c7662030d5Ed8C6BA7606152977D5A629f"
    },
    "src/core/flamm/FLAMMFloatLib.sol": {
      "FLAMMFloatLib": "0xf128B7AdB5bF43814D595E3d1fC95a1f2bB16b70"
    },
    "src/core/flamm/FLAMMQuoteLib.sol": {
      "FLAMMQuoteLib": "0xF284B0271EA829F3a15f005BB588b7Df4bEFd526"
    },
    "src/core/flamm/FLAMMTopUpLib.sol": {
      "FLAMMTopUpLib": "0xD56127118C7619e4a13713Fb4280Cf66D560C5A5"
    },
    "src/core/mm/CTokenRewardsLib.sol": {
      "CTokenRewardsLib": "0xcda63d7eCCF838F2732Bff676706BDE5abA4DcF7"
    },
    "src/core/mm/MMRouterAdminLib.sol": {
      "MMRouterAdminLib": "0x8423744b3F304ED0B43043d7ad4E7d8A247aDc96"
    },
    "src/core/flamm/FLAMMPolicyLib.sol": {
      "FLAMMPolicyLib": "0x6FE69Ed6659A547da6100225Cd0616CfDB678097"
    },
    "src/core/flamm/FLAMMSettleLib.sol": {
      "FLAMMSettleLib": "0x1834d367BD65AF7CCf41D2025758bB69Af56e060"
    },
    "src/core/flamm/FLAMMSharedLib.sol": {
      "FLAMMSharedLib": "0xFaAEd38962aEb6c282Ac36E0cdE9313AbA2511ba"
    },
    "src/periphery/FLAMMExitMaxima.sol": {
      "FLAMMExitMaxima": "0x480f51866554e92649c9d3502bA31AA4234e0a81"
    },
    "src/hooks/everlong/LeverageLib.sol": {
      "LeverageLib": "0x1B1D1C42d26c169dB59D8681d0FD4C9a2840Ad11"
    },
    "src/core/flamm/FLAMMMaintainLib.sol": {
      "FLAMMMaintainLib": "0x5691dc81338DFdF5e4E76Fccb79e38540ff4D380"
    },
    "src/core/flamm/FLAMMPairQuoteLib.sol": {
      "FLAMMPairQuoteLib": "0xa0c8489D5a572eAeAeEDDf48cb888c20A950c3E3"
    },
    "src/hooks/everlong/EverlongOpsLib.sol": {
      "EverlongOpsLib": "0xAbe4447C954E3C7a405f8E75116BF9f5787426F7"
    }
  },
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
    "solady/=lib/solady/src/",
    "forge-std/=lib/forge-std/src/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.