Skip to content
Verified contractExactUNLICENSED

FLAMMMaintainLib

Address0xaa5434e13eb54f37c577229efc981cceceb56417
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,480,482
Creation transaction
0x2d80313aa4…2759c5e0f5
Libraries
src/core/mm/MMRouterLib.sol:MMRouterLib0x95b3…48ef2csrc/core/flamm/FLAMMLane.sol:FLAMMLane0x5d81…90de37src/core/flamm/FLAMMRoute.sol:FLAMMRoute0xb1ff…7fb0fesrc/periphery/FLAMMMaxima.sol:FLAMMMaxima0x6854…90a91bsrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0xf55c…49cf45src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x0be7…5ecc47src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xa5db…72803esrc/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0x2795…4cfb77src/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0x3a05…434368src/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x70ca…60bee4src/core/mm/CTokenMarketLib.sol:CTokenMarketLib0x60e4…314010src/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0x0b10…1ce950src/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x634d…298fcdsrc/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0x5dc3…aa7e91src/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0x9dbb…798f1asrc/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0x6b2b…518935src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0x99de…929869src/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0xe4be…cfac2esrc/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0x93ab…262861src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x6abb…60ea7esrc/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0x3858…f91f06src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0x4551…33b301src/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xb852…b71005src/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x6a6a…798659src/hooks/everlong/LeverageLib.sol:LeverageLib0x8039…16d055src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0xaa54…b56417src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0x3bc5…2055ddsrc/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xf6d5…9dfeef

52 files

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

src/core/flamm/FLAMMMaintainLib.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, InvalidAmount, InvalidConfig, NothingToMaintain, CollateralToppedUp, CollateralReleased,
    EmergencyAction, PriceUnchecked, BelowMinimumShares, NotBootstrapped, DepositNotPermitted, ZeroShares, Bootstrapped,
    TokenSeeded, PerformanceFeeCharged, VenueFrozen, RoomExhausted, VenueReportsLoss, WAD
} from "src/core/flamm/FLAMMStore.sol";
import {FLAMMGateLib} from "src/core/flamm/FLAMMGateLib.sol";
import {FLAMMLawLib} from "src/core/flamm/FLAMMLawLib.sol";
import {FLAMMFlowLib} from "src/core/flamm/FLAMMFlowLib.sol";
import {FLAMMBlindLib} from "src/core/flamm/FLAMMBlindLib.sol";
import {FLAMMFenceLib} from "src/core/flamm/FLAMMFenceLib.sol";
import {FLAMMTopUpLib} from "src/core/flamm/FLAMMTopUpLib.sol";
import {FLAMMKeptLib} from "src/core/flamm/FLAMMKeptLib.sol";
import {IFLAMM, IFLAMMProtocolFee} from "src/interfaces/core/flamm/IFLAMM.sol";
import {IMMRouter, VENUE_RETIRED, VENUE_FENCED} from "src/interfaces/core/mm/IMMRouter.sol";
import {MMRouterLib} from "src/core/mm/MMRouterLib.sol";
import {IFinancingAccount} from "src/interfaces/core/mm/IFinancingAccount.sol";
import {VenueAccountBase} from "src/core/mm/VenueAccountBase.sol";
import {ReentrancyGuardLib} from "src/libraries/ReentrancyGuardLib.sol";

