Verified contractExactUNLICENSED
FLAMMFlowLib
Address0x2577d707d41209489b2ef53101a4f6badd4e3473
- 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,536
- Creation transaction
- 0xb084796480…d59a54210c
- 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/FLAMMFlowLib.solmain55.24 KB
- lib/openzeppelin-contracts-compat/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/openzeppelin-contracts-compat/contracts/token/ERC20/IERC20.sol2.77 KB
- lib/openzeppelin-contracts-compat/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- lib/openzeppelin-contracts-compat/contracts/utils/math/Math.sol12.51 KB
- lib/openzeppelin-contracts-compat/contracts/utils/math/SafeCast.sol35.08 KB
- lib/openzeppelin-contracts-upgradeable-compat/contracts/proxy/utils/Initializable.sol8.91 KB
- lib/openzeppelin-contracts-upgradeable-compat/contracts/token/ERC20/ERC20Upgradeable.sol12.23 KB
- lib/openzeppelin-contracts-upgradeable-compat/contracts/utils/ContextUpgradeable.sol1.19 KB
- src/core/PriceFeed.sol19.12 KB
- src/core/flamm/FLAMM.sol54.32 KB
- src/core/flamm/FLAMMAdmitLib.sol37.26 KB
- src/core/flamm/FLAMMBlindLib.sol41.3 KB
- src/core/flamm/FLAMMClaimLib.sol49.42 KB
- src/core/flamm/FLAMMClaimVault.sol1.65 KB
- src/core/flamm/FLAMMFenceLib.sol72.83 KB
- src/core/flamm/FLAMMFloatLib.sol57.91 KB
- src/core/flamm/FLAMMGateLib.sol87.39 KB
- src/core/flamm/FLAMMKeptLib.sol45.59 KB
- src/core/flamm/FLAMMLane.sol70.27 KB
- src/core/flamm/FLAMMLawLib.sol60.67 KB
- src/core/flamm/FLAMMMaintainLib.sol41.67 KB
- src/core/flamm/FLAMMOpsLib.sol32.2 KB
- src/core/flamm/FLAMMPolicyLib.sol39.49 KB
- src/core/flamm/FLAMMQuoteLib.sol16.89 KB
- src/core/flamm/FLAMMRoute.sol16.45 KB
- src/core/flamm/FLAMMSettleLib.sol42.92 KB
- src/core/flamm/FLAMMSharedLib.sol13.11 KB
- src/core/flamm/FLAMMStore.sol135.42 KB
- src/core/flamm/FLAMMSwapLib.sol55.65 KB
- src/core/flamm/FLAMMTopUpLib.sol48.97 KB
- src/core/mm/MMRouterAdminLib.sol24.07 KB
- src/core/mm/MMRouterLib.sol72.71 KB
- src/core/mm/VenueAccountBase.sol15.61 KB
- src/core/mm/VenueReads.sol2.05 KB
- src/interfaces/core/IDepositAllowlist.sol1.06 KB
- src/interfaces/core/IEverlongCore.sol889 B
- src/interfaces/core/IPriceFeed.sol3.71 KB
- src/interfaces/core/flamm/IFLAMM.sol52.68 KB
- src/interfaces/core/flamm/IFLAMMHooks.sol8.36 KB
- src/interfaces/core/flamm/IHookCapabilities.sol2.63 KB
- src/interfaces/core/flamm/IPairHook.sol14.14 KB
- src/interfaces/core/mm/IAccountDeployer.sol2.99 KB
- src/interfaces/core/mm/IFinancingAccount.sol46.04 KB
- src/interfaces/core/mm/IHeldRepay.sol2.61 KB
- src/interfaces/core/mm/IMMRouter.sol70.37 KB
- src/interfaces/utils/integrations/IAggregatorV3Interface.sol818 B
- src/libraries/Constants.sol2.11 KB
- src/libraries/DelayLib.sol11.22 KB
- src/libraries/ReentrancyGuardLib.sol2.52 KB
- src/libraries/SafeTransferLib.sol5.11 KB
- src/propamm/libraries/PropAMMLaneLib.sol2.31 KB
src/core/flamm/FLAMMFlowLib.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, Paused, PegBroken, Expired, InvalidAmount, NotBootstrapped, DepositNotPermitted,
DepositCapExceeded, BelowMinimumShares, ZeroShares, Slippage, TokenInExceeded, TokenOutBelowMin,
CustodyMismatch, PriceUnchecked, ProRataDeposit, ProRataRedeem, BookOwesPoolAsset, VenueFrozen, BasketNotRecorded,
LedgerBoundBreached, ExitWorsensLedger, WAD
} from "src/core/flamm/FLAMMStore.sol";
import {FLAMMAdmitLib} from "src/core/flamm/FLAMMAdmitLib.sol";
import {FLAMMGateLib} from "src/core/flamm/FLAMMGateLib.sol";
import {FLAMMLawLib} from "src/core/flamm/FLAMMLawLib.sol";
import {FLAMMMaintainLib} from "src/core/flamm/FLAMMMaintainLib.sol";
import {FLAMMTopUpLib} from "src/core/flamm/FLAMMTopUpLib.sol";
import {FLAMMKeptLib} from "src/core/flamm/FLAMMKeptLib.sol";
import {FLAMMQuoteLib} from "src/core/flamm/FLAMMQuoteLib.sol";
import {IFLAMM} from "src/interfaces/core/flamm/IFLAMM.sol";
import {IMMRouter} from "src/interfaces/core/mm/IMMRouter.sol";
import {MMRouterLib} from "src/core/mm/MMRouterLib.sol";
import {CAN_SUPPLY, CAN_WITHDRAW_SUPPLY, IFinancingAccount} from "src/interfaces/core/mm/IFinancingAccount.sol";
import {IDepositAllowlist} from "src/interfaces/core/IDepositAllowlist.sol";
/// @notice Hook-free LP settlement (no hook or callback runs on an entry, an exit or a redemption): an entry or an exit
/// scales every token's custody and each live venue's collateral, debt and supply pro rata; a retired venue
/// carries no leg. Each token's legs net to one transfer, never converted. An entry pays in what the pool holds
/// and posts of a slice, rounded up, and takes what it owes borrowed for it, rounded down; an exit takes what
/// it holds, rounded down, and repays what it owes, rounded up, each debt leg a few units more (the lender's
/// rounding, below). The spread fee the pool owes the protocol nets each token's legs as a debt that stays in
/// custody. A release a venue cannot make now is paid from custody. An exit's slice at a venue whose lender
/// cannot pay all of its face is paid cut by that share (the larger of the lender's ratio and the pool's record
/// of it, `FLAMMKeptLib.largerLoss`), which stays in custody: the exiter bears its share of the venue's loss
/// and the holders who stay none of it, whether the venue releases the slice or custody pays it; at a frozen
/// venue mark an exit forfeits its slice of a venue that owes nothing (or no more than the lenders' rounding),
/// recorded so no skim counts it as performance, and refuses where one owes more. The fee mark and split of the
/// performance fee live here too (every flow crystallizes the fee first, `FLAMMMaintainLib.crystallize`). The
/// previews and the conversions run in `FLAMMQuoteLib`, on the legs and the fee arithmetic shared from here;
/// the flows' maxima run outside the pool (`FLAMMMaxima`, periphery), on the previews' legs.
library FLAMMFlowLib {
/// @dev The most a restoring collateral leg gives up to rounding before an entry shrinks its borrow instead of
/// reverting at the pin: the legs' own ceilings, a unit each.
uint256 internal constant FIT_DUST = 2;
/// @dev The legs of one flow: per venue, the collateral, debt and supply legs ({IFLAMM.VenueLeg}) and the venue's
/// two tokens; per token, the custody slice, the collateral legs together (an entry's after its top-ups), the
/// pro-rata collateral slices before them, the supply and debt legs together, the net in and the net out; per
/// venue, an entry's least collateral leg (its top-up; none where it borrows nothing) and the debt its pin
/// allows per collateral unit (`unit`: the pair's price scale times its LTV, rounded up, scaled by 1e36); per
/// venue, an exit's collateral haircut (`loss`, WAD: the share of face its lender cannot pay); the frozen
/// venues whose slices an exit forfeits (`forfeits`, bit `i` for venue `i`), and the venues that cut an exit's
/// supply slice (`supplyCut`, bit `i`); per token, the collateral an exit leaves posted out of its slices, out
/// of its payout: what its units leave at a venue ({FLAMMGateLib.nearUnitsAt}) and what a venue that held its
/// repay keeps (`dust`, {_heldRepay}; empty where it left none).
struct Legs {
IFLAMM.VenueLeg[] venue;
uint8[] coll;
uint8[] debt;
uint256[] held;
uint256[] posts;
uint256[] slices;
uint256[] supplies;
uint256[] owed;
uint256[] tokenIn;
uint256[] tokenOut;
uint256[] least;
uint256[] unit;
uint256[] loss;
uint256 forfeits;
uint256 supplyCut;
uint256[] dust;
uint256[] cuts;
}
// ------------------------------------------------------------------ legs
/// @dev The legs of a flow of `num / den` of the book, rounded against the LP: an entry's paid-in legs up and its
/// borrow legs down, an exit's repaid legs up and its paid-out legs down. A retired or idle slot carries no
/// leg and is not read (`FLAMMStore.unread`): NAV skips it, a retired one's lender may have stopped answering,
/// an idle one holds nothing the Router recognizes, and its leg names its id alone. Interest or a price move
/// lifts an indebted venue over its pair's pin, so an entry's collateral leg at a venue it borrows from is
/// raised to what restores the pin after the borrow, drawing on the pool's custody of the collateral token
/// where the entry's own falls short; an unchecked price keeps the pro-rata leg. An entry into a book that
/// owes then fits its legs, per collateral token, to what it brings plus that custody ({_fit}). Where a token
/// sits moves no value: custody and collateral count alike in NAV. With `exact`, the pool asset's pay-in is
/// `num` itself (`depositProRata`, sized in it), not its slices.
function proRata(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 num, uint256 den, bool entry, bool exact)
internal
view
returns (Legs memory L)
{
(IMMRouter r, uint256 m) = ($.router, b.legs.length);
uint256 n = r.venueCount(address(this));
(L.venue, L.coll, L.debt) = (new IFLAMM.VenueLeg[](n), new uint8[](n), new uint8[](n));
(L.held, L.posts, L.slices, L.supplies) = (new uint256[](m), new uint256[](m), new uint256[](m), new uint256[](m));
(L.owed, L.tokenIn, L.tokenOut) = (new uint256[](m), new uint256[](m), new uint256[](m));
(L.least, L.unit, L.loss) = (new uint256[](entry ? n : 0), new uint256[](entry ? n : 0), new uint256[](n));
Math.Rounding up = entry ? Math.Rounding.Up : Math.Rounding.Down;
uint256[] memory cut = new uint256[](m);
(uint256 gated, uint256 lossy) = ($.gatedVenues, entry ? 0 : $.lossVenues);
for (uint16 i; i < n; ++i) {
IFLAMM.VenueLeg memory v = L.venue[i];
v.id = i;
if (FLAMMStore.unread($, i)) continue;
IMMRouter.VenueView memory vv = r.venue(address(this), i);
(v.pair, L.coll[i], L.debt[i]) = (vv.pair, vv.coll, vv.debt);
(, uint256 coll,, uint256 sup, uint256 debt) = r.venuePosition(address(this), i);
// A frozen venue mark ({FLAMMGateLib.frozen}): no exit repays a debt there, and an exit forfeits its slice
// of a venue that owes nothing, or no more than a lender's rounding (`RELEASE_SLACK`, whose share it leaves
// behind), which stays posted for the holders who remain.
if (
!entry && (gated >> i) & 1 != 0 && (coll | sup | debt) != 0
&& _actions(vv.account, vv.id) == 0
) {
if (debt > MMRouterLib.RELEASE_SLACK) revert VenueFrozen();
L.forfeits |= uint256(1) << i;
continue;
}
v.collateral = Math.mulDiv(coll, num, den, up);
if (entry) {
v.owed = Math.mulDiv(debt, num, den);
} else if (debt != 0) {
// A lender's partial repay may leave up to `RELEASE_SLACK` over the exact rest, which the exit's own
// proportional release and its monotone law would then refuse: an exit repays that much more, at most
// the whole debt, so it leaves no more debt than its share.
v.owed = Math.mulDiv(debt, num, den, Math.Rounding.Up) + MMRouterLib.RELEASE_SLACK;
// The exit that leaves only the bootstrap's dead shares repays the whole debt: their slice of it, which
// no holder could ever repay, can round up to a unit of a lender's own accounts against a collateral
// slice that rounds down to none, and that lender would refuse the release.
if (v.owed > debt || num + FLAMMStore.MINIMUM_SHARES == den) v.owed = debt;
}
v.supplied = Math.mulDiv(sup, num, den, up);
// an exit's slices as the venue's units round: near-whole ones at a venue sharing one reserve (a kind that
// shares one reports its lender's losses too, so it is in `lossy`), and a collateral slice at most what
// keeps the whole units a release could take past the threshold of a venue that still owes: what it leaves
// there the record prices
if (!entry && ((gated | lossy) >> i) & 1 != 0) {
uint256 cs = v.collateral;
(v.collateral, v.supplied) = FLAMMGateLib.nearUnitsAt(
vv.account,
vv.id,
coll,
sup,
cs,
v.supplied,
($.sharedVenues >> i) & 1 != 0 ? n : 0,
debt > v.owed ? uint256($.pairs[vv.pair].ltvWad) | uint256(vv.pair) << 64 : 0
);
if (v.collateral < cs) {
if (L.dust.length == 0) L.dust = new uint256[](m);
L.dust[vv.coll] += cs - v.collateral;
}
}
if ((lossy >> i) & 1 != 0) {
// the share of face the venue's lender cannot pay, cut from the exit's slices, rounded against it; a
// redemption fee (`FLAMMStore.S.feeVenues`) cuts the legs themselves, so the venue burns the exiter's
// units and no more
// each the larger of the lender's ratio now and the venue's loss mark, so a supply to the lender's
// reserve in the exit's transaction lowers no cut
(uint256 cl, uint256 sl) = FLAMMKeptLib.largerLoss(i, vv.account, vv.id);
if (($.feeVenues >> i) & 1 != 0) {
(v.collateral, v.supplied) = (
v.collateral - Math.mulDiv(v.collateral, cl, WAD, Math.Rounding.Up),
v.supplied - Math.mulDiv(v.supplied, sl, WAD, Math.Rounding.Up)
);
} else {
cut[vv.coll] += Math.mulDiv(v.collateral, cl, WAD, Math.Rounding.Up);
cut[vv.debt] += Math.mulDiv(v.supplied, sl, WAD, Math.Rounding.Up);
L.loss[i] = cl;
if (sl != 0) L.supplyCut |= uint256(1) << i;
}
}
L.slices[vv.coll] += v.collateral;
if (entry && v.owed != 0) {
uint256 p = FLAMMGateLib.frameOf(b, vv.coll, vv.debt);
uint256 ltv = $.pairs[vv.pair].ltvWad;
if (p != 0) {
(L.least[i], L.unit[i]) =
(_toPin(coll, debt + v.owed, ltv, p), Math.mulDiv(p, ltv, WAD, Math.Rounding.Up));
}
if (L.least[i] > v.collateral) v.collateral = L.least[i];
}
L.posts[vv.coll] += v.collateral;
L.owed[vv.debt] += v.owed;
L.supplies[vv.debt] += v.supplied;
}
for (uint256 t; t < m; ++t) {
L.held[t] = Math.mulDiv(b.legs[t].held, num, den, up);
}
// A flow's slice of each kept share's debt past the senior claims' (`FLAMMKeptLib.keptLegs`, the pool's and
// the junior claims' share), a debt like the spread fee that stays in custody: an exit's junior claim there
// (`FLAMMFenceLib.recordClaims`) then takes its collateral and supply shares alone. Once the share is
// given up its junior claims' share stays owed from custody till they settle: an entry, open again, nets
// its slice rounded down, so it pays for none of the custody owed out. No price: where the kept venue's
// position does not read an entry refuses (`VenueFrozen`), and an exit nets the debt its unwind read
// (`FLAMMKeptLib.keptLegs`), so no outage there holds an exit. The pool asset's exact entry is sized on its gross legs, so a debt owed in it refuses
// that entry, as the book's own does (`BookOwesPoolAsset`).
uint256[] memory kept;
// the fence word, read once: its kept shares here, and below the tokens whose custody is out
uint256 out = $.fenceWord;
if (out >> FLAMMStore.KEPT_SHIFT != 0) {
bool ok;
(ok,,, kept) = FLAMMKeptLib.keptLegs(m, !entry);
if (!ok) revert VenueFrozen();
if (exact && kept[0] != 0) revert BookOwesPoolAsset();
}
if (entry && (exact || FLAMMGateLib.owes(b))) _fit(L, b, num, exact);
// Each token's legs net to one transfer, its collateral legs at their slices (an exit's posts are its slices),
// the spread fee owed in it a debt like its venue debt, rounded the same way, that stays in custody; an exit's
// slices cut by what their venues' lenders cannot pay, which stays in custody too. An exit pays out none of a
// token whose custody a fence holds out: it leaves its share of that custody as a claim on the token's record
// (`FLAMMFenceLib.fenceToken`), and what it owes in the token past its custody slice, a kept share's debt, it
// pays from that claim first (`FLAMMKeptLib.fromRecord`), so it brings the token in only where the claim
// falls short. Its net there is never an output: a custody slice past what it owes (a debt its lender lowered,
// exits' payments past a debt given up) stays with the pool, and so does the rounding.
out = entry ? 0 : (out >> FLAMMStore.OUT_TOKENS_SHIFT) & 0xffff;
if (out != 0) L.cuts = new uint256[](m);
for (uint256 t; t < m; ++t) {
uint256 pos = L.held[t] + L.supplies[t] + L.slices[t];
if (exact && t == 0) pos = num;
pos = pos > cut[t] ? pos - cut[t] : 0;
uint256 neg = L.owed[t];
if (kept.length != 0) neg += Math.mulDiv(kept[t], num, den, entry ? Math.Rounding.Down : Math.Rounding.Up);
uint256 fw = b.legs[t].fee;
if (fw != 0) {
// token 1's word carries the cheap-lane bit: an entry there waits for the deposit basket where the
// curator's fee may be charged (`FLAMMGateLib.basketGated`), as its preview does; a book with no fee
// word reads none of it
if (entry && t == 1 && fw >> 255 != 0 && FLAMMGateLib.basketGated($)) revert BasketNotRecorded();
fw &= FLAMMGateLib.FEE_MASK;
if (fw != 0) {
// No venue draws a fee owed past custody: an entry's slice of it would come out of the custody
// kept for it, so the entry is refused, as its preview is, until custody covers the fee again.
if (entry) revert CustodyMismatch();
neg += Math.mulDiv(fw, num, den, Math.Rounding.Up);
}
}
if ((out >> t) & 1 != 0) {
if (neg > pos) (L.cuts[t], L.tokenIn[t]) = FLAMMKeptLib.fromRecord($, t, neg - pos, num, den);
continue;
}
(uint256[] memory inc, uint256[] memory dec) = entry ? (L.tokenIn, L.tokenOut) : (L.tokenOut, L.tokenIn);
if (pos > neg) inc[t] = pos - neg;
else dec[t] = neg - pos;
}
// A supply leg under its token's batch moves through custody instead of the venue: an entry's stays in
// custody, and an exit's is paid from custody while custody covers it and the custody leg. The payout is the
// same either way (each token's total leg is unchanged, the cut included), so only where the token sits
// changes. A leg whose action its venue refuses now stays at the venue and reverts there, as a full-size leg
// does: a venue that cannot be read refuses every action at a frozen venue mark, and no flow moves its share
// through custody at that mark. Only a kind that can refuse an action is asked (`FLAMMStore.S.gatedVenues`). An
// exit's leg of a token that backs a debt stays at the venue: custody of it is backing, which the exit's law
// reads; so does one at a venue that cuts its supply, withdrawn at face, as a haircut its own supply lowers in
// the exit's transaction would shave the cut of a slice custody pays.
uint8 action = entry ? CAN_SUPPLY : CAN_WITHDRAW_SUPPLY;
for (uint256 i; i < n; ++i) {
IFLAMM.VenueLeg memory v = L.venue[i];
uint256 sup = v.supplied;
if (sup == 0) continue;
uint256 t = L.debt[i];
if (sup >= $.tokens[t].minSupplyBatch) continue;
if (
!entry
&& (b.legs[t].held < L.held[t] + sup || FLAMMGateLib.backsDebt(b, t) || (L.supplyCut >> i) & 1 != 0)
) continue;
if ((gated >> i) & 1 != 0 && r.venueCapacity(address(this), uint16(i)).actions & action == 0) continue;
L.held[t] += sup;
L.supplies[t] -= sup;
v.supplied = 0;
}
}
/// @dev Venue `id`'s action bits at `account` (`IFinancingAccount.actions`, the one field of its capacity a
/// frozen venue mark reads), read as the high-level call reads them: the account's revert bubbles up, and an
/// answer under a word or past `uint8` reverts empty.
function _actions(address account, bytes32 id) private view returns (uint256 bits) {
bytes4 sel = IFinancingAccount.actions.selector;
assembly ("memory-safe") {
mstore(0x00, sel)
mstore(0x04, id)
if iszero(staticcall(gas(), account, 0x00, 0x24, 0x00, 0x20)) {
let m := mload(0x40)
returndatacopy(m, 0x00, returndatasize())
revert(m, returndatasize())
}
bits := mload(0x00)
if or(lt(returndatasize(), 0x20), gt(bits, 0xff)) { revert(0x00, 0x00) }
}
}
/// @dev The least collateral leg a venue holding `coll` needs for an entry's borrow to leave `debt` at its pair's
/// pin, the posting law's two roundings covering it; `proRata` raises the venue's leg to it.
function _toPin(uint256 coll, uint256 debt, uint256 ltvWad, uint256 price36) private pure returns (uint256 top) {
top = Math.mulDiv(Math.mulDiv(debt, WAD, ltvWad, Math.Rounding.Up), 1e36, price36, Math.Rounding.Up);
return top > coll ? top - coll : 0;
}
/// @dev Fits each collateral token's legs of an entry that borrows, or that pays in exactly `num` of the pool asset
/// (`exact`), to what the entry brings of it (its custody, collateral and supply slices, or `num` of the pool
/// asset), less its supply legs, plus the pool's custody of it, so legs each rounded up never post more than
/// that (an exact entry's pool-asset supply legs give way first, in venue order, so they and its posts never
/// pass `num` and custody together): past it, each leg gives back, in venue order, what it holds over its
/// least (`L.least`), which stays in custody; then a restoring leg gives way. Where it gives up rounding dust
/// (`FIT_DUST` units at most), its borrow shrinks by what that collateral allows at the pin and two units for
/// the Router's roundings, so the entry borrows that much less and the venue stays at its pin; past that the
/// entry and its preview refuse ({refuseUnrestored}), as the two cannot restore it.
function _fit(Legs memory L, FLAMMGateLib.Book memory b, uint256 num, bool exact) private pure {
for (uint256 a; a < b.legs.length; ++a) {
uint256 budget = b.legs[a].held + (exact && a == 0 ? num : L.held[a] + L.slices[a] + L.supplies[a]);
if (exact && a == 0) _fitSupply(L, budget);
uint256 posted = L.posts[a];
if (posted == 0) continue;
budget = budget > L.supplies[a] ? budget - L.supplies[a] : 0;
for (uint256 k; k < 2 && posted > budget; ++k) {
for (uint256 i; i < L.venue.length && posted > budget; ++i) {
if (L.coll[i] != a) continue;
IFLAMM.VenueLeg memory v = L.venue[i];
uint256 keep = k == 0 ? L.least[i] : 0;
uint256 cut = Math.min(posted - budget, v.collateral > keep ? v.collateral - keep : 0);
v.collateral -= cut;
posted -= cut;
if (k == 0 || cut == 0 || cut > FIT_DUST || v.owed == 0) continue;
uint256 drop = Math.min(Math.mulDiv(cut, L.unit[i], 1e36, Math.Rounding.Up) + 2, v.owed);
(v.owed, L.owed[L.debt[i]]) = (v.owed - drop, L.owed[L.debt[i]] - drop);
}
}
L.posts[a] = posted;
}
}
/// @dev An entry, and its preview, refuse (`IMMRouter.Unhealthy`, as the Router's pin would) where a borrow leg's
/// restoring collateral leg was cut past rounding dust ({_fit}): its venue stays past its pin in the
/// collateral the pool recognizes, which the law reads, before any leg moves. A gift at the venue, which the
/// Router's own check counts, makes no venue better there. An exit's legs carry no restoring leg.
function refuseUnrestored(Legs memory L) internal pure {
for (uint256 i; i < L.least.length; ++i) {
IFLAMM.VenueLeg memory v = L.venue[i];
if (v.owed != 0 && v.collateral + FIT_DUST < L.least[i]) revert IMMRouter.Unhealthy();
}
}
/// @dev An exact entry's pool-asset supply legs give way first, in venue order (they bind no pin), so they and its
/// posts never pass `budget`, what it pays and custody holds.
function _fitSupply(Legs memory L, uint256 budget) private pure {
uint256 out = L.supplies[0] + L.posts[0];
if (out <= budget) return;
uint256 over = Math.min(out - budget, L.supplies[0]);
L.supplies[0] -= over;
for (uint256 i; i < L.venue.length && over != 0; ++i) {
if (L.debt[i] != 0) continue;
IFLAMM.VenueLeg memory v = L.venue[i];
uint256 cut = Math.min(over, v.supplied);
(v.supplied, over) = (v.supplied - cut, over - cut);
}
}
/// @dev Reverts `InvalidAmount` unless both vectors cover exactly the tokens from `from` on, so a caller sized
/// before an `addToken` fails rather than leaving the new token unbounded.
function _bound(Legs memory L, uint256[] memory maxIn, uint256[] memory minOut, uint256 from) private pure {
uint256 m = L.tokenIn.length;
if (maxIn.length + from != m || minOut.length + from != m) revert InvalidAmount();
for (uint256 t = from; t < m; ++t) {
if (L.tokenIn[t] > maxIn[t - from]) revert TokenInExceeded();
if (L.tokenOut[t] < minOut[t - from]) revert TokenOutBelowMin();
}
}
/// @dev Moves each token's net leg `v` through custody: with `pull` its net input, pulled from the caller into
/// custody; else its net output, paid to `to` out of it, which custody must hold (`CustodyMismatch`). The
/// custody read before a pull is the one after it: a pull writes no pool storage, and every pool writer holds
/// the shared guard.
function _move(FLAMMStore.S storage $, uint256[] memory v, bool pull, address to) private {
for (uint256 t; t < v.length; ++t) {
if (v[t] == 0) continue;
address token = FLAMMStore.tokenOf($, t);
uint256 h = FLAMMStore.heldOf($, t);
if (pull) FLAMMStore.pull(token, v[t]);
else if (h < v[t]) revert CustodyMismatch();
FLAMMStore.setHeld($, t, pull ? h + v[t] : h - v[t]);
if (!pull) FLAMMStore.safeTransfer(token, to, v[t]);
}
}
/// @dev Snapshots every token's real balance (`bal[m + t]`) so the legs' actual moves can be tracked back, each
/// beside the `2^255` an exit's expected move starts from (`bal[t]`); while a token's fence record is open
/// (`FLAMMStore.SWAP_FENCE`, read with the pool asset from the first word, which also keeps the fee pass on,
/// `FLAMMGateLib.keeps`), a token whose custody the fence holds out reads no balance, as its `balanceOf` may
/// revert, and keeps a zero `bal[t]`, which no leg moves and {_settle} passes over. `fenced`: that record is
/// open.
function _balances(FLAMMStore.S storage $, FLAMMGateLib.Book memory b)
private
view
returns (uint256[] memory bal, bool fenced)
{
uint256 m = b.legs.length;
(address a0, uint8 bits) = ($.poolAsset, $.swapBits);
uint256 out;
if (bits & FLAMMStore.SWAP_FENCE != 0) (fenced, out) = (true, $.fenceWord >> FLAMMStore.OUT_TOKENS_SHIFT);
bal = new uint256[](2 * m);
for (uint256 t; t < m; ++t) {
if ((out >> t) & 1 == 0) {
(bal[t], bal[m + t]) = (1 << 255, FLAMMStore.balanceOfThis(t == 0 ? a0 : $.tokens[t].token));
}
}
}
/// @dev Moves each token's custody by its balance's change since the snapshot `bal` ({_balances}). With `exact`
/// (an exit) it reverts `CustodyMismatch` first unless that change is exactly the expected move `bal[t]`; a
/// token whose custody is out (a zero `bal[t]`) reads no balance: no leg moves it, as its venues are fenced
/// and its custody zero.
function _settle(FLAMMStore.S storage $, uint256[] memory bal, bool exact) private {
uint256 m = bal.length / 2;
for (uint256 t; t < m; ++t) {
(uint256 move, uint256 was) = (bal[t], bal[m + t]);
if (move == 0) continue;
uint256 now_ = FLAMMStore.balanceOfThis(FLAMMStore.tokenOf($, t));
// `now_ - was` must equal `move - 2^255`, both signed
if (exact && now_ + (1 << 255) != move + was) revert CustodyMismatch();
if (now_ != was) FLAMMStore.setHeld($, t, FLAMMStore.heldOf($, t) + now_ - was);
}
}
/// @dev Every borrow leg needs its pair's checked price scale and both of its tokens on peg at the book's prices,
/// which that price scale proves checked in this call ({_onPeg}). A token's peg is read once (`onPeg`, bit
/// `t`): it cannot move inside the call, so the verdicts are those of a read per leg.
function _checkBorrows(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, Legs memory L) private view {
uint256 onPeg;
for (uint256 i; i < L.venue.length; ++i) {
if (L.venue[i].owed == 0) continue;
(uint256 a, uint256 c) = (L.coll[i], L.debt[i]);
if (FLAMMGateLib.frameOf(b, a, c) == 0) revert PriceUnchecked();
uint256 both = (uint256(1) << a) | (uint256(1) << c);
if (onPeg & both == both) continue;
if (!_onPeg($, b, a) || !_onPeg($, b, c)) revert PegBroken();
onPeg |= both;
}
}
/// @dev Whether token `t` sits within its peg band at the book's checked price (`FLAMMGateLib.onPeg`): the rule
/// `PriceFeed.pegOk` applies to the same price, which cannot move inside the call, as a swap reads it.
function _onPeg(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 t) private view returns (bool) {
return FLAMMGateLib.onPeg($, FLAMMStore.tokenOf($, t), b.usd[t]);
}
/// @dev An entry's venue legs: the drawn venues first, each posting then borrowing (their collateral token is never
/// owed, so pulls and custody fund it), then the posts at venues that owe nothing (one may hold the collateral
/// of a token the borrows just drew), then the supply legs, token by token, each grant revoked after its legs.
function _enterLegs(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, Legs memory L) private {
(IMMRouter r, uint256 m) = ($.router, b.legs.length);
for (uint256 a; a < m; ++a) {
if (L.posts[a] != 0) FLAMMStore.grant($, FLAMMStore.tokenOf($, a), L.posts[a]);
}
for (uint256 i; i < L.venue.length; ++i) {
IFLAMM.VenueLeg memory v = L.venue[i];
if (v.owed == 0) continue;
if (v.collateral != 0) r.postCollateral(v.id, v.collateral);
r.borrow(v.id, v.owed, address(this), b.usd);
}
for (uint256 i; i < L.venue.length; ++i) {
IFLAMM.VenueLeg memory v = L.venue[i];
if (v.owed == 0 && v.collateral != 0) r.postCollateral(v.id, v.collateral);
}
for (uint256 a; a < m; ++a) {
if (L.posts[a] != 0) FLAMMStore.revoke($, FLAMMStore.tokenOf($, a));
}
for (uint256 t; t < m; ++t) {
if (L.supplies[t] == 0) continue;
address token = FLAMMStore.tokenOf($, t);
FLAMMStore.grant($, token, L.supplies[t]);
for (uint256 i; i < L.venue.length; ++i) {
IFLAMM.VenueLeg memory v = L.venue[i];
if (v.supplied != 0 && L.debt[i] == t) r.supply(v.id, v.supplied);
}
FLAMMStore.revoke($, token);
}
}
/// @dev The entry both flows share, on the priced or position-only book `b` (priced wherever it owes): the legs at
/// `num / den`, refused where one leaves its venue past its pin ({refuseUnrestored}), their bounds from token
/// `from` on, the borrow legs' prices and pegs, the pull of each token's net input (the pool asset's `num`
/// itself with `exact`), the venue legs, each token's custody settled by its balance's change, the net outputs
/// paid to the caller; then, where the book owes and on every `exact` entry of a pool with a band, one
/// position read that sets the debt-free flags and runs the entry gate against the anchor.
function _enter(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
uint256 num,
uint256 den,
bool exact,
uint256[] memory maxIn,
uint256[] memory minOut
) private returns (Legs memory L) {
(uint256[] memory u0, uint256[] memory g0, uint256[] memory d0, uint256[] memory o0) = FLAMMLawLib.anchorOf(b);
L = proRata($, b, num, den, true, exact);
refuseUnrestored(L);
_bound(L, maxIn, minOut, exact ? 1 : 0);
_checkBorrows($, b, L);
// With `exact` the pool asset's net input is `num` itself, pulled first: the book owes none of it.
_move($, L.tokenIn, true, address(0));
(uint256[] memory before, bool fenced) = _balances($, b);
_enterLegs($, b, L);
_settle($, before, false);
_move($, L.tokenOut, false, msg.sender);
// One position read after the legs serves the gate, the debt-free flags and the idle record, at `b`'s prices
// (`FLAMMQuoteLib.entryGate`). A borrow leg only extends debt its venue already holds, so its token's flag is
// already clear. A pool with no band reads no price and holds no debt: its entry gates nothing. No leg writes
// `b`, so whether it borrows is read from it here.
if (FLAMMGateLib.owes(b) || (exact && !$.noBand)) {
FLAMMQuoteLib.entryGate($, b.usd, u0, g0, d0, o0, 0, LedgerBoundBreached.selector);
}
// as {redeem}'s: no token whose custody is out is read
FLAMMStore.reconcileBut($, fenced ? ($.fenceWord >> FLAMMStore.OUT_TOKENS_SHIFT) & 0xffff : 0);
}
// ------------------------------------------------------------------ entries
/// @notice `FLAMM.depositProRata`: exactly `poolAssets` of the pool asset for that share of what the pool holds,
/// lends and posts of it, and the same share of every other token's legs, bounded from token 1 on. The book
/// is priced with no reverting read, and a token that owes nothing needs no price for its legs or the gate:
/// a book with no debt enters while its feed is unchecked, at pro-rata legs that move no value at any
/// price, unless a fee rate is on (`feeOn`), when the curator's fee mark must read
/// (`FLAMMGateLib.markedAt`: a cheap-lane pool's basket needs token 1's price, a pending forfeit record its
/// tokens' prices). A book that owes the pool asset reverts `BookOwesPoolAsset`.
function depositProRata(
FLAMMStore.S storage $,
uint256 poolAssets,
address receiver,
uint256[] memory maxIn,
uint256[] memory minOut,
uint256 minShares,
uint256 deadline,
uint256 supply
) public returns (uint256 shares, uint256 in1, uint256 out1) {
_entryGuards($, receiver, deadline, supply);
if (poolAssets == 0) revert InvalidAmount();
FLAMMGateLib.Book memory b = FLAMMGateLib.priced($);
FLAMMGateLib.Leg memory L0 = b.legs[0];
if (L0.owed != 0) revert BookOwesPoolAsset();
if (feeOn($) && !FLAMMGateLib.markedAt($, b)) revert PriceUnchecked();
uint256 gross0 = L0.held + L0.supplied + L0.posted;
if (gross0 == 0) revert NotBootstrapped();
shares = Math.mulDiv(poolAssets, supply, gross0);
if (shares == 0) revert ZeroShares();
if (shares < minShares) revert Slippage();
Legs memory L = _enter($, b, poolAssets, gross0, true, maxIn, minOut);
(in1, out1) = (L.tokenIn[1], L.tokenOut[1]);
emit ProRataDeposit(msg.sender, receiver, shares, L.tokenIn, L.tokenOut);
}
/// @notice `FLAMM.mintProRata`: `shares` of `supply` (the supply after the caller's skim, which read the fee mark
/// if `marked`) for that slice of every token's legs, on any book. Its holdings legs are paid in rounded up
/// and its debt legs borrowed for the entrant rounded down, topping up each pair's pin from the pool's
/// custody of its collateral. A book that owes nothing is read without a price, as its slice moves no value
/// at any price, but while a fee rate is on the entry needs a skim that read the fee mark (`feeOn`); a book
/// that owes is priced, and each borrow leg needs its pair's checked price scale and both tokens on peg.
/// Capped by `mintProRataCap` on the supply after it.
function mint(
FLAMMStore.S storage $,
uint256 shares,
address receiver,
uint256[] memory maxIn,
uint256[] memory minOut,
uint256 deadline,
uint256 supply,
bool marked
) public returns (uint256[] memory tokenIn, uint256[] memory tokenOut) {
_entryGuards($, receiver, deadline, supply);
if (shares == 0) revert InvalidAmount();
if (supply + shares > $.mintProRataCap) revert DepositCapExceeded();
// a skim that read no fee mark (a book it cannot price, a share price past the fee mark's range, or no band)
// left a gain unpaid
if (!marked && feeOn($)) revert PriceUnchecked();
FLAMMGateLib.Book memory b = FLAMMGateLib.book($);
if (!holds(b)) revert NotBootstrapped();
if (FLAMMGateLib.owes(b)) FLAMMGateLib.priceIn($, b);
Legs memory L = _enter($, b, shares, supply, false, maxIn, minOut);
(tokenIn, tokenOut) = (L.tokenIn, L.tokenOut);
emit ProRataDeposit(msg.sender, receiver, shares, tokenIn, tokenOut);
}
/// @dev The guards every entry shares: the deadline, the pause, `FEATURE_DEPOSITS`, no token fence holding a pool
/// part (`VenueFrozen`: its parted bits, read while a token's record is open, `FLAMMStore.SWAP_FENCE`, on the
/// word the pause and the features share) and no venue record holding a kept share (`FLAMMStore.KEPT_SHIFT`),
/// the allowlist on the receiver and a bootstrapped supply; the pool refuses a frozen venue mark and a venue
/// fence's part after its skim (`FLAMM`).
function _entryGuards(FLAMMStore.S storage $, address receiver, uint256 deadline, uint256 supply) private view {
if (block.timestamp > deadline) revert Expired();
if ($.paused) revert Paused();
FLAMMStore.requireFeature($, 0); // FEATURE_DEPOSITS
uint256 w = $.fenceWord;
if (
$.swapBits & FLAMMStore.SWAP_FENCE != 0 && (w >> FLAMMStore.PARTED_TOKENS_SHIFT) & 0xffff != 0
|| (w >> FLAMMStore.KEPT_SHIFT) & FLAMMStore.FENCE_VENUES != 0
) revert VenueFrozen();
if (!depositAllowed($, receiver)) revert DepositNotPermitted();
if (supply == 0) revert NotBootstrapped();
}
/// @dev Whether `b` holds anything: a book with every leg zero has no slice to enter.
function holds(FLAMMGateLib.Book memory b) internal pure returns (bool) {
for (uint256 t; t < b.legs.length; ++t) {
if ((b.legs[t].held | b.legs[t].supplied | b.legs[t].posted | b.legs[t].owed) != 0) return true;
}
return false;
}
// ------------------------------------------------------------------ redeem
/// @notice `FLAMM.redeemProRata`: price-free and never paused. The exiter repays its slice of every debt, rounded
/// up and a few units more (at most the venue's debt), and takes its slice of every holding, rounded down.
/// The monotone law holds the exit to no owed token's ratio to its backing rising.
/// @dev - The order ({_exitLegs}): supply withdrawn, collateral released at venues that owe nothing where the exit
/// repays that token, then the repay at each drawn venue, then every other release, at each drawn venue the
/// release its repay frees in proportion, so at a frame's account no release is read before a mate's repay,
/// whose room it may need.
/// - Each token's custody must move by exactly what the venues moved (`CustodyMismatch`); then the net outputs
/// are paid from custody, which pays too what a venue could not release now (a release that waits for an
/// oracle, a drained or held venue), so the exiter takes its share in full, but for a slice under one unit's
/// assets and one at a venue that still owes, which stays posted ({FLAMMGateLib.nearUnitsAt}), while the
/// rest stays posted for the holders who remain; custody short of it refuses (`CustodyMismatch`).
/// - An indebted venue whose lender takes a redemption fee releases nothing while the fee is set (the
/// comptroller kind's rule), so once custody is spent the remaining holders' exits refuse
/// (`CustodyMismatch`) until the fee ends or the venue owes nothing: 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, and one
/// that leaves any debt frees nothing. What posts that custody into an owing fee venue under a fee
/// (`FLAMMPolicyLib.setDials`): the operator's emergency `TopUp`, the collateral maintainer's post, which
/// the venue-oracle band sizes, and an entry's restoring leg; a taker's draw there is refused. 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.
/// - Where a venue takes less of a repay than asked, the rest stays in custody, netting the debt still owed
/// there (per pair too, in the exit gate), and custody pays the collateral that venue keeps posted, refused
/// alike past the dust, which stays posted, out of the payout ({_heldRepay}).
/// - Every slice is paid cut by its venue's haircut; at a frozen venue mark the exit forfeits its slice of a
/// venue that owes nothing and refuses where one owes ({proRata}), and at a venue that still owes it leaves
/// posted what a release in whole units could take past the venue's threshold, its collateral slice cut to
/// keep that much there ({FLAMMGateLib.nearUnitsAt}), each recorded for the fee mark.
/// - Its share of each fence that holds a pool part stays there as its receiver's claim, which the pool
/// records in the same call (`FLAMMFenceLib.recordClaims`) where `parted`, a slot both retired and idle
/// in the Router's word the legs read, or a token's record is open (`FLAMMStore.SWAP_FENCE`, read beside the
/// pool asset), or where `cuts` is not empty: its claim on a token's record less what it paid from that
/// claim (`cuts`, `FLAMMKeptLib.fromRecord`).
function redeem(
FLAMMStore.S storage $,
uint256 shares,
address receiver,
address owner,
uint256[] memory maxIn,
uint256[] memory minOut,
uint256 deadline,
uint256 supply,
uint256 balance
) public returns (uint256[] memory tokenIn, uint256[] memory tokenOut, bool parted, uint256[] memory cuts) {
if (block.timestamp > deadline) revert Expired();
if (shares == 0 || shares > balance) revert InvalidAmount();
if (supply - shares < FLAMMStore.MINIMUM_SHARES) revert BelowMinimumShares();
FLAMMGateLib.Book memory b = FLAMMGateLib.book($);
(uint256[] memory u0, uint256[] memory g0, uint256[] memory d0, uint256[] memory o0) = FLAMMLawLib.anchorOf(b);
Legs memory L = proRata($, b, shares, supply, false, false);
_bound(L, maxIn, minOut, 0);
_move($, L.tokenIn, true, address(0));
// a venue that took a repay short can leave a slice's dust posted, out of the payout (`_heldRepay`): the
// exiter's floors again
uint256[] memory short;
(short, parted) = _exitLegs($, b, L);
if (short.length != 0) _bound(L, maxIn, minOut, 0);
// the custody slices leave with the payout, and what a venue could not release with them
_move($, L.tokenOut, false, receiver);
FLAMMQuoteLib.gateExitAtRead(
$, u0, g0, d0, o0, short, L.forfeits, ExitWorsensLedger.selector, MMRouterLib.RELEASE_SLACK
);
// a token whose custody is out is not read: the book may hold some of it, which exits brought in against a
// kept share's debt (`FLAMMKeptLib.fromRecord`). Only `parted` reads the fence word, as a token's record
// open sets it (`FLAMMStore.SWAP_FENCE`, {_balances})
FLAMMStore.reconcileBut($, parted ? ($.fenceWord >> FLAMMStore.OUT_TOKENS_SHIFT) & 0xffff : 0);
// what it forfeited or left stays with the holders who remain: no gain the fee may charge
if (L.forfeits != 0) FLAMMMaintainLib.recordForfeit($, L.forfeits, shares, supply);
if (L.dust.length != 0) _recordDust($, L.dust, supply - shares);
(tokenIn, tokenOut, cuts) = (L.tokenIn, L.tokenOut, L.cuts);
emit ProRataRedeem(msg.sender, receiver, owner, shares, tokenIn, tokenOut);
}
/// @dev An exit's venue legs, in four passes: the supply legs; the releases at venues that owe nothing whose
/// collateral token the exit repays, as such a release may fund that repay; every drawn venue's repay; then
/// every other release, each drawn venue's in proportion, which reads no price (each repay is granted from
/// custody and the exiter's pull, per token, before the passes, and revoked after them). A drawn venue's
/// collateral is owed nowhere (the Router's drawn sets), so no later release funds a repay, and none is read
/// before one: at a frame's account, whose venues share one position at the lender, a release is cut to the
/// frame's spare room while a mate lacks, and the repays add to that room what a healthy frame's proportional
/// releases take. Each token's balance must then have moved by exactly what the venues moved, withdrawn plus
/// released less repaid, each as the Router reports it (`CustodyMismatch` otherwise, {_settle}), and its
/// custody moves by that. A release the venue makes short (`IMMRouter.withdrawCollateral` releases what it can
/// now) leaves the rest posted, and the payout takes it from custody. A venue that takes less of its repay
/// than asked releases in proportion to what it took, and the rest of the repay stays in custody
/// ({_heldRepay}): per venue, what each did not take (`short`, empty where every venue took it all), which the
/// exit gate nets at that venue's pair. `parted`: a fence may hold a pool part, a slot both retired and idle
/// in the Router's word, read beside the Router, or a token's open record ({_balances}).
function _exitLegs(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, Legs memory L)
private
returns (uint256[] memory short, bool parted)
{
(IMMRouter r, uint256 m) = ($.router, b.legs.length);
(uint256[] memory expect, bool fenced) = _balances($, b);
parted = fenced || $.retiredVenues & $.idleVenues != 0
|| ($.fenceWord >> FLAMMStore.KEPT_SHIFT) & FLAMMStore.FENCE_VENUES != 0;
for (uint256 t; t < m; ++t) {
if (L.owed[t] != 0) FLAMMStore.grant($, FLAMMStore.tokenOf($, t), L.owed[t]);
}
// Pass 0 withdraws the supply legs; pass 1 releases where the exit repays more of the venue's collateral token
// than the venue's own repay, which only a venue that owes nothing meets; pass 2 repays at each drawn venue;
// pass 3 makes every other release. The proportional releases read no price: they take the exit's book's
// vector, which is unpriced (`FLAMMGateLib.book`).
for (uint256 k; k < 4; ++k) {
for (uint256 i; i < L.venue.length; ++i) {
IFLAMM.VenueLeg memory v = L.venue[i];
if (k == 2) {
if (v.owed != 0) {
uint256 paid = r.repay(v.id, v.owed);
expect[L.debt[i]] -= paid;
if (paid < v.owed) {
if (short.length == 0) short = new uint256[](L.venue.length);
short[i] = v.owed - paid;
v.collateral = _heldRepay($, b, L, i, paid);
}
}
} else if (k == 0) {
if (v.supplied != 0) expect[L.debt[i]] += r.withdrawSupplied(v.id, v.supplied, address(this));
} else {
uint256 c = v.collateral;
if (c != 0 && (L.owed[L.coll[i]] > v.owed) == (k == 1)) {
uint256 got = r.withdrawCollateral(v.id, c, b.usd, true);
expect[L.coll[i]] += got;
if (got < c) _fromOwnCustody(b, L, L.coll[i], c - got);
}
}
}
}
for (uint256 t; t < m; ++t) {
if (L.owed[t] != 0) FLAMMStore.revoke($, FLAMMStore.tokenOf($, t));
}
_settle($, expect, true);
}
/// @dev What a venue could not release now (`short` of token `a`) the exit's payout takes from custody, beside the
/// exiter's own slice of it: refused (`CustodyMismatch`) past the custody the pool owns, so the custody kept
/// for the protocol's spread fee never pays an exiter.
function _fromOwnCustody(FLAMMGateLib.Book memory b, Legs memory L, uint256 a, uint256 short) private pure {
uint256 take = L.held[a] + short;
if (take > b.legs[a].held) revert CustodyMismatch();
L.held[a] = take;
}
/// @dev Venue `i` took `paid` of the exit's repay leg, less than asked (a minimum position holds a partial repay at
/// its minimum, or at nothing while its price cannot be read; a lender takes no repay past its market's total
/// borrows, and one can take a whole repay a unit short): the exit takes of the venue's collateral the share
/// the repay frees, which its proportional release proves, at most what leaves a venue that still owes the
/// last units a release in whole units could take past its threshold (`FLAMMAdmitLib.heldRelease`). The rest
/// of the repay stays in custody, where it nets the debt the venue still holds, so the exit pays its debt
/// slice as any exit does and the gate reads the book an exit that repaid in full leaves. The collateral slice
/// the venue keeps posted is paid from the custody the pool owns, as a release a venue makes short is
/// ({_fromOwnCustody}): the exit refuses (`CustodyMismatch`) where custody cannot pay it past the dust, those
/// units, bounded at the larger of the pair's safety gap and 1 %, the lenders' rounding and a share under one
/// unit's assets and one, which the venue releases none of, all of which any exit can leave where custody runs
/// dry: it stays posted for the holders who remain, leaves the payout and is recorded for the fee mark
/// (`L.dust`). The venue's haircut (`L.loss`) cuts only the collateral the exit takes: the cut on that dust
/// comes back. Returns the release.
function _heldRepay(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, Legs memory L, uint256 i, uint256 paid)
private
view
returns (uint256 release)
{
IFLAMM.VenueLeg memory v = L.venue[i];
uint256 a = L.coll[i];
uint256 pay;
(release, pay, L.tokenOut[a]) = FLAMMAdmitLib.heldRelease(
$, v.id, v.collateral, paid, v.owed, b.legs[a].held - L.held[a], L.tokenOut[a], L.loss[i]
);
L.held[a] += pay;
uint256 left = v.collateral - release - pay;
if (left != 0) {
if (L.dust.length == 0) L.dust = new uint256[](L.tokenOut.length);
L.dust[a] += left;
}
}
/// @dev Records the collateral an exit left posted out of its slices (`dust`, per token: what its units left at a
/// venue and what a venue that held its repay kept), per share of the `left` that stay, 1e36, rounded up, as
/// `FLAMMMaintainLib.recordForfeit` records a frozen venue's slice: the next skim that reads the fee mark
/// raises it by that first, so no fee charges it.
function _recordDust(FLAMMStore.S storage $, uint256[] memory dust, uint256 left) private {
for (uint256 t; t < dust.length; ++t) {
if (dust[t] != 0) $.forfeited[t] += Math.mulDiv(dust[t], 1e36, left, Math.Rounding.Up);
}
$.poolBits |= FLAMMStore.POOL_FORFEIT;
}
// ------------------------------------------------------------------ performance fee
/// @dev Whether a fee rate is on where the fee charges: either rate, on a pool with a market band. A pro-rata
/// entry then needs a book its skim could price, and a share-sized one, which reads no price, a skim that read
/// the fee mark: a skim that reads none leaves the gain uncharged, and it would be charged later on the
/// entrant's shares too. A share price over the fee mark's `uint128` still prices the book, so a pro-rata
/// entry stays live there, as every other flow does. A pool with no band charges nothing, and the band
/// attached to it restarts the fee mark at the share price it finds, so it leaves no such gain.
function feeOn(FLAMMStore.S storage $) internal view returns (bool) {
return ($.performanceFeeBp | $.protocolFeeBp) != 0 && !FLAMMStore.bandOff($);
}
/// @dev Whether the fee mark reads at `assets` (`marked`: NAV checked, the price within `uint128`, which also
/// bounds `FLAMMMaintainLib.crystallize`'s narrowing write, as `peakAfter <= cur`, and a band in force), the
/// share price and the fee mark in the fee mark's measure (`FLAMMGateLib.tryMarkedTotalAssets`: NAV at 18
/// decimals of par whatever the pool asset, or, on a pool whose deposit basket is set, in the basket's units,
/// so the price is NAV per share against the basket's value), the fee mark raised by `forfeit` (what exits
/// forfeited at frozen venue marks since it last read, per share, which the price counts and no holder
/// earned); `cur` is zero where there is nothing to charge: NAV unchecked, the price over `uint128`, or the
/// price at or under the fee mark. `peak` is zero only where the fee mark does not read.
function mark(FLAMMStore.S storage $, bool ok, uint256 assets, uint256 supply, uint256 forfeit)
internal
view
returns (bool marked, uint256 cur, uint256 peak)
{
if (!ok) return (false, 0, 0);
cur = Math.mulDiv(assets, WAD, supply);
if (cur > type(uint128).max) return (false, 0, 0);
peak = $.peakSharePriceWad;
if (forfeit != 0) peak += forfeit;
if (cur <= peak) cur = 0;
marked = !FLAMMStore.bandOff($);
}
/// @dev Both parts of one gain from one base at the pre-mint supply, each rounded down: their order cannot
/// compound, their sum is never over the exact share of the gain at the two rates together, and the
/// rounding stays with the LPs.
function split(uint256 supply, uint256 cur, uint256 peak, uint256 bp, uint256 pbp)
internal
pure
returns (uint256 feeShares, uint256 protocolShares)
{
uint256 base = Math.mulDiv(supply, cur - peak, cur);
return (Math.mulDiv(base, bp, 1e4), Math.mulDiv(base, pbp, 1e4));
}
/// @dev A pool with no allowlist bound admits every depositor; a bound one decides.
function depositAllowed(FLAMMStore.S storage $, address who) internal view returns (bool) {
return $.allowlist == address(0) || IDepositAllowlist($.allowlist).isDepositAllowed(who);
}
}
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.