Verified contractPartialUNLICENSED
FLAMMLawLib
Address0xf55c5807b6fbe5555443fd6ddbbd52079849cf45
- 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
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,480,481
- Creation transaction
- 0x7dda584aa4…56ea62d8b8
- Libraries
- src/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0xf55c…49cf45src/core/flamm/FLAMMLawLib.sol:FLAMMSharedLib0xb852…b71005
52 files
The source code is large: one file is shown at a time. Choose a file in the list.
- src/core/flamm/FLAMMLawLib.solmain61.53 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.sol55.93 KB
- src/core/flamm/FLAMMAdmitLib.sol38.79 KB
- src/core/flamm/FLAMMBlindLib.sol60.72 KB
- src/core/flamm/FLAMMClaimLib.sol49.63 KB
- src/core/flamm/FLAMMClaimVault.sol1.65 KB
- src/core/flamm/FLAMMFenceLib.sol72.81 KB
- src/core/flamm/FLAMMFloatLib.sol62.2 KB
- src/core/flamm/FLAMMFlowLib.sol54.32 KB
- src/core/flamm/FLAMMGateLib.sol93.55 KB
- src/core/flamm/FLAMMKeptLib.sol45.86 KB
- src/core/flamm/FLAMMLane.sol70.59 KB
- src/core/flamm/FLAMMMaintainLib.sol42.7 KB
- src/core/flamm/FLAMMOpsLib.sol32.2 KB
- src/core/flamm/FLAMMPolicyLib.sol39.79 KB
- src/core/flamm/FLAMMQuoteLib.sol17 KB
- src/core/flamm/FLAMMRoute.sol16.45 KB
- src/core/flamm/FLAMMSettleLib.sol43.2 KB
- src/core/flamm/FLAMMSharedLib.sol13.11 KB
- src/core/flamm/FLAMMStore.sol137.17 KB
- src/core/flamm/FLAMMSwapLib.sol55.86 KB
- src/core/flamm/FLAMMTopUpLib.sol52.56 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.sol3.04 KB
- src/interfaces/core/mm/IFinancingAccount.sol47.32 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/FLAMMLawLib.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, CircularBook, CreditPathOff, PriceUnchecked, WAD} from "src/core/flamm/FLAMMStore.sol";
import {FLAMMGateLib} from "src/core/flamm/FLAMMGateLib.sol";
import {FLAMMSettleLib} from "src/core/flamm/FLAMMSettleLib.sol";
import {FLAMMSharedLib} from "src/core/flamm/FLAMMSharedLib.sol";
import {MMRouterLib} from "src/core/mm/MMRouterLib.sol";
import {IMMRouter} from "src/interfaces/core/mm/IMMRouter.sol";
import {IPriceFeed} from "src/interfaces/core/IPriceFeed.sol";
import {IRepayable} from "src/interfaces/core/mm/IHeldRepay.sol";
/// @notice The credit law over the book, for pairs between any two tokens: several collateral tokens per debt token
/// and several debt tokens per collateral token, under the Router's rule that no token is owed and backing at
/// once. A debt token owed at one pair is charged its net debt (owed less held and supplied) at that pair's
/// collateral, as its term `ceil(ceil(u * 1e54 / P) * WAD / ltv)`; one owed at two or more pairs (`MANY`)
/// with nothing held or supplied is charged each pair's whole debt at that pair's collateral (a forced load);
/// one owed at two or more pairs with a part of its debt covered (FLEX) charges each pair's gross debt when the
/// other debts' caps are sized, and holds where its pairs' excess over their caps fits what it holds and
/// supplies. A backing token holds where its loads fit what it holds and posts, `G * WAD`. Also: the room a
/// payout may draw at a pair, the per-pair entry and exit gates, the law at one backing token (a dial move, a
/// rotation), and the per-pair debt read of a pool where some token has two or more live pairs
/// (`FLAMMStore.POOL_MULTI`). The internal functions compile into each caller; the public entries serve the
/// swap's plan and the book's reads, and the flows' gates on this law are `FLAMMQuoteLib`'s.
library FLAMMLawLib {
/// @dev No token and no pair: as a token or pair argument it matches none; as the `only` mask, every token.
uint256 internal constant NONE = type(uint256).max;
/// @dev {lawBound}'s answer where the payout may neither draw nor pay custody of an owed output: past any backing
/// a token holds, so it caps no ceiling.
uint256 internal constant NO_CREDIT = type(uint256).max - 1;
// ------------------------------------------------------------------ terms
/// @notice The load of a debt `u` at price scale `p` and LTV `ltv`, collateral base units times WAD:
/// `ceil(ceil(u * 1e54 / p) * WAD / ltv)`.
function term(uint256 u, uint256 p, uint256 ltv) internal pure returns (uint256) {
return Math.mulDiv(Math.mulDiv(u, 1e54, p, Math.Rounding.Up), WAD, ltv, Math.Rounding.Up);
}
/// @notice The largest debt whose load is within `room`: `floor(floor(room * ltv / WAD) * p / 1e54)`, the exact
/// inverse of {term}.
function inv(uint256 room, uint256 p, uint256 ltv) internal pure returns (uint256) {
return Math.mulDiv(Math.mulDiv(room, ltv, WAD), p, 1e54);
}
// ------------------------------------------------------------------ the law
/// @notice The credit law at `b`'s prices, with pair `over` at the LTV `ltvOver` instead of its own (`NONE`: none,
/// every pair at its own): every backing token's loads within what it holds and posts, and every FLEX
/// token's excess over its pairs' caps within what it holds and supplies. With one pair it is
/// `U <= ltv * G` bit for bit, as `G * WAD` is an integer. Reverts `CircularBook` where an indebted pair's
/// collateral is owed, and `PriceUnchecked` where a charged debt's price is unchecked; a debt its own held
/// and supplied cover charges nothing and needs no price; a debt no live pair owes never holds.
function lawAt(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 over, uint256 ltvOver)
internal
view
returns (bool)
{
return _holds($, b, NONE, NONE, over, ltvOver);
}
/// @notice The law at backing token `a` alone, pair `over` at `ltvOver`: `a`'s loads within its backing, and each
/// FLEX pair at `a` within its cap less what its token holds and supplies. A dial move at a pair changes no
/// load but its collateral token's.
function loadHolds(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 a, uint256 over, uint256 ltvOver)
internal
view
returns (bool)
{
return !FLAMMGateLib.backsDebt(b, a) || _holds($, b, NONE, uint256(1) << a, over, ltvOver);
}
/// @notice What backing token `a` must hold and post for its loads ({_loads} at `a`), its FLEX pairs at their
/// gross: at least what the law needs there.
function backingNeed(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 a)
internal
view
returns (uint256)
{
return _need($, b, a, NONE);
}
/// @dev {backingNeed} with token `skip`'s debts left out (`NONE`: none).
function _need(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 a, uint256 skip)
private
view
returns (uint256)
{
(, uint256[] memory load, uint256[] memory gross,) = _loads($, b, skip, uint256(1) << a, NONE, 0);
uint256 l = (load.length != 0 ? load[a] : 0) + (gross.length != 0 ? gross[a] : 0);
return Math.ceilDiv(l, WAD);
}
/// @notice The law at every backing token but `a`: each one's loads within what it holds and posts, and each FLEX
/// pair there within its cap. A token whose debt no live pair owes is passed over.
function holdsBesides(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 a) internal view returns (bool) {
return _holds($, b, NONE, ~(uint256(1) << a), NONE, 0);
}
/// @dev The law at the backing tokens in `only` (a mask; `NONE`: every one), token `skip`'s debts left out (`NONE`:
/// none) and pair `over` at `ltvOver`: each one's loads within what it holds and posts ({_loads}, which loads
/// no token outside `only`), and each FLEX pair there within its cap. False where `only` is every token and a
/// debt no live pair owes is read; an empty load has no FLEX gross either, and holds.
function _holds(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
uint256 skip,
uint256 only,
uint256 over,
uint256 ltvOver
) private view returns (bool) {
(bool ok, uint256[] memory load, uint256[] memory gross, uint256[] memory g) =
_loads($, b, skip, only, over, ltvOver);
if (!ok) return false;
for (uint256 t; t < load.length; ++t) {
if (load[t] > FLAMMGateLib.backing(b.legs[t]) * WAD) return false;
}
return g.length == 0 || _flexHolds($, b, load, gross, g, over, ltvOver);
}
// ------------------------------------------------------------------ the law's bounds on a swap's payout
/// @notice A swap's plan on a book of three or more tokens, out of line (`FLAMMSwapLib.plan`), on the book with the
/// swap's pair priced: every other token that holds a leg priced, and `a`, whose price the room reads even
/// where it holds none (`usd`, the book's prices after; a price the book holds already stands, as on a
/// quote's re-ask on its first pass's book); the law's bound on its payout of `y` for `x` beside the room,
/// so the settlement's gate passes whatever the hook fills under it (none on a pool with no band, which
/// reads no price); the request's rest of the book ({restOf}); `drawable`, the draw rule's book term; and
/// the pair's pricer.
/// @dev - Where `y` backs a debt, the bound is the most the payout takes of it ({_backingCap}).
/// - Where the input is owed and `y` backs that debt alone, which the cover repays toward its backing, the law
/// where it holds now holds after any cover (a fill inside the band pays at most `1 + band` of its input's
/// worth, and the protocol's part leaves with it, so the debt's excess over its cap falls wherever
/// `ltv * (1 + band) * (1 + part) < 1` at the part's ceiling, `FLAMMStore.coverSafe`).
/// - Where it fails now, or that does not hold, the gate takes that ratio's not worsening in its place: there
/// the debt the cover repays toward is `coverDebt` ({_coverDebt}), whose ratio to `y`'s backing no fill may
/// raise (`FLAMMSwapLib.validate` holds the fill itself to it, so a hook that slices its input to the
/// ceiling is refused by the quote as by the swap), and the bound is the most that keeps it from rising at
/// the request (`amountIn` times that backing over the debt), read only where a fill inside the band could
/// raise it ({_mayRise}), a pair within the band of its debt's worth.
/// - Those two give way where the input, owed at two or more pairs, owes at a venue there that refuses repays,
/// whose repay then goes to its other pairs, or that may hold the repay short, which can leave that pair's
/// debt in place ({coverLeavesOwed}): the backing cap holds there. That cap bounds such a cover
/// as a cash payout: the plan reads the held repay as taking nothing, so a cover that a minimum position
/// would take all but the minimum of (one leaving between one unit and the minimum and the lenders' rounding
/// owed), or that a venue holding at nothing would leave in custody, is refused wherever its payout passes
/// the backing `y` leaves free, while a smaller cover and one past the debt fill. The hold is read at the
/// request (`amountIn`, before its notional cap) or the debt: a fill using less than the venue's debt there
/// can pass a held repay uncapped, which the settlement's gate still holds to the law, while the quote plans
/// at the input it uses, so a swap at its quoted input reads the hold as the quote does.
/// - Where `y` backs no debt, the bound turns on whether the payout may draw `y` against `a`, the backing of
/// its payout pair, or pay custody of `y` while `y` is owed: both raise `y`'s net debt, after which the gate
/// takes the whole law, which the room keeps at `a`; the swap moves no other backing token's loads or
/// backing but to repay, so that needs the law there now: `NO_CREDIT` where it fails at one. That holds too
/// where `y` backs the input's debt alone: a draw past the cover crosses, so the law there is read without
/// that debt, and the law then fails now, so the cover is held to the ratio too.
/// - The draw rule's book term (`FLAMMSwapLib._draw`) is one only a book of three or more tokens can fail:
/// `drawable` where the Router's drawn-set limit admits `y` for a swap of `amountIn`.
/// - Only a book of three or more tokens can name a pricer past the swap hook: the pair hook where it prices
/// the pair of `x` and `y` (`FLAMMStore.pairHookOf`), else the swap hook.
/// - A custody-blind pool's swap runs on its hook pair alone (tokens 0 and 1), and only while token 1 keeps no
/// buffer (no reserve target), else `CreditPathOff`: its plan and its preview refuse alike. Its law is the
/// posted-only one, which each slice keeps at its venue's pin; its draw posts nothing of the idle floor,
/// which the fill's grant (`FLAMMSettleLib._borrow`) and the preview's (`FLAMMPairQuoteLib._funded`) both
/// take off the pool asset's custody, so the Router's own funding check refuses a fill past it in both.
function lawBound(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
uint256 x,
uint256 y,
uint256 a,
uint256 amountIn
)
public
view
returns (
uint256 law,
uint256 restHeld,
uint256 restOwed,
uint256[] memory usd,
bool drawable,
address hook,
uint256 coverDebt
)
{
// a custody-blind pool's own swap runs on its hook pair alone, while token 1 keeps no buffer
if (
$.features & FLAMMStore.CUSTODY_BLIND != 0 && ((x | y) > 1 || $.tokens[1].reserveTarget != 0)
) revert CreditPathOff();
hook = $.invariantHook;
if ($.swapBits & FLAMMStore.SWAP_PAIR_HOOK != 0) {
address ph = FLAMMStore.pairHookOf($, x, y);
if (ph != address(0)) hook = ph;
}
usd = b.usd;
law = type(uint256).max;
if ($.noBand) {
(restHeld, restOwed) = restOf(b, x, y);
return (law, restHeld, restOwed, usd, true, hook, 0);
}
// every other token that holds a leg, from its own read that never reverts (the pool asset and the payout
// pair's backing token always), but one the book prices already (a quote's re-ask on its first pass's book)
IPriceFeed feed = $.priceFeed;
for (uint256 t; t < b.legs.length; ++t) {
if (t == x || t == y) continue;
FLAMMGateLib.Leg memory L = b.legs[t];
if ((t != 0 && t != a && (L.held | L.supplied | L.posted | L.owed) == 0) || usd[t] != 0) continue;
(bool ok, uint256 v,) = feed.peekUsd(FLAMMStore.tokenOf($, t));
if (ok) usd[t] = v;
}
FLAMMGateLib.frameAll(b);
(restHeld, restOwed) = restOf(b, x, y);
FLAMMGateLib.Leg memory Lx = b.legs[x];
if (FLAMMGateLib.backsDebt(b, y)) {
if (
Lx.owed == 0 || FLAMMGateLib.backsBesides($, b, y, x)
|| (
Lx.partner == FLAMMStore.MANY
&& coverLeavesOwed(
$, y, x, Lx.held + amountIn < Lx.owed ? amountIn : Lx.owed
)
)
) {
law = _backingCap($, b, x, y);
} else {
// `y` backs the input's debt alone, which the cover repays: a draw past it crosses, clearing that debt
// first, and the gate takes the whole law after it, so every other backing token must hold now
// without it, else the law fails now too
bool besides = a == FLAMMStore.NO_PARTNER || _holds($, b, x, ~(uint256(1) << a), NONE, 0);
if (!besides) law = NO_CREDIT;
// where the law fails now, or where its holding now need not hold after (the pair's LTV past what the
// band and the protocol's part keep, `FLAMMStore.coverSafe`), that debt's ratio to `y`'s backing, which
// the gate holds, cannot rise
uint256 d = _coverDebt($, b, x, y);
if (
d != 0 && _mayRise($, b, x, y, d)
&& (!besides || !_coverSafe($, b, x, y) || !lawAt($, b, NONE, 0))
) {
coverDebt = d;
if (besides) law = Math.mulDiv(amountIn, FLAMMGateLib.backing(b.legs[y]), d);
}
}
} else if (a != FLAMMStore.NO_PARTNER && !holdsBesides($, b, a)) {
law = NO_CREDIT;
}
if (a == FLAMMStore.NO_PARTNER) return (law, restHeld, restOwed, usd, false, hook, coverDebt);
bool clears = Lx.owed != 0 && (Lx.held >= Lx.owed || amountIn >= Lx.owed - Lx.held);
drawable = _drawnSetAdmits($, b, y, x, clears);
}
/// @dev The debt a cover of `x` for `y`, which backs `x`'s debt alone, repays toward: `x`'s net debt, or where `x`
/// owes at two or more pairs the cover pair's debt (`FLAMMGateLib.pairOf(y, x)`), which its repay reaches
/// first; the gate holds its ratio to `y`'s backing where the law fails.
function _coverDebt(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 x, uint256 y)
private
view
returns (uint256)
{
FLAMMGateLib.Leg memory Lx = b.legs[x];
return Lx.partner == FLAMMStore.MANY ? b.pairOwed[FLAMMGateLib.pairOf($, b, y, x)] : FLAMMGateLib.netDebt(Lx);
}
/// @dev Whether no cover of `x` for `y` inside their band raises the excess over its cap of the debt it repays
/// toward, at the cover pair's LTV (`FLAMMStore.coverSafe`): a pair none names reads that one may.
function _coverSafe(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 x, uint256 y)
private
view
returns (bool)
{
uint8 r = FLAMMGateLib.pairOf($, b, y, x);
return r != FLAMMStore.NO_PAIR && FLAMMStore.coverSafe($.pairs[r].ltvWad, FLAMMStore.pairBand($, x, y));
}
/// @dev Whether a fill inside the pair's band could raise debt `d`'s ratio to `y`'s backing: `d`'s worth in `y` at
/// the pair's price scale, rounded up, at the band's top and a tenth more (the protocol's part, at most 3 % of
/// the net, leaves with the payout), past that backing. Where it does not, no cover fill raises it and the
/// plan reads no law for it. An unchecked price reads that it could.
function _mayRise(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 x, uint256 y, uint256 d)
private
view
returns (bool)
{
uint256 p36 = x < y ? FLAMMGateLib.frameOf(b, x, y) : FLAMMGateLib.frameOf(b, y, x);
if (p36 == 0) return true;
uint256 v = x < y ? Math.mulDiv(d, p36, 1e36, Math.Rounding.Up) : Math.mulDiv(d, 1e36, p36, Math.Rounding.Up);
uint256 top = WAD + FLAMMStore.pairBand($, x, y) + 0.1e18;
return Math.mulDiv(v, top, WAD, Math.Rounding.Up) > FLAMMGateLib.backing(b.legs[y]);
}
/// @dev The Router's drawn-set rule, mirrored: a token not owed yet is drawn only while fewer tokens than
/// `maxDrawnTokens` (zero reads as one) are owed, the input counted as repaid where it clears its whole debt
/// (`cleared`), which `fund` then reads.
function _drawnSetAdmits(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 y, uint256 x, bool cleared)
private
view
returns (bool)
{
if (b.legs[y].owed != 0) return true;
uint256 owed;
for (uint256 t; t < b.legs.length; ++t) {
if (b.legs[t].owed != 0 && !(t == x && cleared)) ++owed;
}
if (owed == 0) return true;
uint256 limit = $.maxDrawnTokens;
return owed < (limit == 0 ? 1 : limit);
}
/// @notice The USD value (WAD) at the feed of every token's legs past `x` and `y`: held, supplied and posted
/// rounded down, owed rounded up. Reverts `PriceUnchecked` where such a token holds a leg at an unchecked
/// price.
function restOf(FLAMMGateLib.Book memory b, uint256 x, uint256 y)
internal
pure
returns (uint256 held, uint256 owed)
{
uint256 n = b.legs.length;
for (uint256 t; t < n; ++t) {
if (t == x || t == y) continue;
FLAMMGateLib.Leg memory L = b.legs[t];
uint256 pos = L.held + L.supplied + L.posted;
if ((pos | L.owed) == 0) continue;
uint256 u = b.usd[t];
if (u == 0) revert PriceUnchecked();
held += Math.mulDiv(pos * L.scale, u, WAD);
owed += Math.mulDiv(L.owed * L.scale, u, WAD, Math.Rounding.Up);
}
}
/// @dev The most a swap may pay of `y`, a token that backs a debt, out of what it holds and posts. The gate takes
/// the whole law after such a payout, as it worsens the ratio of a debt `y` backs and that the input does not
/// repay, so nothing unless the law holds now at every other backing token and at `y`; then the backing `y`
/// leaves free past its loads. A cover of a debt owed at one pair against `y` (the input owed there) adds that
/// debt's load as its input repays it, where the band and the protocol's part keep any fill's payout under the
/// load its input frees (`ltv * (1 + band) * (1 + part) < 1` at that pair, `FLAMMStore.coverSafe`). A cover of
/// a debt `y` backs keeps room for the lender's rounding of its repay: the load of `MMRouterLib.RELEASE_SLACK`
/// units of that debt, and a unit.
function _backingCap(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 x, uint256 y)
private
view
returns (uint256)
{
if (!holdsBesides($, b, y)) return 0;
uint256 g = FLAMMGateLib.backing(b.legs[y]);
uint256 need = backingNeed($, b, y);
if (need > g) return 0;
FLAMMGateLib.Leg memory Lx = b.legs[x];
uint8 r = Lx.owed != 0 ? FLAMMGateLib.pairOf($, b, y, x) : FLAMMStore.NO_PAIR;
uint256 slack;
if (r != FLAMMStore.NO_PAIR) {
FLAMMStore.PairCfg storage pc = $.pairs[r];
uint256 p = FLAMMGateLib.frameOf(b, y, x);
if (p == 0) revert PriceUnchecked();
slack = Math.ceilDiv(term(MMRouterLib.RELEASE_SLACK, p, pc.ltvWad), WAD) + 1;
// the band `FLAMMSwapLib.validate` holds the fill to (the tighter of the two tokens', the pool asset none)
// and the protocol's part at its ceiling, which leaves `y`'s backing with the payout
if (Lx.partner == y && FLAMMStore.coverSafe(pc.ltvWad, FLAMMStore.pairBand($, x, y))) need = _need($, b, y, x);
}
return need + slack > g ? 0 : g - need - slack;
}
/// @dev Each backing token's load (`load`: the terms of the debts owed at one pair, and every pair's whole debt of
/// a token owed at two or more with nothing held or supplied) and FLEX gross (`gross`: the gross terms of the
/// pairs of tokens owed at two or more with a part covered, each pair's in `g`), leaving out token `skip`'s
/// debts and every backing token outside `only` (a mask; `NONE`: all). `ok` false: a debt no live pair owes.
function _loads(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
uint256 skip,
uint256 only,
uint256 over,
uint256 ltvOver
) private view returns (bool ok, uint256[] memory load, uint256[] memory gross, uint256[] memory g) {
uint256 n = b.legs.length;
for (uint256 t; t < n; ++t) {
FLAMMGateLib.Leg memory L = b.legs[t];
if (L.owed == 0 || t == skip || L.partner == FLAMMStore.MANY) continue;
uint256 a = L.partner;
if (a == FLAMMStore.NO_PARTNER) {
if (only == NONE) return (false, load, gross, g);
continue;
}
if ((only >> a) & 1 == 0) continue;
if (b.legs[a].owed != 0) revert CircularBook();
uint256 u = FLAMMGateLib.netDebt(L);
if (u == 0) continue;
uint256 p = FLAMMGateLib.frameOf(b, a, t);
if (p == 0) revert PriceUnchecked();
if (load.length == 0) load = new uint256[](n);
load[a] += term(u, p, L.pair == over ? ltvOver : $.pairs[L.pair].ltvWad);
}
if (b.many != 0) {
uint256 m = b.pairOwed.length;
for (uint256 r; r < m; ++r) {
uint256 d = b.pairOwed[r];
if (d == 0) continue;
FLAMMStore.PairCfg storage pc = $.pairs[r];
(uint256 a, uint256 t) = (pc.coll, pc.debt);
if ((b.many >> t) & 1 == 0 || t == skip || (only >> a) & 1 == 0) continue;
if (b.legs[a].owed != 0) revert CircularBook();
FLAMMGateLib.Leg memory Lt = b.legs[t];
uint256 h = Lt.held + Lt.supplied;
if (Lt.owed <= h) continue;
uint256 p = FLAMMGateLib.frameOf(b, a, t);
if (p == 0) revert PriceUnchecked();
uint256 gr = term(d, p, r == over ? ltvOver : pc.ltvWad);
if (load.length == 0) load = new uint256[](n);
// nothing held or supplied nets the token's debt: every pair carries its whole debt
if (h == 0) {
load[a] += gr;
continue;
}
if (g.length == 0) (g, gross) = (new uint256[](m), new uint256[](n));
g[r] = gr;
gross[a] += gr;
}
}
ok = true;
}
/// @dev Whether every FLEX token's excess fits what it holds and supplies: pair `r` at backing `a` is within its
/// cap where `a`'s load and FLEX gross fit `a`; else its excess is its debt over `inv` of what `a` leaves past
/// the load and the other FLEX pairs' gross at `a`, the whole debt where that is not positive.
function _flexHolds(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
uint256[] memory load,
uint256[] memory gross,
uint256[] memory g,
uint256 over,
uint256 ltvOver
) private view returns (bool) {
uint256 n = b.legs.length;
uint256[] memory ex = new uint256[](n);
for (uint256 r; r < g.length; ++r) {
uint256 gr = g[r];
if (gr == 0) continue;
FLAMMStore.PairCfg storage pc = $.pairs[r];
(uint256 a, uint256 t) = (pc.coll, pc.debt);
uint256 c = FLAMMGateLib.backing(b.legs[a]) * WAD;
uint256 used = load[a] + gross[a];
if (used <= c) continue;
uint256 cap = c + gr > used
? inv(c + gr - used, FLAMMGateLib.frameOf(b, a, t), r == over ? ltvOver : pc.ltvWad)
: 0;
ex[t] += b.pairOwed[r] - cap;
}
for (uint256 t; t < n; ++t) {
if (ex[t] > b.legs[t].held + b.legs[t].supplied) return false;
}
return true;
}
/// @notice Whether a cover's repay of `x`, a grant of `left`, can leave debt owed at the pair that borrows `x`
/// against `y`: a venue there that owes and refuses repays now (`FLAMMGateLib.repayRefused`), which the
/// repay passes over, sending it, where `x` is owed at two or more pairs, to their venues; or, in the
/// settlement's order (`FLAMMSettleLib._repayInput`: venue by venue, each offered what is left), a venue
/// that may take less of its offer than it is offered, the rest staying in custody: one offered less than
/// it owes that may hold that repay short at a minimum position (`FLAMMGateLib.holdsRepay`: it takes all
/// but the minimum, or nothing while the minimum cannot be read), or a gated one whose lender takes less
/// than its offer now (`IRepayable`: a Venus sole borrower's remainder past its market's total borrows,
/// which the repays before it at venues borrowing from the same market lowered). Either leaves part of that
/// pair's debt in place, which `lawBound` then bounds as a cash payout: a known minimum under the debt
/// takes all but the minimum, yet the bound reads the repay as taking nothing, so a cover leaving less than
/// the minimum and the lenders' rounding owed is refused where its payout passes the free backing.
function coverLeavesOwed(FLAMMStore.S storage $, uint256 y, uint256 x, uint256 left) private view returns (bool) {
uint256 live = ~uint256($.retiredVenues);
uint256 gated = $.gatedVenues & live;
uint256 held = $.heldRepayVenues;
if ((gated | held) == 0) return false;
for (uint256 q; q < $.pairCount; ++q) {
FLAMMStore.PairCfg storage c = $.pairs[q];
if (c.coll != y || c.debt != x) continue;
uint256 mask = c.venues & live;
// what each venue before it takes of the repay reads into a hold, so the pair is walked whole
if (mask & (gated | held) == 0) continue;
// the markets the walk's bounded venues repay at, and what it took of each one's bound
(uint256[] memory mk, uint256[] memory took) = (new uint256[](32), new uint256[](32));
for (uint256 i; mask >> i != 0; ++i) {
if ((mask >> i) & 1 == 0) continue;
(,,,, uint256 d) = $.router.venuePosition(address(this), uint16(i));
if (d == 0) continue;
if (FLAMMGateLib.repayRefused($, i)) return true;
uint256 rp = left < d ? left : d;
if (rp != 0) {
if (rp < d && FLAMMGateLib.holdsRepay($, i, d - rp)) return true;
if (((gated & ~held) >> i) & 1 != 0 && _takesLess($, i, rp, mk, took)) return true;
}
left -= rp;
}
}
}
/// @dev Whether venue `id`'s lender takes less than `rp` of a repay now (`IRepayable.repayable`): its bound less
/// what the walk's repays before it took at the same market (`mk`, `took`, one slot per market), which this
/// one's adds to; false at a kind that does not answer it.
function _takesLess(FLAMMStore.S storage $, uint256 id, uint256 rp, uint256[] memory mk, uint256[] memory took)
private
view
returns (bool)
{
IMMRouter.VenueView memory v = $.router.venue(address(this), uint16(id));
(bool ok, bytes memory ret) = v.account.staticcall(abi.encodeCall(IRepayable.repayable, (v.id)));
if (!ok || ret.length < 64) return false;
// the market as a word: an answer whose address word has stray bits reads as a market of its own
(uint256 bound, uint256 market) = abi.decode(ret, (uint256, uint256));
uint256 j;
while (mk[j] != market && mk[j] != 0) ++j;
(mk[j], took[j]) = (market, took[j] + rp);
return bound < took[j];
}
// ------------------------------------------------------------------ the room's terms of a token owed at two pairs
// Out of line: `FLAMMGateLib.roomOf` reads them only where a token owes, or would owe once it draws, at two or more
// pairs.
/// @notice The sum over every pair at `x` of a token other than `y` that owes at two or more pairs and is net-owed
/// (a forced load or a FLEX pair) of the pair's gross debt at its own LTV, scaled to `ltv`
/// (`FLAMMGateLib.scaled`), each rounded up, in the room's head units (`FLAMMGateLib.roomOf`).
function flexAt(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 x, uint256 y, uint256 ltv)
public
view
returns (uint256 other)
{
for (uint256 r; r < b.pairOwed.length; ++r) {
uint256 d = b.pairOwed[r];
if (d == 0) continue;
FLAMMStore.PairCfg storage pc = $.pairs[r];
uint256 t = pc.debt;
if (pc.coll != x || t == y || (b.many >> t) & 1 == 0 || FLAMMGateLib.netDebt(b.legs[t]) == 0) continue;
other += FLAMMGateLib.scaled(b, x, t, d, pc.ltvWad, ltv);
}
}
/// @notice `y`'s excess over its pairs' caps were it FLEX: at each pair it owes at, its debt over the cap its
/// backing token leaves after every other debt charged as the law charges it ({_loads} without `y`); and
/// the cash that nets it, what `y` holds and what its lenders can return of its supply now
/// (`FLAMMGateLib.withdrawable`), as a draw's funding withdraws that first. Where the other debts' loads
/// alone pass a backing token's backing, the law fails there whatever `y` pays, and the gate then lets no
/// net debt rise: that pair's excess reads `type(uint128).max`, past any cash, so the room is at most the
/// cash `y` holds over all it owes.
function excessAfter(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 y)
public
view
returns (uint256 e, uint256 cash)
{
FLAMMGateLib.Leg memory Ly = b.legs[y];
cash = Ly.held + (Ly.supplied == 0 ? 0 : FLAMMGateLib.withdrawable($, y, Ly.supplied));
uint256 only = Ly.partner == FLAMMStore.MANY ? b.backs : uint256(1) << Ly.partner;
(, uint256[] memory load, uint256[] memory gross,) = _loads($, b, y, only, NONE, 0);
if (Ly.partner != FLAMMStore.MANY) return (_over($, b, Ly.pair, Ly.owed, load, gross), cash);
for (uint256 r; r < b.pairOwed.length; ++r) {
uint256 d = b.pairOwed[r];
if (d == 0 || $.pairs[r].debt != y) continue;
e += _over($, b, r, d, load, gross);
}
}
/// @notice The most of its custody a repay of token `y`, owed at two or more pairs, may spend at pair `p`. While
/// some pair of `y` is past its cap ({excessAfter}'s terms; one whose backing the other debts alone
/// overload, by its whole debt): `p`'s own excess, which the repay takes off one for one, less what the
/// cash the law nets `y`'s excess with (what it holds and supplies) falls short of all of it, so the
/// custody that nets another pair's excess stays, and so does what `y` holds past every pair's. With none
/// past: all of it for the keeper or the curator (`steward`), as it nets no excess then, and none for
/// anyone else, as it may be what a pair at its cap pays its sellers from. The law then holds after the
/// repay where it held, and no other pair's excess loses the cash that nets it. `b` priced.
function repayRoom(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 y, uint256 p, bool steward)
internal
view
returns (uint256 room)
{
(, uint256[] memory load, uint256[] memory gross,) = _loads($, b, y, b.backs, NONE, 0);
uint256 e;
for (uint256 r; r < b.pairOwed.length; ++r) {
uint256 d = b.pairOwed[r];
if (d == 0 || $.pairs[r].debt != y) continue;
uint256 x = Math.min(_over($, b, r, d, load, gross), d);
e += x;
if (r == p) room = x;
}
if (e == 0) return steward ? type(uint256).max : 0;
FLAMMGateLib.Leg memory L = b.legs[y];
uint256 h = L.held + L.supplied;
// short: the shortfall comes off `p`'s room, which leaves the cash that nets the other pairs' excess
if (e > h) room = room > e - h ? room - (e - h) : 0;
}
/// @dev Pair `r`'s debt `d` over the cap its backing token leaves past the loads {_loads} charged there;
/// `type(uint128).max` where those loads alone pass its backing.
function _over(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
uint256 r,
uint256 d,
uint256[] memory load,
uint256[] memory gross
) private view returns (uint256) {
FLAMMStore.PairCfg storage pc = $.pairs[r];
(uint256 a, uint256 t, uint256 ltv) = (pc.coll, pc.debt, pc.ltvWad);
uint256 p = FLAMMGateLib.frameOf(b, a, t);
if (p == 0) revert PriceUnchecked();
uint256 l = load.length != 0 ? load[a] : 0;
uint256 used = l + (gross.length != 0 ? gross[a] : 0);
uint256 c = FLAMMGateLib.backing(b.legs[a]) * WAD;
if (term(d, p, ltv) + used <= c) return 0;
return c > used ? d - inv(c - used, p, ltv) : l > c ? type(uint128).max : d;
}
// ------------------------------------------------------------------ anchors and the monotone law
/// @notice The gates' anchor: each token's net debt in L18 and backing, and where the book was read per pair, each
/// pair's debt (`d0`) and each token's debt (`o0`). A book that owes nothing anchors no debt: empty arrays.
function anchorOf(FLAMMGateLib.Book memory b)
internal
pure
returns (uint256[] memory u0, uint256[] memory g0, uint256[] memory d0, uint256[] memory o0)
{
if (!FLAMMGateLib.owes(b)) return (u0, g0, d0, o0);
uint256 n = b.legs.length;
(u0, g0) = (new uint256[](n), new uint256[](n));
for (uint256 t; t < n; ++t) {
FLAMMGateLib.Leg memory L = b.legs[t];
u0[t] = FLAMMGateLib.netDebt(L) * L.scale;
g0[t] = FLAMMGateLib.backing(L);
}
uint256 m = b.pairOwed.length;
if (m == 0) return (u0, g0, d0, o0);
(d0, o0) = (new uint256[](m), new uint256[](n));
for (uint256 t; t < n; ++t) {
FLAMMGateLib.Leg memory L = b.legs[t];
o0[t] = L.owed;
if (L.owed != 0 && L.partner != FLAMMStore.MANY && L.partner != FLAMMStore.NO_PARTNER) d0[L.pair] = L.owed;
}
for (uint256 r; r < m; ++r) {
if (b.pairOwed[r] != 0) d0[r] = b.pairOwed[r];
}
}
/// @notice The entry gate: the credit law, else no owed token's ratio to its backing worsened per pair against the
/// anchor ({requireNotWorsened}, at the caller's `dust` and refusal `err`: a flow's are `0` and
/// `LedgerBoundBreached`).
function entryGateAt(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
uint256[] memory u0,
uint256[] memory g0,
uint256[] memory d0,
uint256[] memory o0,
uint256 dust,
bytes4 err
) internal view {
if (!lawAt($, b, NONE, 0)) requireNotWorsened($, b, u0, g0, d0, o0, dust, err);
}
/// @notice The monotone law, price-free, per pair: reverts `err` where a token net-owed now was not at the anchor;
/// a token owed at one pair now, the pair all its anchor debt sat at, takes its net debt's ratio to that
/// pair's backing token's backing; any other net-owed token takes its net debt over its debt, and, per pair
/// it owes at now, that pair's debt over its backing token's backing (a pair owed now that owed nothing at
/// the anchor fails), each within the slack. A backing of zero at the anchor bounds no ratio. A token
/// net-owed at most `dust` native units counts as owing nothing. A ratio over the slack is read once more
/// with the backing token's posts at accruing kinds credited what their lenders' share rounding can read
/// back short ({FLAMMSharedLib.roundingAllowance}): a proportional leg there can leave a unit's assets less
/// than its exact share.
function requireNotWorsened(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
uint256[] memory u0,
uint256[] memory g0,
uint256[] memory d0,
uint256[] memory o0,
uint256 dust,
bytes4 err
) internal view {
bool perPair;
for (uint256 t; t < b.legs.length; ++t) {
FLAMMGateLib.Leg memory L = b.legs[t];
uint256 u1 = FLAMMGateLib.netDebt(L);
if (u1 <= dust) continue;
u1 *= L.scale;
uint256 a = L.partner;
bool ok = a != FLAMMStore.NO_PARTNER && u0.length != 0 && u0[t] != 0;
if (ok && a != FLAMMStore.MANY && (d0.length == 0 || d0[L.pair] == o0[t])) {
// one pair now, and all its debt there at the anchor: the token's own ratio
uint256 g = g0[a];
uint256 h = FLAMMGateLib.backing(b.legs[a]);
if (g == 0 || u1 * g <= _slack(u0[t] * h)) continue;
ok = u1 * g <= _slack(u0[t] * (h + FLAMMSharedLib.roundingOf($, a)));
} else if (ok) {
ok = u1 * o0[t] <= _slack(u0[t] * L.owed);
// owed at one pair now, at two or more at the anchor: that pair's debt, which the book reads per pair
// (the exit gate's net of a repay a venue took short, {gateExitAtRead})
if (ok && a != FLAMMStore.MANY) {
ok = _pairNotWorse($, b, a, L.pair, b.pairOwed[L.pair], L.scale, g0, d0);
}
if (a == FLAMMStore.MANY) perPair = true;
}
if (!ok) _fail(err);
}
if (!perPair) return;
for (uint256 r; r < b.pairOwed.length; ++r) {
uint256 d1 = b.pairOwed[r];
if (d1 == 0) continue;
FLAMMStore.PairCfg storage pc = $.pairs[r];
FLAMMGateLib.Leg memory L = b.legs[pc.debt];
if (L.partner != FLAMMStore.MANY || FLAMMGateLib.netDebt(L) <= dust) continue;
if (!_pairNotWorse($, b, pc.coll, r, d1, L.scale, g0, d0)) _fail(err);
}
}
/// @dev Reverts with the bare selector `err`, the error the caller named.
function _fail(bytes4 err) private pure {
assembly ("memory-safe") {
mstore(0, err)
revert(0, 4)
}
}
/// @dev Pair `r`'s debt `d1` over its backing token `a`'s backing, against the anchor's, once more with the
/// backing's read-back rounding where over the slack.
function _pairNotWorse(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
uint256 a,
uint256 r,
uint256 d1,
uint256 s,
uint256[] memory g0,
uint256[] memory d0
) private view returns (bool) {
if (d0[r] == 0) return false;
uint256 g = g0[a];
uint256 h = FLAMMGateLib.backing(b.legs[a]);
return g == 0 || d1 * s * g <= _slack(d0[r] * s * h)
|| d1 * s * g <= _slack(d0[r] * s * (h + FLAMMSharedLib.roundingOf($, a)));
}
/// @dev `v` raised by the monotone law's slack, `FLAMMStore.MONOTONE_SLACK_WAD`, rounded down.
function _slack(uint256 v) private pure returns (uint256) {
return Math.mulDiv(v, WAD + FLAMMStore.MONOTONE_SLACK_WAD, WAD);
}
// ------------------------------------------------------------------ the per-pair read
/// @notice The venue legs of the per-pair book (`FLAMMGateLib.bookOf` of a pool where some token has two or more
/// live pairs): the Router's book read once for every venue but those of the second and later live pairs of
/// each token with two or more, and once more per such rank, each pair's debt kept apart; a token two or
/// more of whose pairs owe is `MANY`, and the collateral tokens of its indebted pairs are its backs. Out of
/// line, as one array of words (`FLAMMGateLib` adopts it): per token its supplied, posted and owed legs,
/// its partner and its pair; then the empty venues, the `MANY` tokens and their backs, with the tokens of
/// two or more live pairs from `FLAMMGateLib.SPLIT_SHIFT`; then each pair's debt.
function splitRead() public view returns (uint256[] memory w) {
FLAMMStore.S storage $ = FLAMMStore.s();
FLAMMGateLib.Book memory b = FLAMMGateLib.custodyBook($);
if (!$.noLiveVenue) _read($, b, $.multiPairs);
(uint256 n, uint256 m) = (b.legs.length, b.pairOwed.length);
w = new uint256[](5 * n + 3 + m);
for (uint256 t; t < n; ++t) {
FLAMMGateLib.Leg memory L = b.legs[t];
(w[5 * t], w[5 * t + 1], w[5 * t + 2], w[5 * t + 3], w[5 * t + 4]) =
(L.supplied, L.posted, L.owed, L.partner, L.pair);
}
uint256 k = 5 * n;
(w[k], w[k + 1], w[k + 2]) = (b.empty, b.many, b.backs);
for (uint256 r; r < m; ++r) {
w[k + 3 + r] = b.pairOwed[r];
}
}
/// @dev The per-pair read into `b`, its custody and prices kept: the k-th live pair of each token with two or more
/// (`multiPairs`) is read by the k-th extra `book` call, skipping every other venue, so each such pair's debt
/// is its token's owed in that call.
function _read(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint32 multiPairs) private view {
uint256 idle = $.idleVenues;
uint256 m = $.pairCount;
uint256 n = b.legs.length;
uint256[] memory info = new uint256[](m);
uint64[16] memory extra;
uint256 count;
uint256 rounds;
uint256 skip = idle;
// the debt tokens of these pairs: the tokens with two or more live pairs
uint256 split;
for (uint256 r; r < m; ++r) {
if ((multiPairs >> r) & 1 == 0) continue;
FLAMMStore.PairCfg storage pc = $.pairs[r];
uint256 t = pc.debt;
split |= uint256(1) << t;
uint256 v = pc.venues & ~idle;
if (v == 0) continue;
uint256 k = (count >> (4 * t)) & 15;
count += 1 << (4 * t);
info[r] = ((k + 1) << 16) | (uint256(pc.coll) << 8) | t;
if (k == 0) continue;
skip |= v;
extra[k - 1] |= uint64(v);
if (k > rounds) rounds = k;
}
uint256[] memory owed = new uint256[]((rounds + 1) * n);
FLAMMGateLib.bookRead($, b, skip, false, owed, 0);
for (uint256 k; k < rounds; ++k) {
FLAMMGateLib.bookRead($, b, idle | (~uint256(extra[k]) & type(uint64).max), true, owed, (k + 1) * n);
}
b.pairOwed = new uint256[](m);
uint256 ind;
for (uint256 r; r < m; ++r) {
uint256 x = info[r];
if (x == 0) continue;
uint256 d = owed[((x >> 16) - 1) * n + (x & 0xff)];
b.pairOwed[r] = d;
if (d != 0) ind += 1 << (4 * (x & 0xff));
}
(b.many, b.backs) = (0, split << FLAMMGateLib.SPLIT_SHIFT);
for (uint256 r; r < m; ++r) {
uint256 x = info[r];
if (x == 0) continue;
(uint256 a, uint256 t) = ((x >> 8) & 0xff, x & 0xff);
FLAMMGateLib.Leg memory L = b.legs[t];
uint256 k = (ind >> (4 * t)) & 15;
if (k >= 2) {
L.partner = FLAMMStore.MANY;
b.many |= 1 << t;
if (b.pairOwed[r] != 0) b.backs |= 1 << a;
} else if (k == 0 || b.pairOwed[r] != 0) {
(L.partner, L.pair) = (uint8(a), uint8(r));
}
}
}
/// @notice The collateral pair `p`'s live venues post, as the Router recognizes it: what a cover that repays the
/// pair's debt can free there (`FLAMMSwapLib`, out of line).
function postedAt(FLAMMStore.S storage $, uint8 p) public view returns (uint256 posted) {
uint256 mask = $.pairs[p].venues & ~uint256($.retiredVenues);
IMMRouter r = $.router;
for (uint256 i; mask >> i != 0; ++i) {
if ((mask >> i) & 1 == 0) continue;
(, uint256 rec,,,) = r.venuePosition(address(this), uint16(i));
posted += rec;
}
}
// ------------------------------------------------------------------ the rotation's plan
/// @notice A swap's one rotation of `x` for `y`, `y` backing a debt (`FLAMMSwapLib.plan`, out of line: only a hook
/// that prices rotations reaches it): the first token `t` owed at (y -> t) that the input's pair (x -> t)
/// can draw (listed and borrowing; both `t` and `x` on peg, a draw's rule, else none there). The room at (x
/// -> t), the input credited at `phi`, at most what a fill inside the swap's band guarantees
/// (`FLAMMStore.pairBand`), and `t`'s own custody and supply left out, is the budget: the rotation keeps
/// those, while the law charges the new pair's gross debt against every other FLEX pair at `x`. What it
/// repays at (y -> t)'s venues releases `y` in proportion ({rotationCapacity}); a venue there
/// the settlement repays whole (one that may hold a partial repay) counts only where its debt fits the room
/// with the input (`amountIn`) credited its own worth at the pair's LTV alone, which is what it backs of
/// the draw. `rotIn` is `FLAMMStore.NO_PAIR` where none rotates; what the Router can fund of the draw is
/// the quote's to check (`FLAMMPairQuoteLib`), as a draw's is. The plan does not read the frame bound the
/// settlement applies to the release (`FLAMMSettleLib`, `FLAMMTopUpLib.frameBound`): where a frame posting
/// the output lacks, a rotation within the plan's ceiling can still be refused (`RoomExhausted`).
/// @dev The settlement rotates once the payout passes `y`'s custody less `keep`, which it keeps for the law at `y`:
/// the loads and the collateral at (y -> t) fall together as it rotates, so the law holds there through any
/// rotation where it holds both before it (the custody past `y`'s collateral the loads need) and once the
/// rotated debt is repaid whole (the custody past the other pairs' collateral the rest needs), as long as the
/// collateral falls no faster than the pair's own ratio of collateral to debt; what a venue holding more
/// collateral per unit of debt releases past that ratio is kept too ({_releaseLead}). A token is passed over
/// where its `keep` is more than `y` holds, and none rotates where that is so once the release's rounding and
/// lead are added, or where the law fails at another backing token: the gate takes the whole law after every
/// rotation. `verdicts`: what the ceiling found of `rotOut`'s venues ({rotationCapacity}), which
/// the swap hands its settlement (`FLAMMSettleLib.VERDICTS`).
function rotationPlan(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint8 x, uint8 y, uint256 amountIn)
public
view
returns (uint8 rotIn, uint8 rotOut, uint256 freed, uint256 keep, uint256 verdicts)
{
uint256[] memory w;
(rotIn, rotOut, freed, keep, w, verdicts) = _rotationPlan($, b, x, y, amountIn);
if (rotIn == FLAMMStore.NO_PAIR) return (rotIn, rotOut, 0, 0, 0);
// the proportional releases at `rotOut`'s venues read back up to a unit's assets and one low where the
// collateral accrues (`FLAMMSharedLib.roundingAllowance`), and run ahead of the pair's ratio at a venue holding
// more collateral per unit of debt than the pair ({_releaseLead}): both kept in custody for the law at `y`
// too, and none rotates where that is more than `y` holds
keep += FLAMMSharedLib.roundingAllowance($, $.pairs[rotOut].venues) + _releaseLead($, rotOut, freed, w);
if (keep > b.legs[y].held) return (FLAMMStore.NO_PAIR, rotOut, 0, 0, 0);
}
/// @dev The most a rotation releasing at most `freed` at `rotOut`'s venues releases ahead of the pair's ratio
/// `posted / owed` (its venues' recognized collateral over their debt), the line along which
/// {_rotationPlan}'s `keep` holds the law at `y`. The settlement repays the venues in their order and releases
/// each in proportion to its own recognized collateral `c` per unit of its debt `d`
/// (`FLAMMTopUpLib.rotate`), so a release `R` at a venue repays at least `R * d / c` and runs at most
/// `R * (1 - d * posted / (c * owed))` ahead of the line where `c / d` passes `posted / owed`, behind it
/// elsewhere. A venue releases at most `c` and `freed`: the sum of those leads, each rounded up, bounds the
/// lead at every point of every rotation the plan admits. A pair with one venue releases along its own ratio:
/// none. `w`: the venues' positions as the plan read them ({_positions}).
function _releaseLead(FLAMMStore.S storage $, uint8 rotOut, uint256 freed, uint256[] memory w)
private
view
returns (uint256 lead)
{
uint256 mask = $.pairs[rotOut].venues;
if (freed == 0 || mask & (mask - 1) == 0) return 0;
uint256 n = w.length / 2;
(uint256 posted, uint256 owed) = (0, 0);
for (uint256 i; i < n; ++i) {
(posted, owed) = (posted + w[2 * i], owed + w[2 * i + 1]);
}
for (uint256 i; i < n; ++i) {
(uint256 c, uint256 d) = (w[2 * i], w[2 * i + 1]);
if (d == 0 || c == 0) continue;
// `d * posted / c`, floored, so the lead rounds up
uint256 q = Math.mulDiv(d, posted, c);
if (q >= owed) continue;
lead += Math.mulDiv(c < freed ? c : freed, owed - q, owed, Math.Rounding.Up);
}
}
/// @dev Pair `p`'s venues read once for the rotation's plan: each one's recognized collateral and debt,
/// interleaved by venue id (`w[2 * i]`, `w[2 * i + 1]`; zero at an id that is not the pair's), which the
/// ceiling ({rotationCapacity}) and the lead ({_releaseLead}) size from, and that collateral
/// summed over its live venues, as {postedAt} sums it.
function _positions(FLAMMStore.S storage $, uint8 p) private view returns (uint256[] memory w, uint256 posted) {
uint256 mask = $.pairs[p].venues;
uint256 live = ~uint256($.retiredVenues);
uint256 n = FLAMMSettleLib.span(mask);
w = new uint256[](2 * n);
IMMRouter r = $.router;
for (uint256 i; i < n; ++i) {
if ((mask >> i) & 1 == 0) continue;
(, uint256 c,,, uint256 d) = r.venuePosition(address(this), uint16(i));
(w[2 * i], w[2 * i + 1]) = (c, d);
if ((live >> i) & 1 != 0) posted += c;
}
}
/// @dev {rotationPlan} before the release's rounding allowance and its lead past the pair's ratio, with the
/// positions of `rotOut`'s venues it read ({_positions}).
function _rotationPlan(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint8 x, uint8 y, uint256 amountIn)
private
view
returns (uint8 rotIn, uint8 rotOut, uint256 freed, uint256 keep, uint256[] memory w, uint256 verdicts)
{
rotIn = FLAMMStore.NO_PAIR;
if (!holdsBesides($, b, y)) return (rotIn, rotOut, 0, 0, w, 0);
FLAMMGateLib.Leg memory Ly = b.legs[y];
uint256 posted = Ly.posted;
uint256 need = backingNeed($, b, y);
uint256 n = b.legs.length;
for (uint256 t; t < n; ++t) {
if (b.legs[t].owed == 0 || t == x || t == y) continue;
uint8 o = FLAMMGateLib.pairOf($, b, y, t);
if (o == FLAMMStore.NO_PAIR) continue;
uint8 i = FLAMMGateLib.pairOf($, b, x, t);
if (i == FLAMMStore.NO_PAIR || $.pairs[i].borrowOff) continue;
if (
!FLAMMGateLib.onPeg($, FLAMMStore.tokenOf($, t), b.usd[t])
|| !FLAMMGateLib.onPeg($, FLAMMStore.tokenOf($, x), b.usd[x])
) continue;
// one read of the pair's venues serves the collateral they post, the ceiling and the lead
uint256 at;
(w, at) = _positions($, o);
uint256 rest = posted - Math.min(at, posted);
keep = need > posted ? need - posted : 0;
uint256 after_ = _need($, b, y, t);
if (after_ > rest && after_ - rest > keep) keep = after_ - rest;
if (keep > Ly.held) continue;
FLAMMGateLib.Leg memory Lt = b.legs[t];
(uint256 h, uint256 su) = (Lt.held, Lt.supplied);
(Lt.held, Lt.supplied) = (0, 0);
// the budget, the input credited at most what a fill inside the swap's band guarantees, as a draw's is;
// then the room with the input credited nothing, to which its own worth at the pair's LTV comes, which a
// whole repay must fit too (one read site for both)
uint256[2] memory room;
uint256 band = FLAMMStore.pairBand($, x, y);
for (uint256 k; k < 2; ++k) {
room[k] = FLAMMGateLib.roomOf($, b, i, band, 0, type(uint256).max);
band = FLAMMGateLib.UNCREDITED;
}
room[1] += Math.mulDiv(Math.mulDiv(amountIn, FLAMMGateLib.frameOf(b, x, t), 1e36), $.pairs[i].ltvWad, WAD);
(Lt.held, Lt.supplied) = (h, su);
(freed, verdicts) = rotationCapacity($, room[0], room[1], i, o, w);
return (i, o, freed, keep, w, verdicts);
}
keep = 0;
}
/// @notice A rotation's ceiling, for its plan ({rotationPlan}, which runs it inline): what `budget` of the owed
/// token, drawn at `rotIn` and shaved by its room's epsilon (the draw's venue reads a new borrow back high,
/// `FLAMMGateLib.READ_BACK_UNITS`, so a draw at the pin's edge reads over it), releases of the output from
/// `rotOut`'s venues as the settlement sizes it (`FLAMMSettleLib`).
/// @dev - Per venue that takes repays (`FLAMMGateLib.repayRefused`) and is healthy at its own oracle (the market
/// refuses a release past its threshold), of what it can release now (`FLAMMGateLib.releasableOf`), the
/// whole where the budget covers the whole debt, else in proportion to the repay less the margin.
/// - The venues sharing one reserve's cash stay within the cash they leave for releases
/// (`FLAMMSharedLib.releaseRoom`, one room per token), where each release redeems at least one unit of the
/// market: none there while the room left is under one unit's payout, and each takes at least that payout
/// of the room, whatever its face, so the releases the rotation makes, and only those, cost the room their
/// units.
/// - A venue whose kind may hold a partial repay short (`FLAMMStore.S.heldRepayVenues`: a minimum position)
/// counts only whole: where the budget left covers its debt and it can release all its collateral now,
/// outside a shared reserve; it is passed over otherwise, and the count stops at one whose debt the budget
/// left cannot cover, as the settlement repays such a venue whole or not at all.
/// - Its whole debt must fit `bare` too, shaved alike: the room at `rotIn` with the swap's input credited only
/// its own worth at the pair's LTV (`rotationPlan`), less the debts of the venues counted whole
/// before it. The budget credits the input as if it backed the whole draw, but a rotation's input only buys
/// its output, so a whole repay far past what the input backs would leave the law at `rotIn` failing after
/// the swap, which its quote does not read.
/// - `w`: each venue's recognized collateral and debt, interleaved by venue id, as the plan read them once for
/// its other figures too, in the same state.
/// - `verdicts`: what it found of each owing venue it reached, for the swap's settlement
/// (`FLAMMSettleLib.VERDICTS`): bit `i` where venue `i` takes repays and is healthy, bit `128 + i` where it
/// refuses a repay or is past its threshold; neither where it was not asked.
function rotationCapacity(
FLAMMStore.S storage $,
uint256 budget,
uint256 bare,
uint8 rotIn,
uint8 rotOut,
uint256[] memory w
) private view returns (uint256 out, uint256 verdicts) {
budget -= Math.mulDiv(budget, $.pairs[rotIn].roomEpsilonWad, WAD, Math.Rounding.Up);
bare -= Math.mulDiv(bare, $.pairs[rotIn].roomEpsilonWad, WAD, Math.Rounding.Up);
// nothing to size
if (budget == 0) return (0, 0);
uint256 mask = $.pairs[rotOut].venues;
IMMRouter r = $.router;
uint256 margin = FLAMMSettleLib.REPAY_MARGIN;
// unbounded with no unit where no live venue shares a reserve's cash, as `FLAMMSharedLib.releaseRoom` answers
// there, so it is asked only where one does
uint256 room = type(uint256).max;
uint256 unit;
if ($.sharedVenues & ~uint256($.retiredVenues) != 0) (room, unit) = FLAMMSharedLib.releaseRoom(rotOut);
for (uint256 i; mask >> i != 0 && budget != 0; ++i) {
if ((mask >> i) & 1 == 0) continue;
(uint256 rec, uint256 d) = (w[2 * i], w[2 * i + 1]);
if (d == 0 || rec == 0) continue;
if (FLAMMGateLib.repayRefused($, i) || !r.venueHealthy(address(this), uint16(i))) {
verdicts |= uint256(1) << (128 + i);
continue;
}
verdicts |= uint256(1) << i;
uint256 cap = FLAMMGateLib.releasableOf($, i, rec);
bool sh = ($.sharedVenues >> i) & 1 != 0;
if (($.heldRepayVenues >> i) & 1 != 0) {
if (cap < rec || sh) continue;
if (budget < d || bare < d) break;
}
// a release at a shared reserve redeems a whole unit at least: none under one unit's payout of room
if (sh) cap = room < unit ? 0 : cap > room ? room : cap;
if (budget >= d) {
(out, budget, bare) = (out + cap, budget - d, bare > d ? bare - d : 0);
} else {
if (budget <= margin) break;
uint256 take = Math.mulDiv(budget - margin, rec, d);
if (take < cap) cap = take;
(out, budget) = (out + cap, 0);
}
// and it takes at least that payout of the room
if (sh && cap != 0) room -= cap > unit ? cap : unit;
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {
"src/core/flamm/FLAMMLawLib.sol": {
"FLAMMLawLib": "0xf55c5807b6fbe5555443fd6ddbbd52079849cf45",
"FLAMMSharedLib": "0xb852d9cbdda85cbed7da0885bca2714ba1b71005"
}
},
"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.