/// @notice The pool's custody maintenance: the permissionless collateral maintainer (its entry; it runs in
///         `FLAMMTopUpLib`), the maintenance path, the emergency path, the bootstrap and the curator's
///         seeds, which put custody in before any entry, and the performance fee's skim. None of them
///         posts or repays with the spread fee the pool keeps in custody for the protocol (`FLAMMStore.ownHeld`). Every
///         venue move takes its venue's own tokens, from its pair: a post or a top-up its collateral token, a repay or
///         a supply withdrawal its debt token. None of it runs on an entry, an exit or a swap: a swap's rotation
///         runs beside the collateral maintainer (`FLAMMTopUpLib.rotate`).
library FLAMMMaintainLib {

    // ------------------------------------------------------------------ custody maintenance
    /// @dev `TopUp` posts `amount` of venue `a`'s collateral token from custody at it, a token the pool owes nowhere:
    ///      custody of an owed token nets its debt and a post of it would not, so the post would raise that debt. A
    ///      venue that owes passes at once, as no token both backs a debt and is owed; at one that owes nothing (a
    ///      lender that pays on collateral, say) an owed token reverts `NothingToMaintain`; a venue whose kind can
    ///      refuse an action and that takes no post now (`FLAMMGateLib.postable` zero: a frozen venue mark among them)
    ///      reverts `VenueFrozen`, as an exit during a freeze would forfeit the post; and one whose lender reports a
    ///      loss on its collateral reverts `VenueReportsLoss` ({_requireNoLoss}), as NAV would fall by that share of
    ///      the post and rise again with its release: such a venue is topped up by the collateral maintainer alone
    ///      (`FLAMMTopUpLib.maintainCollateral`, which anyone calls and the posting law sizes). `Release` releases
    ///      `amount` of collateral token `a` across the venues whose collateral it is (`IMMRouter.reclaim`), on a
    ///      custody-blind pool only where its gate holds after it (`FLAMMBlindLib.blindGate`: no release while a venue
    ///      is past its trigger). While a venue of a frame posting `a` sits under its own trigger, the release takes no
    ///      more than that frame spares over its venues' triggers, summed, as a swap's reclaim
    ///      (`FLAMMTopUpLib.frameBound`): past it the whole release reverts `RoomExhausted`, what venues outside the
    ///      frame could give among it, and the keeper sizes it again; it reverts `PriceUnchecked` while an indebted
    ///      venue of such a frame has no price for its pair, and spares none while a venue there holds collateral with
    ///      no price. Read only on a pool that lists a venue of a kind that can refuse an action, the pooled kinds,
    ///      whose accounts alone can be a frame's, among them;
    ///      `Refinance` moves debt from venue `a` to venue `b` of one pair, its bridge in the pair's debt token;
    ///      `FundedRefinance` is that move, its bridge what custody holds of the token and, past it, a loan from the
    ///      caller: the caller needs an allowance to the pool for the transaction and is repaid in full in it, no fee
    ///      and no claim on either side, the same where the move took no bridge. Either move takes its share of
    ///      `a`'s collateral with it, and out of a frame's account or into one it may not leave a frame under its
    ///      venues' triggers ({_requireFrameCovered}: `RoomExhausted`, and the keeper moves less or covers the mates
    ///      first);
    ///      `MigrateSupply` moves supply between two venues that lend one token. A refinance whose destination's lender
    ///      reports a loss on its collateral, and a supply move whose destination's reports one on its supply, revert
    ///      `VenueReportsLoss`; out of such a venue each runs. The last branch is `MigrateSupply`:
    ///      ABI decoding refuses any other `kind` before the body runs, so a new `MaintainKind` member needs its own
    ///      branch.
    function maintain(IFLAMM.MaintainKind kind, uint16 a, uint16 b, uint256 amount) public {
        FLAMMStore.S storage $ = FLAMMStore.s();
        FLAMMStore.requireFeature($, 4); // FEATURE_MAINTENANCE
        FLAMMGateLib.accrueRead($, 0);
        // a reading of the loss marks before any check of them, so a first loss no skim has seen is judged on a mark,
        // not on a ratio a supply held for this call lowers again
        if ($.features & FLAMMStore.LOSS_MARKS != 0) FLAMMKeptLib.recordLossMarks();
        IMMRouter r = $.router;
        if (kind == IFLAMM.MaintainKind.TopUp) {
            // a gated venue that takes no post now, a frozen venue mark among them, takes none from custody: every
            // exit during the freeze would forfeit it
            if (($.gatedVenues >> a) & 1 != 0 && FLAMMGateLib.postable($, a) == 0) revert VenueFrozen();
            _requireNoLoss($, a, FLAMMStore.LOSS_LEG_COLLATERAL);
            IMMRouter.VenueView memory vv = r.venue(address(this), a);
            uint8 t = vv.coll;
            (,,,, uint256 debt) = r.venuePosition(address(this), a);
            // the room is one field (`FLAMMGateLib.postable`), which at the Aave V3 kind's exception may allow a post
            // at a venue whose actions read none: where it owes no more than the lenders' rounding every exit would
            // forfeit that post (`FLAMMFlowLib.proRata`), so the action bits are asked there too
            if (
                ($.gatedVenues >> a) & 1 != 0 && debt <= MMRouterLib.RELEASE_SLACK
                    && !FLAMMGateLib.acts(vv.account, vv.id)
            ) revert VenueFrozen();
            if (debt == 0) {
                (uint16 owed,) = r.drawn(address(this));
                if ((owed >> t) & 1 != 0) revert NothingToMaintain();
            }
            if (amount == 0 || amount > FLAMMStore.ownHeld($, t)) revert InvalidAmount();
            FLAMMTopUpLib.post($, t, a, amount, FLAMMStore.heldOf($, t));
            emit CollateralToppedUp(a, amount, msg.sender);
        } else if (kind == IFLAMM.MaintainKind.Release) {
            if (amount == 0) revert InvalidAmount();
            FLAMMStore.checkToken($, a); // so `a` is a token index, and `uint8(a)` is `a`
            // the price vector alone: custody priced, no position read
            FLAMMGateLib.Book memory pb = FLAMMGateLib.custodyBook($);
            FLAMMGateLib.priceIn($, pb);
            // a frame's venues share one position at the lender, and the Router holds each to its own pin alone: while
            // one of them lacks, the release takes no more of the frame than its venues' triggers spare. The bound
            // reads the book's prices, scales and custody, and each venue's position at the Router.
            if ($.gatedVenues != 0 && FLAMMTopUpLib.frameBound(pb, a, amount, FLAMMStore.NO_PAIR) != amount) {
                revert RoomExhausted();
            }
            FLAMMStore.setHeld($, a, FLAMMStore.heldOf($, a) + r.reclaim(uint8(a), amount, pb.usd));
            // custody-blind: a release lowers what the gate reads as backing, so it holds after it, every venue within
            // its trigger; it posts nothing to make it so
            if (FLAMMBlindLib.blind($, pb)) FLAMMBlindLib.blindGate($, FLAMMLawLib.NONE, 0, type(uint256).max);
            FLAMMStore.reconcile($);
            emit CollateralReleased(uint8(a), amount, msg.sender);
        } else if (kind == IFLAMM.MaintainKind.Refinance) {
            // The grant is the bridge budget for a move between accounts; a pool short of custody of the debt token
            // reverts `InsufficientBridge`.
            _requireNoLoss($, b, FLAMMStore.LOSS_LEG_COLLATERAL);
            IMMRouter.VenueView memory v = r.venue(address(this), a);
            address token = FLAMMStore.tokenOf($, v.debt);
            uint256[] memory usd = FLAMMGateLib.pairUsd($, v.pair);
            uint256 before = FLAMMStore.balanceOfThis(token);
            FLAMMGateLib.wake($, uint256(1) << b);
            FLAMMStore.grant($, token, Math.min(amount, FLAMMStore.heldOf($, v.debt)));
            // Accrued first, so a kind that projects its debt reads the lender's own balance, which the bridge's
            // repay then clears exactly, even after someone else's repay rewrote the borrow record.
            r.accrueExcept(0, 0);
            r.refinanceDebt(a, b, amount, usd);
            FLAMMStore.revoke($, token);
            FLAMMStore.setHeld($, v.debt, FLAMMStore.heldOf($, v.debt) + FLAMMStore.balanceOfThis(token) - before);
            _requireFrameCovered($, r, a, b, v);
        } else if (kind == IFLAMM.MaintainKind.FundedRefinance) {
            // The caller lends the move's shortfall, sized on the debt the Router reads, accrued first as `Refinance`
            // does, and takes it back below: custody stands, as the balance read here is the one before the loan. The
            // pool cannot see whether the Router will bridge, so the caller's choice of this kind decides: a move that
            // takes no bridge lends and returns the loan, costing the caller its gas.
            _requireNoLoss($, b, FLAMMStore.LOSS_LEG_COLLATERAL);
            IMMRouter.VenueView memory v = r.venue(address(this), a);
            address token = FLAMMStore.tokenOf($, v.debt);
            uint256[] memory usd = FLAMMGateLib.pairUsd($, v.pair);
            uint256 before = FLAMMStore.balanceOfThis(token);
            FLAMMGateLib.wake($, uint256(1) << b);
            r.accrueExcept(0, 0);
            uint256 held = FLAMMStore.heldOf($, v.debt);
            uint256 want = Math.min(amount, IFinancingAccount(v.account).debtOf(v.id));
            uint256 lent = want > held ? want - held : 0;
            if (lent != 0) FLAMMStore.pull(token, lent);
            FLAMMStore.grant($, token, Math.min(amount, held + lent));
            r.refinanceDebt(a, b, amount, usd);
            FLAMMStore.revoke($, token);
            if (lent != 0) FLAMMStore.safeTransfer(token, msg.sender, lent);
            FLAMMStore.setHeld($, v.debt, held + FLAMMStore.balanceOfThis(token) - before);
            _requireFrameCovered($, r, a, b, v);
        } else {
            _requireNoLoss($, b, FLAMMStore.LOSS_LEG_SUPPLY);
            FLAMMGateLib.wake($, uint256(1) << b);
            r.migrateSupply(a, b, amount);
        }
    }

    /// @dev Reverts `VenueReportsLoss` where venue `id`'s lender reports a loss on the leg a move would add to, its
    ///      collateral or its supply (`leg`, `FLAMMKeptLib.lossAtFloor`): NAV cuts that leg and counts
    ///      custody at par, so the move would lower NAV by the loss's share of it in the call. So too where the
    ///      venue's haircut is a redemption fee and any fee stands on that leg (`FLAMMStore.LOSS_LEG_FEES`): the way
    ///      out pays it, and no move back returns it. Read only on a pool that lists a venue whose kind reports a
    ///      loss (`FLAMMStore.LOSS_MARKS`).
    function _requireNoLoss(FLAMMStore.S storage $, uint16 id, uint256 leg) private view {
        if (
            $.features & FLAMMStore.LOSS_MARKS != 0
                && FLAMMKeptLib.lossAtFloor(uint256(1) << id, leg | FLAMMStore.LOSS_LEG_FEES)
        ) revert VenueReportsLoss();
    }

    /// @dev After a move of venue `a`'s (`v`) debt to venue `b`, its share of `a`'s collateral with it
    ///      (`IMMRouter.refinanceDebt`), between two accounts one of which at least is a frame's, whose venues share
    ///      one position at the lender, while the Router held each end to its own pin alone and the release to the
    ///      source's spare room at the lender. Out of a frame, that collateral left it, and a venue of the frame under
    ///      its own trigger stands on its mates' collateral, the part `a` held over its own trigger among it. Into a
    ///      frame, the debt joined it with collateral at the source's ratio, which may sit under what the debt's
    ///      trigger asks though within the pin on the destination's whole post: the rest then comes out of what the
    ///      frame held over its triggers, on which a mate under its own may stand. So either move reverts
    ///      `RoomExhausted` where it leaves a frame posting the pair's collateral token with a venue under its own
    ///      trigger and its recognized collateral not over its venues' triggers, summed, as a swap's reclaim reads
    ///      them (`FLAMMTopUpLib.frameBound`, at the priced custody book, for one unit of the token). The keeper then
    ///      moves a smaller part, or first covers the venue that lacks (a top-up, a repay). The read is the frames'
    ///      state after the move, so a frame that sat under its triggers before it holds every such move until it is
    ///      topped up, a move that would bring it collateral over what its debt asks and a move at another frame
    ///      posting the token among them; it reverts `PriceUnchecked` while an indebted venue of such a frame has no
    ///      price for its pair. A move within one account, or between two accounts neither of which is a frame's (a
    ///      pair's own, or one at a kind that refuses no action), reads nothing.
    function _requireFrameCovered(
        FLAMMStore.S storage $,
        IMMRouter r,
        uint16 a,
        uint16 b,
        IMMRouter.VenueView memory v
    ) private view {
        uint256 gated = $.gatedVenues;
        if (((gated >> a) | (gated >> b)) & 1 == 0) return;
        address to = r.venue(address(this), b).account;
        if (to == v.account || !(_frames(gated >> a, v.account) || _frames(gated >> b, to))) return;
        FLAMMGateLib.Book memory pb = FLAMMGateLib.custodyBook($);
        FLAMMGateLib.priceIn($, pb);
        if (FLAMMTopUpLib.frameBound(pb, v.coll, 1, FLAMMStore.NO_PAIR) == 0) revert RoomExhausted();
    }

    /// @dev Whether `account` is a frame's: its venue's kind can refuse an action (bit 0 of `gated`, the venue's bit of
    ///      `FLAMMStore.S.gatedVenues`), as the kinds whose accounts can be a frame's do, and it answers no collateral
    ///      token.
    function _frames(uint256 gated, address account) private view returns (bool) {
        return gated & 1 != 0 && IFinancingAccount(account).COLLATERAL_ASSET() == address(0);
    }

    // ------------------------------------------------------------------ emergency path (bound pool only)
    /// @dev Acts on the venue's account directly, so the Router's pause does not apply; the Router's trackers re-sync
    ///      best-effort. `Repay` pays the venue's debt token from custody, any shortfall pulled from the caller as a
    ///      donation; a repayment the venue cannot absorb stays in custody. `TopUp` posts the venue's collateral token
    ///      at a live venue, a token the pool owes nowhere (`NothingToMaintain` otherwise, as `maintain`'s top-up), at
    ///      a venue whose lender reports a loss on its collateral only where the venue owes, and then the operator's
    ///      alone (`VenueReportsLoss` otherwise, as `maintain`'s top-up: a venue that owes takes the operator's post
    ///      that cures it, and NAV bears the loss's share of it; the guardian's is refused, as the post takes any size
    ///      custody holds), never where an exit would forfeit the post (`VenueFrozen`: a gated venue that allows no
    ///      action and owes no more than `MMRouterLib.RELEASE_SLACK`); `WithdrawSupplied` and `WithdrawCollateral`
    ///      credit custody of the token they recall. Under a redemption fee on the venue's collateral the post pays
    ///      that fee out of NAV, so there only the operator's lands, at a venue that owes: the one post that cures a
    ///      venue nearing liquidation under a fee. It is one of the three posts that still put custody into a fee venue
    ///      under a fee (`FLAMMPolicyLib.setDials`): this `TopUp`, the collateral maintainer's post, which the
    ///      venue-oracle band sizes, and an entry's restoring leg, as a taker's draw there is refused; anyone's
    ///      settlement of the void's claim pays the fee too, on its way out, and spends no custody. An indebted fee
    ///      venue releases nothing while the fee is set, so once custody is spent the remaining holders' exits refuse
    ///      (`CustodyMismatch`) until the fee ends or the venue owes nothing (`FLAMMFlowLib.redeem`): each of those
    ///      posts can spend that custody, and a repay that clears the venue's whole debt (a buy's, a flush, an
    ///      emergency `Repay`) is the cure that pays no fee and frees the stall; one that leaves any debt frees
    ///      nothing. An entry's pro-rata post and borrow also reach an owing fee venue, and an exit of those shares is
    ///      paid from custody; a custody-blind refill's borrow at a fee venue that needs no new post lands too. No kind
    ///      moves a token whose custody a fence holds out (`InvalidConfig`), at any venue, live, retired or fenced, but
    ///      the operator's `TopUp` at a fenced venue, which the operator then pays whole, custody untouched: what the
    ///      venue took, refunded or released would land in custody the fence holds out, which no exit pays out and its
    ///      lift moves whole, so a token that then refused the pool would hold every exit and the lift. Which of these
    ///      a venue's outage leaves live is its kind's ({IFinancingAccount}): at a Morpho Blue market whose rate model
    ///      is unreadable only `TopUp`, and only on an indebted venue. The last branch is `WithdrawCollateral`: ABI
    ///      decoding refuses any other `kind` before the body runs. At a fenced venue the operator's `TopUp` (the
    ///      core's owner's, never the guardian's) lands while the pool's part there is not written off: NAV does not
    ///      read then, so the post, from the custody the pool owns of the collateral token, moves no price, the slot
    ///      stays out of the book, and a fenced venue that owes keeps one cure the pool funds, which no claim of any
    ///      size closes. While claims are open on the venue's record the position is shared with them, and a claim's
    ///      collateral share is its part of what the Router recognizes there (`FLAMMClaimLib.shares`), the post
    ///      included: so the caller pays the claims' share of the post into custody, in the collateral token, `assets *
    ///      claimed / (live + claimed)` of the venue's record, rounded up (`FLAMMStore.pull`: the caller's allowance to
    ///      the pool, a short delivery reverting `CustodyMismatch`). Custody then gives up the pool's part of the post
    ///      alone: the shares that stay are whole in the collateral token, at no price; the claims receive the
    ///      operator's own funds; an operator that holds the claims takes its payment back at their settlement; and an
    ///      exit after the post takes its slice of that custody and its part of the position as posted. The share is
    ///      read at execution: an exit or an unwind of the pool's part landing first raises it and a settlement lowers
    ///      it, so the caller's allowance of the collateral token to the pool is the cap on what it pays, `assets` at
    ///      most. At a frame's account the record of the venue named answers for the frame, whose records hold the same
    ///      fractions (`FLAMMClaimLib`). Nor does the pool's custody bound that top-up: what the custody the pool owns
    ///      cannot give of the post is the caller's too, so it pays the larger of the claims' share and `assets` less
    ///      that custody, and custody gives up the rest, never the fee the pool owes in the token. A fence of the
    ///      collateral token's own custody, or a custody already posted or paid out to exits, then leaves the cure open
    ///      at the operator's cost; while that fence stands the operator pays the post whole, so its custody stays as
    ///      the fence left it. What the caller pays past the claims' share lands in the pool's part of the position,
    ///      the claims' share of the whole post being paid by then: it is the caller's gift to the shares that stay,
    ///      who give up for the post only what custody they own. That top-up apart, at a fenced venue (`FLAMMFenceLib`)
    ///      the pool's position is shared with the fence's claims: `Repay` takes no custody and is all the caller's
    ///      donation, and the other three are refused (`IMMRouter.VenueIsFenced`). At a frame's account a debt-free
    ///      venue's collateral backs its mates, which share one position at the lender: `WithdrawCollateral` there
    ///      needs every venue of the frame debt-free (`VenueAccountBase.DebtOutstanding` while another owes, as the
    ///      account answers while the venue itself does), so the caller repays each mate first (`Repay`), as a pair's
    ///      own account asks of its one venue. It reads each mate's raw position at the account and no price, which may
    ///      be unchecked in an emergency, so it takes no part of the collateral while a mate owes, however much the
    ///      frame could spare; a mate whose lender takes no repay now holds the withdrawal until it does.
    function emergency(IFLAMM.EmergencyKind kind, uint16 id, uint256 assets) public {
        FLAMMStore.S storage $ = FLAMMStore.s();
        if (assets == 0) revert InvalidAmount();
        // a reading of the loss marks before any check of them
        if ($.features & FLAMMStore.LOSS_MARKS != 0) FLAMMKeptLib.recordLossMarks();
        IMMRouter.VenueView memory vv = $.router.venue(address(this), id);
        (IFinancingAccount account, bytes32 m) = (IFinancingAccount(vv.account), vv.id);
        bool fenced = vv.status & VENUE_FENCED != 0;
        // No kind moves a token whose custody a fence holds out, at any venue, so none lands in custody the fence
        // holds out: the debt token's for a repay and a supply withdrawal, the collateral token's for a post and a
        // collateral withdrawal; but the operator's post at a fenced venue, which it then pays whole (below).
        if (kind == IFLAMM.EmergencyKind.Repay) {
            if (FLAMMFenceLib.isOut($, vv.debt)) revert InvalidConfig();
            (address token, uint256 held) = (FLAMMStore.tokenOf($, vv.debt), FLAMMStore.heldOf($, vv.debt));
            uint256 own = fenced ? 0 : FLAMMStore.ownHeld($, vv.debt);
            uint256 fromPool = assets > own ? own : assets;
            if (assets != fromPool) FLAMMStore.pull(token, assets - fromPool);
            FLAMMStore.safeTransfer(token, address(account), assets);
            uint256 before = FLAMMStore.balanceOfThis(token);
            uint256 repaid = account.emergencyRepay(m, assets);
            uint256 refunded = FLAMMStore.balanceOfThis(token) - before;
            if (repaid + refunded != assets) revert InvalidAmount();
            FLAMMStore.setHeld($, vv.debt, held - fromPool + refunded);
        } else if (
            fenced
                && (kind != IFLAMM.EmergencyKind.TopUp || msg.sender != $.core.owner()
                    || ($.fenceWord >> (FLAMMStore.UNWRITTEN_SHIFT + id)) & 1 == 0)
        ) {
            revert IMMRouter.VenueIsFenced();
        } else if (kind == IFLAMM.EmergencyKind.TopUp) {
            // A retired venue's recognized collateral is outside NAV and the pro-rata legs.
            if (vv.status & VENUE_RETIRED != 0) revert IMMRouter.VenueIsRetired();
            if (!fenced && FLAMMFenceLib.isOut($, vv.coll)) revert InvalidConfig();
            // As `maintain`'s top-up, no post of a token the pool owes: a venue that owes passes, its position read
            // raw, with no rate model, as this path must answer while the Router cannot.
            (, uint256 borrowShares,) = account.positionOf(m);
            if (borrowShares == 0) {
                (uint16 owed,) = $.router.drawn(address(this));
                if ((owed >> vv.coll) & 1 != 0) revert NothingToMaintain();
            }
            // nor a post into a collateral leg whose lender reports a loss, which lowers NAV by the loss's share of
            // it: none at a venue that owes nothing, where it would cure nothing, and at one that owes the operator's
            // alone, fenced or not, as this path must answer while the Router cannot and takes any size custody holds
            if (borrowShares == 0 || msg.sender != $.core.owner()) {
                _requireNoLoss($, id, FLAMMStore.LOSS_LEG_COLLATERAL);
            }
            // nor a post an exit would forfeit: at a gated venue that allows no action and owes no more than the
            // lenders' rounding, every exit forfeits its slice (`FLAMMFlowLib.proRata`), read from the account alone
            if (
                ($.gatedVenues >> id) & 1 != 0 && account.actions(m) == 0
                    && account.debtOf(m) <= MMRouterLib.RELEASE_SLACK
            ) revert VenueFrozen();
            uint256 held = FLAMMStore.heldOf($, vv.coll);
            // none of a token whose custody is out: the operator's post at a fenced venue is then its own, whole
            uint256 own = FLAMMFenceLib.isOut($, vv.coll) ? 0 : FLAMMStore.ownHeld($, vv.coll);
            address token = FLAMMStore.tokenOf($, vv.coll);
            uint256 fee;
            if (fenced) {
                // the open claims' share of the post, rounded up, is the caller's to pay: custody gives up the pool's
                // part of it alone, and no more than the pool owns of it, the rest the caller's too. A fenced slot
                // keeps its idle bit, the mark of the pool's part there.
                FLAMMStore.Fence storage f = $.fences[id];
                uint256 claimed = f.claimed;
                if (claimed != 0) fee = Math.mulDiv(assets, claimed, f.live + claimed, Math.Rounding.Up);
                if (assets > own + fee) fee = assets - own;
                if (fee != 0) FLAMMStore.pull(token, fee);
            } else {
                if (assets > own) revert InvalidAmount();
                FLAMMGateLib.wake($, uint256(1) << id);
            }
            // the caller's part first: the post may pass what custody held
            FLAMMStore.setHeld($, vv.coll, held + fee - assets);
            FLAMMStore.safeTransfer(token, address(account), assets);
            uint256 units = account.emergencyTopUp(m, assets);
            // the Router's lock, held by a callback, is no reason to leave the post out of its tracker: NAV would read
            // low by it. Any other failure is swallowed, as this path must answer while the Router cannot.
            try $.router.recognizeCollateral(id, units) {}
            catch (bytes memory reason) {
                ReentrancyGuardLib._passOnLock(reason);
            }
        } else {
            bool supply = kind == IFLAMM.EmergencyKind.WithdrawSupplied;
            uint8 t = supply ? vv.debt : vv.coll;
            if (FLAMMFenceLib.isOut($, t)) revert InvalidConfig();
            address token = FLAMMStore.tokenOf($, t);
            uint256 before = FLAMMStore.balanceOfThis(token);
            if (supply) {
                account.emergencyWithdrawSupplied(m, assets, 0);
            } else {
                _requireMatesOweNothing($, id, account);
                account.emergencyWithdrawCollateral(m, assets);
            }
            FLAMMStore.setHeld($, t, FLAMMStore.heldOf($, t) + (FLAMMStore.balanceOfThis(token) - before));
            try $.router.syncManaged(id) {}
            catch (bytes memory reason) {
                ReentrancyGuardLib._passOnLock(reason);
            }
        }
        FLAMMStore.reconcile($);
        emit EmergencyAction(uint8(kind), id, assets, msg.sender);
    }

    /// @dev Reverts `VenueAccountBase.DebtOutstanding` while a venue beside `id` at its lender account `account` owes:
    ///      every other slot the Router lists there where the account is a frame's (`FLAMMFenceLib.matesOf`), retired
    ///      ones too, as the lender counts the frame's whole debt against the collateral that would leave; none at a
    ///      pair's own account, where `id` is its own health basis. Each mate's borrow units are read raw at the
    ///      account (`IFinancingAccount.positionOf`: no accrual, no rate model, no price), a frame venue's its part of
    ///      the loan market's debt, rounded up, so zero only where it owes nothing.
    function _requireMatesOweNothing(FLAMMStore.S storage $, uint16 id, IFinancingAccount account) private view {
        IMMRouter r = $.router;
        uint256 mates = FLAMMFenceLib.matesOf($, id) & ~(uint256(1) << id);
        for (uint256 i; mates >> i != 0; ++i) {
            if ((mates >> i) & 1 == 0) continue;
            (, uint256 borrowShares,) = account.positionOf(r.venue(address(this), uint16(i)).id);
            if (borrowShares != 0) revert VenueAccountBase.DebtOutstanding();
        }
    }

    // ------------------------------------------------------------------ bootstrap and seeds
    /// @notice `FLAMM.bootstrap`'s body, under its one-time guard: pulls `assets` of the pool asset into custody, which
    ///         tracks nothing before it, and sets the fee mark at par. Returns the shares at par, `assets` at 18
    ///         decimals, of which the pool mints `FLAMMStore.MINIMUM_SHARES` to the dead address and the rest to `to`.
    ///         `InvalidAmount` on a zero `assets` or `to`, `BelowMinimumShares` unless the shares pass those dead ones.
    function bootstrap(FLAMMStore.S storage $, uint256 assets, address to) public returns (uint256 shares) {
        if (assets == 0 || to == address(0)) revert InvalidAmount();
        FLAMMStore.pull($.poolAsset, assets);
        FLAMMStore.setHeld($, 0, assets);
        shares = assets * $.shareScale;
        if (shares <= FLAMMStore.MINIMUM_SHARES) revert BelowMinimumShares();
        // the fee mark at par, 18 decimals of it whatever the pool asset
        $.peakSharePriceWad = uint128(WAD);
        emit Bootstrapped(to, assets, shares - FLAMMStore.MINIMUM_SHARES);
    }

    /// @notice `assets` of token `t` into custody, alone, for the shares they buy at NAV at the checked prices, at the
    ///         supply after the skim the caller ran (`supply`), rounded down. Only before the pool has opened
    ///         (`FLAMMStore.S.opened`, set for good by the first transfer of shares to another address and by the
    ///         first mint to a second holder) and while `to` holds every share but the dead ones (`held`, its
    ///         balance), so the entry's price moves value between no two holders; otherwise it reverts
    ///         `DepositNotPermitted`. The balance at the call alone would pass on shares lent for that call, by a
    ///         holder among others or by the only one, and on shares an escrow holds for their owner. A pool whose
    ///         pro-rata entry waits for the deposit basket (`FLAMMGateLib.basketGated`) reads the flag as every pool
    ///         does: a share handed on or a fee minted elsewhere before its seed of token 1 ends that seed for good.
    ///         NAV per share, and so the fee mark, does not move but for the rounding, which stays with the pool. A
    ///         pool with no band reads no price and mints no shares.
    function seed(FLAMMStore.S storage $, uint8 t, uint256 assets, address to, uint256 supply, uint256 held)
        public
        returns (uint256 shares)
    {
        FLAMMStore.checkToken($, t);
        if (assets == 0 || to == address(0)) revert InvalidAmount();
        if (supply == 0) revert NotBootstrapped();
        if ($.opened || held + FLAMMStore.MINIMUM_SHARES != supply) revert DepositNotPermitted();
        // With no band there is no price to buy shares at: the seed mints none, and its value stays with the holder.
        if (!$.noBand) {
            // read for the pool asset too, so a book that cannot be read reverts with its own error before NAV's check
            uint256 p = FLAMMGateLib.priced($).legs[t].price36;
            uint256 value = assets;
            if (t != 0) {
                if (p == 0) revert PriceUnchecked();
                value = Math.mulDiv(assets, 1e36, p);
            }
            shares = Math.mulDiv(value, supply, FLAMMGateLib.totalAssets($));
            if (shares == 0) revert ZeroShares();
        }
        FLAMMStore.pull(FLAMMStore.tokenOf($, t), assets);
        FLAMMStore.setHeld($, t, FLAMMStore.heldOf($, t) + assets);
        FLAMMStore.reconcile($);
        emit TokenSeeded(t, to, assets, shares);
    }

    // ------------------------------------------------------------------ performance fee
    /// @notice Records what an exit of `num` of `den` shares forfeited at the frozen venues of `venues` (bit `i` for
    ///         venue `i`, each owing no more than the lenders' rounding): its slice of each one's collateral and
    ///         supply, rounded down as the exit would have taken them, per share of the `den - num` it leaves, 1e36,
    ///         rounded up, per token (`FLAMMStore.S.forfeited`), which the next skim that reads the fee mark values
    ///         first and rounds once (`FLAMMGateLib.tryMarkedTotalAssets`). Per share, each forfeit is the gain of the
    ///         shares that stay at that exit, so the record of several exits adds up to the stayers' gain, whatever
    ///         exits follow, and no exit, however small, lifts the fee mark past it. A slice that rounds to nothing
    ///         records nothing.
    function recordForfeit(FLAMMStore.S storage $, uint256 venues, uint256 num, uint256 den) public {
        IMMRouter r = $.router;
        uint256 left = den - num;
        bool any;
        for (uint16 i; venues >> i != 0; ++i) {
            if ((venues >> i) & 1 == 0) continue;
            IMMRouter.VenueView memory v = r.venue(address(this), i);
            (, uint256 coll,, uint256 sup,) = r.venuePosition(address(this), i);
            uint256 c = Math.mulDiv(Math.mulDiv(coll, num, den), 1e36, left, Math.Rounding.Up);
            uint256 u = Math.mulDiv(Math.mulDiv(sup, num, den), 1e36, left, Math.Rounding.Up);
            if (c != 0) $.forfeited[v.coll] += c;
            if (u != 0) $.forfeited[v.debt] += u;
            if ((c | u) != 0) any = true;
        }
        if (any) $.poolBits |= FLAMMStore.POOL_FORFEIT;
    }

    /// @notice Charges the high-water-mark fee on pool asset per share in new shares: the curator's rate to
    ///         `core.feeReceiver()` and the protocol's to the Factory's `protocolFeeReceiver()`, each of the same gain
    ///         over one fee mark; a part whose receiver reads zero is not charged. Abstains while NAV is unchecked or
    ///         the price exceeds `uint128`, so the skim itself never reverts an entry or exit; while a rate is on, an
    ///         entry it would leave a gain unpaid behind is refused instead (`FLAMMFlowLib.feeOn`). `marked` is true
    ///         where the fee mark was read (NAV checked, the price within `uint128`, a gain or none) or there is no
    ///         supply, and only then may a rate rise: a gain an abstaining skim leaves uncharged never pays a rate set
    ///         after it. A pool with no band prices no token past the pool asset, so a gain it shows is none: the skim
    ///         leaves it uncharged and reads no fee mark a rise could use, while the peak still follows its price with
    ///         both rates off. So does one that would charge a fee while a fence holds a pool part, written off or not,
    ///         which the book this read leaves out and every share still owns: no fee mints and the peak waits for the
    ///         part's return or its abandonment, so no fee share takes a slice of the part its gain did not price.
    /// @dev `base = supply * (cur - peak) / cur` at the pre-mint price, and each part is `base * bp / 1e4`
    ///      ({FLAMMFlowLib.split}), so the mint dilutes the realised fee under bp of the gain; the peak moves to the
    ///      price after both mints, rounded up at the fee mark's 18 decimals of par, never recharging it, however often
    ///      a skim runs. Charged gains are never refunded; with both parts off it still raises the peak. What exits
    ///      forfeited at frozen venue marks raises the peak by its value per share before any gain is read
    ///      ({FLAMMFlowLib.mark}), so no rate ever charges a forfeited slice. A receiver is read only for a nonzero
    ///      rate on a gain; a core whose `feeReceiver()` reverts (EverlongCore's cannot) blocks every skim, and so
    ///      every flow, while the curator's rate is on. {pendingFeeShares} mirrors this arithmetic at the loss marks
    ///      stored before this skim records new ones, so where the record lowers or clears a mark the flow's NAV, and
    ///      its fee, read higher than the preview's: exact only where no loss mark changes. `convert` divides
    ///      by NAV, so a pool whose NAV reads zero converts nothing. On a pool with a venue whose kind reports a loss
    ///      (`FLAMMStore.LOSS_MARKS`) it first records each such venue's ratios (`FLAMMKeptLib.recordLossMarks`), so every
    ///      flow, and anyone through `FLAMM.skimPerformanceFee`, keeps the loss marks; a pool with none reads no more
    ///      than the bit.
    function crystallize(FLAMMStore.S storage $, uint256 supply)
        public
        returns (bool marked, address to, uint256 feeShares, address protocolTo, uint256 protocolShares)
    {
        // first, whatever the supply: each loss venue's ratios into its mark, before any read of NAV
        if ($.features & FLAMMStore.LOSS_MARKS != 0) FLAMMKeptLib.recordLossMarks();
        if (supply == 0) return (true, to, 0, protocolTo, 0);
        (bool ok, uint256 assets, uint256 forfeit) = FLAMMGateLib.tryMarkedTotalAssets($);
        (bool m, uint256 cur, uint256 peak) = FLAMMFlowLib.mark($, ok, assets, supply, forfeit);
        marked = m;
        // the fee mark read: what exits forfeited since it last read raised it, and leaves the record
        if (forfeit != 0 && peak != 0) FLAMMStore.takeForfeit($, peak);
        if (cur == 0) return (marked, to, 0, protocolTo, 0);
        (uint256 bp, uint256 pbp) = ($.performanceFeeBp, $.protocolFeeBp);
        if ((bp != 0 || pbp != 0) && FLAMMStore.bandOff($)) return (false, to, 0, protocolTo, 0);
        if (bp != 0) to = $.core.feeReceiver();
        if (pbp != 0) protocolTo = IFLAMMProtocolFee($.factory).protocolFeeReceiver();
        uint256 peakAfter = cur;
        if (to != address(0) || protocolTo != address(0)) {
            // a fence's part, written off or not, is out of the book this read: no fee mints on it, and the fee mark
            // waits
            if (FLAMMStore.parted($)) return (false, to, 0, protocolTo, 0);
            (feeShares, protocolShares) =
                FLAMMFlowLib.split(supply, cur, peak, to == address(0) ? 0 : bp, protocolTo == address(0) ? 0 : pbp);
            uint256 minted = feeShares + protocolShares;
            if (minted != 0) {
                // rounded up, so the price the mint leaves never reads a charged unit over the fee mark again
                peakAfter = Math.mulDiv(assets, WAD, supply + minted, Math.Rounding.Up);
                if (peakAfter > cur) peakAfter = cur;
            }
            emit PerformanceFeeCharged(feeShares, protocolShares, peak, peakAfter);
        }
        $.peakSharePriceWad = uint128(peakAfter);
    }

    /// @notice The shares {crystallize} would mint at `supply`, both parts, without writing: its arithmetic at the NAV
    ///         it reads at the loss marks stored now, before the skim's record of new ones (on a pool with a venue that
    ///         reports a loss the skim's own fee may then differ), the record of forfeits counted as it counts them,
    ///         zero while both rates are 0; an unreadable
    ///         receiver counts as no fee. The previews price at the supply after it, and so do the maxima read from
    ///         them (`FLAMMMaxima`, periphery).
    function pendingFeeShares(FLAMMStore.S storage $, uint256 supply) public view returns (uint256) {
        (uint256 bp, uint256 pbp) = ($.performanceFeeBp, $.protocolFeeBp);
        if (bp == 0 && pbp == 0) return 0;
        (bool ok, uint256 assets, uint256 forfeit) = FLAMMGateLib.tryMarkedTotalAssets($);
        (, uint256 cur, uint256 peak) = FLAMMFlowLib.mark($, ok, assets, supply, forfeit);
        if (cur == 0 || FLAMMStore.bandOff($) || FLAMMStore.parted($)) return 0;
        if (bp != 0) {
            try $.core.feeReceiver() returns (address to) {
                if (to == address(0)) bp = 0;
            } catch {
                bp = 0;
            }
        }
        if (pbp != 0) {
            try IFLAMMProtocolFee($.factory).protocolFeeReceiver() returns (address to) {
                if (to == address(0)) pbp = 0;
            } catch {
                pbp = 0;
            }
        }
        (uint256 feeShares, uint256 protocolShares) = FLAMMFlowLib.split(supply, cur, peak, bp, pbp);
        return feeShares + protocolShares;
    }

}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {
    "src/core/mm/MMRouterLib.sol": {
      "MMRouterLib": "0x95b386d242c061ab2551a0d294c94dfe3948ef2c"
    },
    "src/core/flamm/FLAMMLane.sol": {
      "FLAMMLane": "0x5d81d4a7cfd40c3dfe9e009212545608be90de37"
    },
    "src/core/flamm/FLAMMRoute.sol": {
      "FLAMMRoute": "0xb1ffeae12c53f876aa0e495e9c00c829f47fb0fe"
    },
    "src/periphery/FLAMMMaxima.sol": {
      "FLAMMMaxima": "0x68546ce65986354c5394e4bc2f28027ef490a91b"
    },
    "src/core/flamm/FLAMMLawLib.sol": {
      "FLAMMLawLib": "0xf55c5807b6fbe5555443fd6ddbbd52079849cf45"
    },
    "src/core/flamm/FLAMMOpsLib.sol": {
      "FLAMMOpsLib": "0x0be7fdb3d611b05df90a61778a644654735ecc47"
    },
    "src/core/mm/AaveV3ReadsLib.sol": {
      "AaveV3ReadsLib": "0xa5db415d1af2158dd0a4a3c9c1eada277472803e"
    },
    "src/core/flamm/FLAMMFlowLib.sol": {
      "FLAMMFlowLib": "0x27957f4ddf818de39a1c9dba0bf273a5994cfb77"
    },
    "src/core/flamm/FLAMMGateLib.sol": {
      "FLAMMGateLib": "0x3a05779218510235badcbddcdd78732a16434368"
    },
    "src/core/flamm/FLAMMKeptLib.sol": {
      "FLAMMKeptLib": "0x70cace9076ac8dd6a691ced2f9aa62a5c360bee4"
    },
    "src/core/mm/CTokenMarketLib.sol": {
      "CTokenMarketLib": "0x60e4ab6b6ba72325c58924ee7753b14b37314010"
    },
    "src/core/flamm/FLAMMAdmitLib.sol": {
      "FLAMMAdmitLib": "0x0b107b1f0c64f3716554ccc83b53e492e51ce950"
    },
    "src/core/flamm/FLAMMBlindLib.sol": {
      "FLAMMBlindLib": "0x634d5a14c42fb5bec82a7aea32bf636a8d298fcd"
    },
    "src/core/flamm/FLAMMClaimLib.sol": {
      "FLAMMClaimLib": "0x5dc3bb30c60390ce9522b7e3ca315dd334aa7e91"
    },
    "src/core/flamm/FLAMMFenceLib.sol": {
      "FLAMMFenceLib": "0x9dbba0cbd9d7883f4eedd1c8e08780fac4798f1a"
    },
    "src/core/flamm/FLAMMFloatLib.sol": {
      "FLAMMFloatLib": "0x6b2b25ebba12e78afea697b9ac6d2167a6518935"
    },
    "src/core/flamm/FLAMMQuoteLib.sol": {
      "FLAMMQuoteLib": "0x99de54a108c64ebe23ac7766901c199a91929869"
    },
    "src/core/flamm/FLAMMTopUpLib.sol": {
      "FLAMMTopUpLib": "0xe4be161081d1c9aa91951ca347cc99da35cfac2e"
    },
    "src/core/mm/CTokenRewardsLib.sol": {
      "CTokenRewardsLib": "0x93ab647215a9f9f1050302a76506afcbc0262861"
    },
    "src/core/mm/MMRouterAdminLib.sol": {
      "MMRouterAdminLib": "0x6abb06b1e9cba80888992d366913bb9b7760ea7e"
    },
    "src/core/flamm/FLAMMPolicyLib.sol": {
      "FLAMMPolicyLib": "0x3858e2202cebcb6f12f36a596260dd2ed8f91f06"
    },
    "src/core/flamm/FLAMMSettleLib.sol": {
      "FLAMMSettleLib": "0x4551cddb1de95f5452f6a0f836e047e01833b301"
    },
    "src/core/flamm/FLAMMSharedLib.sol": {
      "FLAMMSharedLib": "0xb852d9cbdda85cbed7da0885bca2714ba1b71005"
    },
    "src/periphery/FLAMMExitMaxima.sol": {
      "FLAMMExitMaxima": "0x6a6a3ff1e834dbbf07dee472e07d1ca977798659"
    },
    "src/hooks/everlong/LeverageLib.sol": {
      "LeverageLib": "0x80396f9f894cc3060dfaa7468c4f576e8b16d055"
    },
    "src/core/flamm/FLAMMMaintainLib.sol": {
      "FLAMMMaintainLib": "0xaa5434e13eb54f37c577229efc981cceceb56417"
    },
    "src/core/flamm/FLAMMPairQuoteLib.sol": {
      "FLAMMPairQuoteLib": "0x3bc57bc05cc9dd1fe18106add8ffc060882055dd"
    },
    "src/hooks/everlong/EverlongOpsLib.sol": {
      "EverlongOpsLib": "0xf6d56f4ed6a7c441fd96c53a327026bac19dfeef"
    }
  },
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
    "forge-std/=lib/forge-std/src/",
    "solady/=lib/solady/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.