Skip to content
Verified contractExactUNLICENSED

FLAMMAdmitLib

Address0xa6dbd8cd5cd10f8a5857cbed54a28405ffbdcbcb
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,511
Creation transaction
0x80e9c6360b…a376e7c464
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

52 files

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

src/core/flamm/FLAMMAdmitLib.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 {
    FLAMMStore, InvalidConfig, HookSetNotReady, HooksSet, PauseSet, CeilingBreached, BandSet, BadPair, NotScheduled,
    AdmissionScheduled, AdmissionCancelled, TokenAdded, PairAdded, PairRetired, CustodyMismatch, GuardianMayOnlyTighten,
    TradePairsSet, TradePairsScheduled, TradePairsCancelled, WAD
} from "src/core/flamm/FLAMMStore.sol";
import {FLAMM} from "src/core/flamm/FLAMM.sol";
import {FLAMMGateLib} from "src/core/flamm/FLAMMGateLib.sol";
import {FLAMMOpsLib} from "src/core/flamm/FLAMMOpsLib.sol";
import {FLAMMPolicyLib} from "src/core/flamm/FLAMMPolicyLib.sol";
import {FLAMMLane} from "src/core/flamm/FLAMMLane.sol";
import {FLAMMFenceLib} from "src/core/flamm/FLAMMFenceLib.sol";
import {IFLAMM} from "src/interfaces/core/flamm/IFLAMM.sol";
import {IMMRouter, MAX_TOKENS} from "src/interfaces/core/mm/IMMRouter.sol";
import {MMRouterAdminLib} from "src/core/mm/MMRouterAdminLib.sol";
import {MMRouterLib} from "src/core/mm/MMRouterLib.sol";
import {
    IFinancingAccount,
    CAP_ACTION_GATES,
    CAP_REPORTED_LOSS,
    CAP_SHARED_LIQUIDITY, CAP_HELD_REPAY,
    CAP_REDEMPTION_FEE,
    CAP_LENT_COLLATERAL,
    CAP_PRICED_RELEASE,
    CAP_ACCRUING_COLLATERAL
} from "src/interfaces/core/mm/IFinancingAccount.sol";
import {HOOK_CAP_TWO_SIDED} from "src/interfaces/core/flamm/IHookCapabilities.sol";
import {IPriceFeed} from "src/interfaces/core/IPriceFeed.sol";
import {IEverlongCore} from "src/interfaces/core/IEverlongCore.sol";
import {ReentrancyGuardLib} from "src/libraries/ReentrancyGuardLib.sol";

/// @notice The pool's genesis and its delayed admissions: tokens, credit pairs and venues enter through one pending
///         table, where the first call schedules an entry and the identical call executes it within its window; the
///         shape and capability checks every pair takes; the curator's trade mask, whose openings wait the pool's delay
///         as an admission does; the retirements of pairs and venues. None of it runs on a swap or an entry, and of an
///         exit only the release at a venue that takes its repay short ({heldRelease}).
///         The genesis and admission entries take `FLAMM`'s own parameters and read the pool's storage themselves, so
///         the pool hands them its call as it stands, decoding nothing.
library FLAMMAdmitLib {
    /// @dev The selectors of `FLAMM`'s delayed admissions, which open each entry's pending-table hash.
    bytes4 internal constant ADD_TOKEN = FLAMM.addToken.selector;
    bytes4 internal constant ADD_PAIR = FLAMM.addPair.selector;
    bytes4 internal constant ADD_VENUE = FLAMM.addVenue.selector;

    // ------------------------------------------------------------------ genesis
    /// @dev Validates the pool, its tokens and its pairs, then writes them with the bindings; the Router lists them in
    ///      {initializeHooks}, in the same creation, once the Factory has registered the pool. It re-checks no binding
    ///      its creation refuses anyway: the Factory, the pool's only creator, passes its own Router and a core with
    ///      code; a feed without code or a zero token fails the listing read (`hasToken`) or the `decimals` reads
    ///      below; and the Router refuses a token listed twice and a gap or band out of bounds for the pin when it
    ///      lists the pairs. Token 1's zero band asks for a pool with no band: two tokens, every pair's borrowing off
    ///      and an LTV envelope near zero (`MAX_NO_BAND_LTV_WAD`), so it never borrows; only its tokens past the pool
    ///      asset must be listed at the feed then (for a band attached later), while a pool with a band needs every
    ///      token listed. `FLAMM.initialize`'s call, whose share name and symbol the pool writes itself.
    function initializePool(
        address core_,
        address poolAsset_,
        address router_,
        address priceFeed_,
        address allowlist_,
        string calldata,
        string calldata,
        FLAMMStore.PoolInit calldata p,
        FLAMMStore.TokenInit[] calldata tokens,
        FLAMMStore.PairInit[] calldata pairs
    ) public {
        FLAMMStore.S storage $ = FLAMMStore.s();
        uint256 n = tokens.length + 1;
        if (tokens.length == 0 || n > MAX_TOKENS || pairs.length > FLAMMStore.MAX_POOL_PAIRS) {
            revert InvalidConfig();
        }
        if (p.feeFloorWad > p.feeCapWad || p.feeCapWad > WAD) revert InvalidConfig();
        // The curator's cap leaves the protocol's whole cap inside the gain, so the two never charge over 100 %.
        if (
            p.maxPerformanceFeeBp > 1e4 - FLAMMStore.MAX_PROTOCOL_FEE_BP
                || p.governanceDelaySec < FLAMMStore.MIN_GOVERNANCE_DELAY_SEC
        ) revert InvalidConfig();
        if (p.features & ~FLAMMStore.FEATURES_ALL != 0) revert InvalidConfig();
        bool noBand = tokens[0].swapPriceBandWad == 0;
        if (noBand && n != 2) revert InvalidConfig();
        uint8 poolDec = IERC20Metadata(poolAsset_).decimals();
        if (poolDec > 18 || poolDec < FLAMMStore.MIN_POOL_DECIMALS) revert InvalidConfig();
        if (!noBand && !IPriceFeed(priceFeed_).hasToken(poolAsset_)) revert InvalidConfig();
        $.core = IEverlongCore(core_);
        $.poolAsset = poolAsset_;
        $.router = IMMRouter(router_);
        $.priceFeed = IPriceFeed(priceFeed_);
        $.allowlist = allowlist_;
        $.factory = msg.sender;
        $.shareScale = uint40(10 ** (18 - poolDec));
        $.feeFloorWad = p.feeFloorWad;
        $.feeCapWad = p.feeCapWad;
        // the pool asset: no swap policy of its own, never lent until its batch is lowered
        FLAMMStore.TokenCfg storage c0 = $.tokens[0];
        (c0.token, c0.decimals, c0.scale, c0.partner) = (poolAsset_, poolDec, uint64(10 ** (18 - poolDec)), FLAMMStore.NO_PARTNER);
        c0.minSupplyBatch = type(uint128).max;
        $.tokenCount = 1;
        uint64 ceiling;
        for (uint256 i; i < tokens.length; ++i) {
            FLAMMStore.TokenInit memory t = tokens[i];
            if (!IPriceFeed(priceFeed_).hasToken(t.token)) revert InvalidConfig();
            _storeToken($, t, i == 0 && noBand);
            if (t.swapPriceBandWad > ceiling) ceiling = t.swapPriceBandWad;
        }
        // written before the pairs, whose checks read it
        $.noBand = noBand;
        for (uint256 i; i < pairs.length; ++i) {
            _storePair($, pairs[i]);
        }
        FLAMMOpsLib.syncLanes($);
        // the pairs' kinds from the Factory's peg groups, which are its caller's
        FLAMMOpsLib.syncKinds($);
        ($.bandCeilingWad, $.feeCapCeilingWad) = (noBand ? FLAMMStore.NO_BAND_CEILING : ceiling, p.feeCapWad);
        $.maxPriceAgeSec = p.maxPriceAgeSec;
        $.maxPerformanceFeeBp = p.maxPerformanceFeeBp;
        $.governanceDelaySec = p.governanceDelaySec;
        $.features = uint16(p.features);
        $.genesis = keccak256(abi.encode(tokens, pairs));
        if (p.startPaused) {
            $.paused = true;
            emit PauseSet(true, msg.sender);
        }
    }

    /// @dev Installs the first hook set (the pairs it prices the curator's trade mask too), lists the tokens and the
    ///      pairs at the Router in the pool's order (each pair at its LTV dial as its pin, its gap and its band, then
    ///      its caps and switch), logging each token's `TokenAdded` (the pool asset's first) and each pair's
    ///      `PairAdded` as a later admission logs it, checks the swap hook against the pairs (`HOOK_CAP_TWO_SIDED`) and
    ///      the band mode (`HOOK_CAP_UNPRICED` with no band; else every token's and pair's price admitted), then admits
    ///      the genesis venues by pair, skipping the admission delay, and their priorities. `tokens` and `pairs` must
    ///      be `initialize`'s own. The Factory calls it once, before `bootstrap`.
    function initializeHooks(
        IFLAMM.HookSet calldata hookSet,
        IFLAMM.VenueInit[] calldata venues,
        FLAMMStore.TokenInit[] calldata tokens,
        FLAMMStore.PairInit[] calldata pairs
    ) public {
        FLAMMStore.S storage $ = FLAMMStore.s();
        if ($.genesis == bytes32(0) || keccak256(abi.encode(tokens, pairs)) != $.genesis) revert InvalidConfig();
        delete $.genesis;
        FLAMMOpsLib.checkHookSet(hookSet);
        FLAMMOpsLib.install($, hookSet);
        // at birth the curator lets every pair the hook prices trade
        setTradeMask($, $.hookPairs);
        IMMRouter r = $.router;
        emit TokenAdded(0, $.poolAsset);
        for (uint256 i; i < tokens.length; ++i) {
            if (r.addToken(tokens[i].token) != i + 1) revert InvalidConfig();
            if (tokens[i].supplyCap != 0) r.setTokenSupplyCap(uint8(i + 1), tokens[i].supplyCap);
            emit TokenAdded(uint8(i + 1), tokens[i].token);
        }
        for (uint256 i; i < pairs.length; ++i) {
            _listPair($, uint8(i), pairs[i]);
        }
        FLAMMGateLib.checkHook($, hookSet.hook);
        if ($.noBand) {
            emit BandSet(true, 0, msg.sender);
        } else {
            for (uint256 t = 1; t < $.tokenCount; ++t) {
                FLAMMGateLib.admitToken($, t);
            }
            for (uint256 i; i < pairs.length; ++i) {
                FLAMMGateLib.admitPair($, pairs[i].coll, pairs[i].debt);
            }
        }
        uint16[] memory order = new uint16[](venues.length);
        for (uint256 i; i < venues.length; ++i) {
            order[i] = _addVenue(venues[i]);
        }
        if (venues.length != 0) r.setPriorities(order, order, order, order);
        else $.noLiveVenue = true;
        emit HooksSet(hookSet);
    }

    /// @dev Appends token `t`'s record (its band zero where `bandless`, the market band of a pool without one), with
    ///      its scale; it starts with no custody and no credit line. Its swap policy is checked first
    ///      ({FLAMMPolicyLib.checkPolicy}).
    function _storeToken(FLAMMStore.S storage $, FLAMMStore.TokenInit memory t, bool bandless) private {
        FLAMMPolicyLib.checkPolicy($, bandless, t.swapPriceBandWad, t.feeFloorWad, t.maxSwapNotional, t.reserveTarget);
        uint8 idx = $.tokenCount;
        uint8 dec = IERC20Metadata(t.token).decimals();
        if (dec > 18) revert InvalidConfig();
        FLAMMStore.TokenCfg storage c = $.tokens[idx];
        (c.token, c.decimals, c.scale, c.partner) = (t.token, dec, uint64(10 ** (18 - dec)), FLAMMStore.NO_PARTNER);
        (c.swapPriceBandWad, c.feeFloorWad, c.maxSwapNotional) = (t.swapPriceBandWad, t.feeFloorWad, uint128(t.maxSwapNotional));
        (c.reserveTarget, c.minSupplyBatch) = (uint128(t.reserveTarget), t.minSupplyBatch);
        $.indexOf[t.token] = idx + 1;
        $.tokenCount = idx + 1;
    }

    /// @dev Checks pair `p` against the pool's shape and its envelope ({_checkPair}) and its LTV against what the
    ///      band of its tokens and the protocol's part keep (`FLAMMStore.coverSafe`, `InvalidConfig`), as the band
    ///      stands when it lists, then appends its record, its credit dial capped at `1 / (1 + band)` of the pair's
    ///      tokens (`FLAMMStore.creditCap`, which the envelope's floor is within). A debt token no live pair owed is
    ///      proven debt-free here, as no venue lends it yet; the caller syncs the pair masks
    ///      (`FLAMMOpsLib.syncLanes`).
    function _storePair(FLAMMStore.S storage $, FLAMMStore.PairInit memory p) private {
        _checkPair($, p);
        if (!FLAMMStore.coverSafe(p.ltvWad, FLAMMStore.pairBand($, p.coll, p.debt))) revert InvalidConfig();
        FLAMMStore.TokenCfg storage d = $.tokens[p.debt];
        uint8 idx = $.pairCount;
        FLAMMStore.PairCfg storage pc = $.pairs[idx];
        (pc.coll, pc.debt, pc.live, pc.borrowOff) = (p.coll, p.debt, true, !p.borrowEnabled);
        // the credit dial capped at what a fill inside the pair's band guarantees an input is worth
        uint256 cap = FLAMMStore.creditCap($, p.coll, p.debt);
        (pc.ltvWad, pc.phiWad, pc.roomEpsilonWad) = (p.ltvWad, p.phiWad > cap ? uint64(cap) : p.phiWad, p.roomEpsilonWad);
        (pc.ltvMinWad, pc.ltvMaxWad, pc.phiMinWad, pc.phiMaxWad) = (p.ltvMinWad, p.ltvMaxWad, p.phiMinWad, p.phiMaxWad);
        (pc.ltvMaxStepWad, pc.minStructDistWad, pc.ltvCooldownSec) = (p.ltvMaxStepWad, p.minStructDistWad, p.ltvCooldownSec);
        pc.lastDialMoveTs = uint48(block.timestamp);
        if (d.partner == FLAMMStore.NO_PARTNER) (d.partner, d.pairId, d.debtFree) = (p.coll, idx, true);
        // a new pair owes nothing: its proof stands (`FLAMMStore.S.pairsFree`) until its first draw
        $.pairsFree |= uint32(1 << idx);
        $.pairCount = idx + 1;
    }

    /// @dev Pair `p` against the pool's shape (two listed tokens, distinct, and no pair of the same two tokens in the
    ///      same roles listed before it, retired or not), its envelope (its credit floor within `1 / (1 + band)` of its
    ///      tokens, `FLAMMStore.creditCap`) and the pair limit: run when the pair is scheduled, so it names tokens
    ///      listed then and a floor the band then refuses waits no delay, and again when it lists, as the band may move
    ///      between. A pool with no band takes no pair that borrows, so a listed pair's switch is its own
    ///      (`_listPair`).
    function _checkPair(FLAMMStore.S storage $, FLAMMStore.PairInit memory p) private view {
        uint256 n = $.tokenCount;
        (uint8 a, uint8 c) = (p.coll, p.debt);
        if (a >= n || c >= n || a == c) revert BadPair();
        uint256 m = $.pairCount;
        for (uint256 q; q < m; ++q) {
            FLAMMStore.PairCfg storage pq = $.pairs[q];
            if (pq.coll == a && pq.debt == c) revert BadPair();
        }
        // `phiMax <= 1` with `ltvMax < 1` keeps the room denominator `1 - ltv*phi` positive across the envelope; at
        // WAD or above, `minStructDistWad` leaves no positive ltv passing the dial move's `1 - ltv/lltv` floor.
        if (p.phiMinWad == 0 || p.phiWad < p.phiMinWad || p.phiWad > p.phiMaxWad || p.phiMaxWad > WAD) revert InvalidConfig();
        if (p.phiMinWad > FLAMMStore.creditCap($, a, c)) revert InvalidConfig();
        if (
            p.ltvWad == 0 || p.ltvWad < p.ltvMinWad || p.ltvWad > p.ltvMaxWad || p.ltvMaxWad >= WAD
                || p.ltvMaxStepWad == 0 || p.minStructDistWad >= WAD
        ) revert InvalidConfig();
        if (p.roomEpsilonWad >= FLAMMStore.MAX_ROOM_EPSILON_WAD) revert InvalidConfig();
        if (uint256(p.ltvWad) + p.safetyGapWad >= WAD || p.oracleBandWad > MMRouterAdminLib.MAX_ORACLE_BAND_WAD) revert InvalidConfig();
        if ($.noBand && (p.borrowEnabled || p.ltvMaxWad > FLAMMStore.MAX_NO_BAND_LTV_WAD)) revert InvalidConfig();
        if ($.pairCount >= FLAMMStore.MAX_POOL_PAIRS) revert InvalidConfig();
    }

    /// @dev Lists pair `idx` at the Router, at its dial as its pin, its gap and its band, then its caps and switch; the
    ///      Router numbers it as the pool does. Every pair listed has passed {_checkPair} under the band mode it lists
    ///      in, so its switch is off with no band.
    function _listPair(FLAMMStore.S storage $, uint8 idx, FLAMMStore.PairInit memory p) private {
        IMMRouter r = $.router;
        if (r.addPair(p.coll, p.debt, p.ltvWad, p.safetyGapWad, p.oracleBandWad) != idx) revert InvalidConfig();
        if (p.borrowEnabled || p.debtCap != 0) r.setPairCaps(idx, p.debtCap, p.borrowEnabled);
        emit PairAdded(idx, p.coll, p.debt);
    }

    // ------------------------------------------------------------------ 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 (`NotCurator`).
    modifier onlyCurator() {
        FLAMMStore.requireCurator(FLAMMStore.s());
        _;
    }

    /// @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();
    }

    // ------------------------------------------------------------------ the pending table
    /// @notice Whether the entry `h = keccak256(call)` executes now, `call` being the entry's selector and arguments,
    ///         abi-encoded as one tuple: the first call (or one after its window lapsed) schedules it `delay` from now,
    ///         logging `call`, and returns false; the identical call within `[due, due + executionWindow]` clears it, the window the longer of `governanceDelaySec` and one day
    ///         and returns true; one before its due time reverts `HookSetNotReady`. The admissions' rule, and the
    ///         fences' (`FLAMMFenceLib`), whose delay is `governanceDelaySec`.
    function due(FLAMMStore.S storage $, bytes4 sel, bytes memory call, uint256 delay) internal returns (bool) {
        bytes32 h = keccak256(call);
        uint48 dueAt = $.pending[h];
        if (dueAt != 0) {
            if (block.timestamp < dueAt) revert HookSetNotReady();
            if (block.timestamp <= uint256(dueAt) + FLAMMStore.executionWindow($.governanceDelaySec)) {
                delete $.pending[h];
                return true;
            }
        }
        dueAt = uint48(block.timestamp + delay);
        $.pending[h] = dueAt;
        emit AdmissionScheduled(h, sel, dueAt, msg.sender, call);
        return false;
    }

    /// @notice Removes a scheduled admission from the pending table; the curator's or the guardian's.
    /// @dev Removes a scheduled admission; `NotScheduled` where the table holds none.
    function cancel(bytes32 h) public curatorOrGuardian nonReentrant {
        FLAMMStore.S storage $ = FLAMMStore.s();
        if ($.pending[h] == 0) revert NotScheduled();
        delete $.pending[h];
        emit AdmissionCancelled(h, msg.sender);
    }

    /// @notice `FLAMM.addToken`, delayed by `governanceDelaySec`: lists `t` at the Router as the next token, with its
    ///         swap and lending policy, and asks the swap hook which of its pairs it prices. It trades only once the
    ///         curator's trade mask opens those pairs (`setTradePairs`, delayed too), so a holder who objects is out
    ///         before it lists. The feed must price it against the pool asset now (`FLAMMGateLib.admitToken`) and its
    ///         band must stand under the band's ceiling. A pool with no band takes no third token.
    /// @dev `t` is decoded whole on entry, so a malformed field reverts before the policy check.
    function addToken(FLAMMStore.TokenInit memory t) public {
        FLAMMStore.S storage $ = FLAMMStore.s();
        FLAMMPolicyLib.checkPolicy($, false, t.swapPriceBandWad, t.feeFloorWad, t.maxSwapNotional, t.reserveTarget);
        if (!due($, ADD_TOKEN, abi.encode(ADD_TOKEN, t), $.governanceDelaySec)) return;
        if ($.noBand) revert InvalidConfig();
        if (t.swapPriceBandWad > $.bandCeilingWad) revert CeilingBreached();
        uint8 idx = $.tokenCount;
        IMMRouter r = $.router;
        if (r.addToken(t.token) != idx) revert InvalidConfig();
        _storeToken($, t, false);
        FLAMMGateLib.admitToken($, idx);
        FLAMMOpsLib.syncKinds($);
        if (t.supplyCap != 0) r.setTokenSupplyCap(idx, t.supplyCap);
        // the hook is asked for the new token's pairs; the curator opens them
        FLAMMLane.syncPairs($);
        emit TokenAdded(idx, t.token);
    }

    /// @notice `FLAMM.addPair`, delayed by `governanceDelaySec` and at least `FLAMMStore.MIN_BAND_DELAY_SEC`: lists `p`
    ///         at the Router as the next pair, at its LTV as its pin, then its caps and switch. Any two listed tokens
    ///         may pair, each pair of tokens in each role once (a retired one included), and a debt token may be owed
    ///         against several collateral tokens. It takes the pool's shape and its envelope's rules when it is
    ///         scheduled and again at execution, so the tokens it names are listed when it is scheduled and the token
    ///         it borrows waits its whole delay. A pair that owes the pool asset or posts a token past it needs the
    ///         swap hook to declare `HOOK_CAP_TWO_SIDED`. A pool with no band takes one only with its borrowing off and
    ///         its envelope near zero; one with a band admits its price both ways.
    function addPair(FLAMMStore.PairInit calldata p) public {
        FLAMMStore.S storage $ = FLAMMStore.s();
        _checkPair($, p);
        uint256 delay = $.governanceDelaySec;
        if (delay < FLAMMStore.MIN_BAND_DELAY_SEC) delay = FLAMMStore.MIN_BAND_DELAY_SEC;
        if (!due($, ADD_PAIR, abi.encode(ADD_PAIR, p), delay)) return;
        uint8 idx = $.pairCount;
        _storePair($, p);
        _listPair($, idx, p);
        FLAMMOpsLib.syncLanes($);
        if (p.coll != 0 || p.debt == 0) {
            FLAMMGateLib.requireCapability($.invariantHook, HOOK_CAP_TWO_SIDED);
            if ($.swapBits & FLAMMStore.SWAP_PAIR_HOOK != 0) {
                FLAMMGateLib.requireCapability(address(uint160($.pairHookWord)), HOOK_CAP_TWO_SIDED);
            }
        }
        if (!$.noBand) FLAMMGateLib.admitPair($, p.coll, p.debt);
    }

    /// @notice `FLAMM.addVenue`, delayed by `governanceDelaySec`; scheduling returns `type(uint16).max`.
    function addVenueScheduled(IFLAMM.VenueInit calldata v) public returns (uint16 id) {
        FLAMMStore.S storage $ = FLAMMStore.s();
        if (!due($, ADD_VENUE, abi.encode(ADD_VENUE, v), $.governanceDelaySec)) return type(uint16).max;
        // never on a pair naming a token whose custody a fence holds out, which no genesis venue meets: the Factory
        // lists those in the call that creates the pool
        if ($.swapBits & FLAMMStore.SWAP_FENCE != 0) {
            FLAMMStore.PairCfg storage pc = $.pairs[v.pair];
            uint256 out = $.fenceWord >> FLAMMStore.OUT_TOKENS_SHIFT;
            if (((out >> pc.coll) | (out >> pc.debt)) & 1 != 0) revert InvalidConfig();
        }
        return _addVenue(v);
    }

    /// @dev Shared by the scheduled path and the genesis venues, on a live pair. A pool with no band reads no price, so
    ///      its prices are all zero, and the Router admits only a venue whose borrowing is off (`OracleBand`
    ///      otherwise). One admitted with its borrowing on keeps the larger of the pair's gap and 1 % over the pin
    ///      (`FLAMMGateLib.requireDustGap`). It reads the pool's storage itself, so neither call site hands it a
    ///      constant: the compiler keeps one copy of it rather than one inlined at each.
    function _addVenue(IFLAMM.VenueInit memory v) private returns (uint16 id) {
        FLAMMStore.S storage $ = FLAMMStore.s();
        FLAMMStore.checkPair($, v.pair);
        if (!$.pairs[v.pair].live) revert InvalidConfig();
        uint256[] memory usd = $.noBand ? new uint256[]($.tokenCount) : FLAMMGateLib.pairUsd($, v.pair);
        IMMRouter r = $.router;
        id = r.addVenue(v.kind, v.pair, v.venueParams, v.borrowEnabled, v.supplyEnabled, usd);
        // A retired slot is reused below the cap, and is live again; only a new slot past it is refused.
        if (id >= FLAMMStore.MAX_POOL_VENUES) revert IMMRouter.TooManyVenues();
        _markAdmitted($, id, v.pair);
        if (v.debtCap != 0 || v.supplyCap != 0 || v.maxBorrowRateWad != 0) {
            r.setVenueCaps(id, v.debtCap, v.supplyCap, v.maxBorrowRateWad);
        }
    }

    /// @dev Marks venue `id` of pair `pair`, just admitted at the Router, live: the pool has a live venue, the slot is
    ///      neither retired nor idle, and the pair counts it.
    ///      - Records whether the venue can refuse an action (`FLAMMStore.S.gatedVenues`: its account's
    ///        `CAP_ACTION_GATES`), can report a haircut (`FLAMMStore.S.lossVenues`: `CAP_REPORTED_LOSS`), shares one
    ///        reserve's cash (`FLAMMStore.S.sharedVenues`: `CAP_SHARED_LIQUIDITY`), can hold a partial repay short
    ///        (`FLAMMStore.S.heldRepayVenues`: `CAP_HELD_REPAY`) and takes a redemption fee (`FLAMMStore.S.feeVenues`:
    ///        `CAP_REDEMPTION_FEE`), read as the Router reads its capabilities at the same admission.
    ///      - A kind whose release depends on the venue's liquidity or reads its oracle (`CAP_LENT_COLLATERAL`,
    ///        `CAP_PRICED_RELEASE`), or that holds a minimum position (`CAP_HELD_REPAY`), and that cannot refuse an
    ///        action (no `CAP_ACTION_GATES`) is refused (`InvalidConfig`), as the ADMISSION notes of
    ///        `IFinancingAccount` ask: the pool reads every refusal of such a release, and the minimum an entry's
    ///        borrow leg checks (`FLAMMSharedLib.heldLegsCheck`), only at a gated venue.
    ///      - So is one that shares one reserve or takes a redemption fee and cannot report a loss (no
    ///        `CAP_REPORTED_LOSS`), as its exit slices are read only beside its haircut.
    ///      - One admitted with its borrowing on needs its threshold at least 1 % over the pair's pin
    ///        (`FLAMMGateLib.requireDustGap`, `LtvLltvGap`), beside the gap the Router holds it to.
    ///      - A slot whose kind reports a loss that is no redemption fee keeps a loss mark
    ///        (`FLAMMStore.S.lossMarks`), cleared here as the slot's last venue's, and the features' bit
    ///        `FLAMMStore.LOSS_MARKS` is set exactly while some slot's kind reports a loss, a redemption fee or not.
    ///      - A kind that declares a bit from 11 up (the spare bits 11 to 15, which the Router admits,
    ///        `KNOWN_CAPABILITIES`) is refused too (`InvalidConfig`): this pool gives none of them a meaning, so it
    ///        could not honour one; a later pool implementation may give one a meaning.
    function _markAdmitted(FLAMMStore.S storage $, uint16 id, uint8 pair) private {
        $.noLiveVenue = false;
        uint32 bit = uint32(1) << id;
        $.retiredVenues &= ~bit;
        $.idleVenues &= ~bit;
        $.pairs[pair].venues |= bit;
        IMMRouter.VenueView memory w = $.router.venue(address(this), id);
        // A frame's account (collateral token zero, `FRAME_VENUE` in `IMMRouter.sol`) keeps its venues in one lender
        // position, while a custody-blind pool's gate holds each venue to its own health: such a pool admits no frame.
        if ($.features & FLAMMStore.CUSTODY_BLIND != 0) {
            if (IFinancingAccount(w.account).COLLATERAL_ASSET() == address(0)) revert InvalidConfig();
        }
        if (w.borrowEnabled) FLAMMGateLib.requireDustGap($, pair, w.lltvWad);
        uint256 caps = IFinancingAccount(w.account).capabilities();
        // a spare bit (11 to 15, past `CAP_REDEMPTION_FEE`), which the Router admits and this pool gives no meaning
        if (caps >> 11 != 0) revert InvalidConfig();
        if (caps & (CAP_LENT_COLLATERAL | CAP_PRICED_RELEASE | CAP_HELD_REPAY) != 0 && caps & CAP_ACTION_GATES == 0) {
            revert InvalidConfig();
        }
        if (caps & CAP_SHARED_LIQUIDITY != 0 && caps & CAP_REPORTED_LOSS == 0) revert InvalidConfig();
        if (caps & CAP_REDEMPTION_FEE != 0 && caps & CAP_REPORTED_LOSS == 0) revert InvalidConfig();
        $.gatedVenues = caps & CAP_ACTION_GATES != 0 ? $.gatedVenues | bit : $.gatedVenues & ~bit;
        $.lossVenues = caps & CAP_REPORTED_LOSS != 0 ? $.lossVenues | bit : $.lossVenues & ~bit;
        $.sharedVenues = caps & CAP_SHARED_LIQUIDITY != 0 ? $.sharedVenues | bit : $.sharedVenues & ~bit;
        $.heldRepayVenues = caps & CAP_HELD_REPAY != 0 ? $.heldRepayVenues | bit : $.heldRepayVenues & ~bit;
        $.feeVenues = caps & CAP_REDEMPTION_FEE != 0 ? $.feeVenues | bit : $.feeVenues & ~bit;
        // the slot's loss mark is its last venue's: cleared, and the features' bit says whether any slot keeps one
        delete $.lossMarks[id];
        uint16 f = $.features & ~uint16(FLAMMStore.LOSS_MARKS);
        $.features = $.lossVenues != 0 ? f | uint16(FLAMMStore.LOSS_MARKS) : f;
    }

    // ------------------------------------------------------------------ the trade masks
    /// @notice Writes the curator's trade mask, clearing any scheduled opening. While a token's fence record is open
    ///         the pairs naming it stay closed: the mask's openings of them are dropped (`FLAMMFenceLib.keepTrades`).
    function setTradeMask(FLAMMStore.S storage $, uint256 mask) public {
        if ($.swapBits & FLAMMStore.SWAP_FENCE != 0) {
            uint256 kept = $.fenceTrades;
            if (kept & ~mask != 0) $.fenceTrades = kept & mask;
            mask = FLAMMFenceLib.keepTrades($, mask);
        }
        ($.tradePairs, $.pendingTradePairs, $.tradePairsExecutableAt) = (mask, 0, 0);
        syncSwapBits($, $.hookPairs, mask);
        emit TradePairsSet(mask, msg.sender);
    }

    /// @notice The hook pair's two bits of both masks into the swap's word: at each write of the curator's mask, of the
    ///         hook's pairs (`FLAMMLane.syncPairs`) and of a token fence's (`FLAMMFenceLib`).
    function syncSwapBits(FLAMMStore.S storage $, uint256 hookMask, uint256 tradeMask) internal {
        uint256 both = hookMask & tradeMask;
        uint8 bits = $.swapBits & ~(FLAMMStore.SWAP_SELL_OPEN | FLAMMStore.SWAP_BUY_OPEN);
        if ((both >> 1) & 1 != 0) bits |= FLAMMStore.SWAP_SELL_OPEN; // token 0 for token 1
        if ((both >> 16) & 1 != 0) bits |= FLAMMStore.SWAP_BUY_OPEN; // token 1 for token 0
        $.swapBits = bits;
    }

    // ------------------------------------------------------------------ retirements
    /// @notice Closes an emptied pair to new venues and borrowing, for good; the Router refuses unless every venue of
    ///         it is retired and empty. Tokens are never retired.
    /// @dev The Router retires pair `p`, which it refuses unless every venue of the pair is
    ///      retired and empty; the pool's switch for it turns off for good, and the pair masks and the partner cache
    ///      follow (`FLAMMOpsLib.syncLanes`).
    ///      The Router numbers the pairs as the pool does, so it refuses a pair past them (`BadPairIndex`) itself.
    function retirePair(uint8 p) public onlyCurator nonReentrant {
        FLAMMStore.S storage $ = FLAMMStore.s();
        $.router.retirePair(p);
        FLAMMStore.PairCfg storage pc = $.pairs[p];
        (pc.live, pc.borrowOff) = (false, true);
        FLAMMOpsLib.syncLanes($);
        emit PairRetired(p);
    }

    /// @notice Retires venue `id` (`IMMRouter.retireVenue`: it must owe nothing and recognize no collateral or supply);
    ///         the curator's. Refused (`InvalidConfig`) while a collateral reserve rule names it; a fenced venue's
    ///         retirement ends its fence; a later admission may reuse the slot.
    /// @dev Retires venue `id` and records it (`FLAMMStore.S.retiredVenues`), so no walk of the venues reads it again;
    ///      once no venue is live the pool records that too, and its swaps stop reading the Router. A venue a
    ///      collateral reserve rule names retires only once the rule is off, since a later admission may reuse its
    ///      slot. A fenced venue's retirement closes its fence (`FLAMMFenceLib.onRetire`): the Router found it holding
    ///      nothing.
    function retireVenue(uint16 id) public onlyCurator nonReentrant {
        FLAMMStore.S storage $ = FLAMMStore.s();
        IMMRouter r = $.router;
        IMMRouter.VenueView memory v = r.venue(address(this), id);
        // A rule names only a venue live under it whose collateral is its token, which cannot retire while it does:
        // only the rule of the venue's collateral can name it.
        FLAMMStore.CollateralReserve storage c = $.reserves[v.coll];
        if (c.reserve != 0 && c.venueId == id) revert InvalidConfig();
        r.retireVenue(id);
        // The Router retires only a live slot of its list, which never shrinks: `id` is under its length, as every
        // recorded slot is, so no venue is live once the record's low `venueCount` bits are all set.
        uint32 bit = uint32(1) << id;
        uint32 retired = $.retiredVenues | bit;
        $.retiredVenues = retired;
        $.idleVenues &= ~bit;
        $.pairs[v.pair].venues &= ~bit;
        if (uint256(retired) + 1 == uint256(1) << r.venueCount(address(this))) $.noLiveVenue = true;
        FLAMMFenceLib.onRetire($, id);
    }

    // ------------------------------------------------------------------ an exit's held repay
    /// @notice `FLAMMFlowLib._heldRepay`'s release at venue `id`, which took `paid` of an exit's `owed` repay leg, less
    ///         than asked, out of its collateral slice `cs`: the share the repay frees, rounded down, which its
    ///         proportional release proves, and the whole slice where the repay left the venue owing nothing (a debt
    ///         read a unit over after another account's repay on the venue's behalf, an Aave repay of a whole debt
    ///         taken a scaled unit short), which then holds nothing.
    /// @dev - A venue that still owes, at a kind whose collateral accrues, keeps posted at least what a release in its
    ///        whole units cannot take past its threshold at its pair's LTV (`floor`: one unit's assets and one, times
    ///        `lltv / (lltv - ltv)` where the threshold is over the LTV), so the release never takes its last unit, and
    ///        releases nothing where the share is under one unit's assets and one, which the kind would release by
    ///        burning a whole unit, refused where the venue's margin is under that unit's worth
    ///        (`FLAMMGateLib.nearUnitsAt`).
    ///      - The custody the pool owns past the exit's own slice (`room`) pays the rest of the slice (`pay`), and what
    ///        it cannot stays posted and leaves the exit's payout of the collateral token (`out`, cut by the venue's
    ///        haircut `cl` on the whole slice, whose cut on that part comes back): at most the dust, one unit's assets
    ///        and one times `lltv / max(lltv - ltv, gap, 1 %)` (`gap`, the pair's safety gap at the Router, floored at
    ///        `FLAMMStore.MIN_DUST_GAP_WAD`, so no cut of the threshold toward the LTV widens it, at a zero gap too;
    ///        what `FLAMMGateLib.nearUnitsAt` leaves where the repay is whole), the lenders' rounding
    ///        (`MMRouterLib.RELEASE_SLACK`) and, where the share is under one unit's assets and one, that share, so an
    ///        exit whose release would burn a unit executes, paid short by that share, which stays posted as recorded
    ///        dust; past it the exit refuses (`CustodyMismatch`).
    ///      - Here, beside the cold paths, so no swap's code moves with it.
    function heldRelease(
        FLAMMStore.S storage $,
        uint16 id,
        uint256 cs,
        uint256 paid,
        uint256 owed,
        uint256 room,
        uint256 out,
        uint256 cl
    ) public view returns (uint256 release, uint256 pay, uint256 outLeft) {
        IMMRouter r = $.router;
        IMMRouter.VenueView memory v = r.venue(address(this), id);
        (, uint256 coll,,, uint256 debt) = r.venuePosition(address(this), id);
        IFinancingAccount k = IFinancingAccount(v.account);
        // token amounts and WAD ratios: no product here nears 2^256
        release = debt == 0 ? cs : cs * paid / owed;
        uint256 dust = MMRouterLib.RELEASE_SLACK;
        if (debt != 0 && k.capabilities() & CAP_ACCRUING_COLLATERAL != 0) {
            (uint256 lltv, uint256 pin) = (v.lltvWad, $.pairs[v.pair].ltvWad);
            uint256 one = k.collateralUnitsToAssets(v.id, 1) + 1;
            (uint256 floor, uint256 most) = (one, one);
            if (lltv > pin) {
                (uint256 d, uint256 gap) = (lltv - pin, r.pair(address(this), v.pair).safetyGapWad);
                if (gap < FLAMMStore.MIN_DUST_GAP_WAD) gap = FLAMMStore.MIN_DUST_GAP_WAD;
                (floor, most) = (Math.ceilDiv(one * lltv, d), Math.ceilDiv(one * lltv, d < gap ? gap : d));
            }
            if (release + floor > coll) release = coll > floor ? coll - floor : 0;
            // a release under one unit's assets and one would burn a whole unit: none; custody pays the slice, and
            // what it cannot of that share may stay posted beside the dust
            if (release < one) (most, release) = (most + release, 0);
            dust += most;
        }
        uint256 kept = cs - release;
        pay = kept < room ? kept : room;
        kept -= pay;
        outLeft = out;
        if (kept == 0) return (release, pay, outLeft);
        if (kept > dust) revert CustodyMismatch();
        if (cl != 0) outLeft += Math.ceilDiv(cs * cl, WAD) - Math.ceilDiv((cs - kept) * cl, WAD);
        if (outLeft < kept) revert CustodyMismatch();
        outLeft -= kept;
    }
}
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.