Verified contractExactUNLICENSED
FLAMMKeptLib
Address0x7a11899232dd9f17c28bf062ec2ee2267158517b
- 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,542
- Creation transaction
- 0x3ccbb2e346…845d7f0b28
- 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/FLAMMKeptLib.solmain45.59 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/FLAMMFlowLib.sol55.24 KB
- src/core/flamm/FLAMMGateLib.sol87.39 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/FLAMMKeptLib.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, WAD, PriceUnchecked, CustodyMismatch, VenueRefusedLeg, NothingToClaim, FenceUnwound, LossMarkSet,
ParkedDrawn
} from "src/core/flamm/FLAMMStore.sol";
import {FLAMMGateLib} from "src/core/flamm/FLAMMGateLib.sol";
import {FLAMMFenceLib} from "src/core/flamm/FLAMMFenceLib.sol";
import {IFinancingAccount} from "src/interfaces/core/mm/IFinancingAccount.sol";
import {IMMRouter} from "src/interfaces/core/mm/IMMRouter.sol";
import {FLAMMClaimVault} from "src/core/flamm/FLAMMClaimVault.sol";
import {ReentrancyGuardLib} from "src/libraries/ReentrancyGuardLib.sol";
import {VenueReads} from "src/core/mm/VenueReads.sol";
/// @notice A kept share's clear ({clearKept}): every claim open at a venue fence's kept share, or a frame's, and the
/// pool's own part leave the venue in one call, each class of claims into the key's vault as a pot its holders
/// draw from ({drawKept}). `FLAMMClaimLib.unwindFence` is the clear's one caller: the pool's dispatch
/// table routes no entry here. Also what NAV, every flow and every claim count of a kept share ({keptLegs},
/// {markKept}, {juniorLegs}, {seniorWord}, {atFace}, {claimLoss}) and of a lender's reported loss: the loss
/// marks ({recordLossMarks}, {largerLoss}) and the floor a move of custody into a leg that bears one is held
/// to ({lossAtFloor}, {lossAtPair}, {lendReportsLoss}).
library FLAMMKeptLib {
/// @dev The pots a kept share's clear fills in its key's vault ({clearKept}), as `FLAMMStore.S.parked` holders: the
/// senior claims' and the junior claims'; no account can call from either.
address internal constant SENIOR_POT = address(1);
address internal constant JUNIOR_POT = address(2);
/// @dev One record's split at a clear ({clearKept}): the position's collateral, supply and debt, what leaves of
/// each, and the senior and junior claims' parts of what leaves; the record's tokens and key.
struct Split {
uint256 c;
uint256 s;
uint256 d;
uint256 cS;
uint256 sS;
uint256 dS;
uint256 cJ;
uint256 sJ;
uint256 cs;
uint256 j;
uint256 k;
uint8 coll;
uint8 debt;
}
/// @notice Clears the kept shares of records `m` (one venue's, or a frame's together; `FLAMMClaimLib.unwindFence`
/// calls it, for anyone, at the book's checked USD prices `usd`): every claim open there and the pool's
/// own part leave the venue in one call, whatever the number of holders.
/// @dev - Per record, of `whole`: the senior claims' part (`FLAMMStore.SENIORS`) at the ratios they settle at
/// ({claimLoss}); what the position is worth past their due at the ratios in force, shared pro rata by the
/// junior claims and the pool's part ({_keptLeg}'s rule); the whole debt repaid, the senior claims' their
/// share, the rest the pool's, as the junior claims' exits paid theirs (`FLAMMStore.JUNIOR_DEBT_SHIFT`).
/// The ratios' cut stays in the position, which the lift returns to the pool.
/// - The legs run in passes over the records as a frame's do (`FLAMMClaimLib._frameLegs`): every supply
/// withdrawn, every debt repaid from custody (`CustodyMismatch` where custody holds too little of a debt
/// token), every collateral released (`VenueRefusedLeg` where a venue takes a leg short).
/// - Each class of claims takes its share in kind into the key's vault (`FLAMMClaimVault`, which the caller
/// deploys where a claim is open), as two pots its holders draw from ({drawKept}): its collateral, and its
/// supply past its debt (the junior class owes none, so it is never under water); where its debt is the
/// larger, the pool pays the rest from custody and keeps collateral worth as much at `usd` in exchange,
/// rounded up (`PriceUnchecked` where a price that takes does not read; `VenueRefusedLeg` where the class's
/// collateral is worth less past the clear's rounding ({shortByRounding}): such a class is under water, and
/// the part waits for the write-off and the abandon; a class short by the rounding alone takes nothing). The
/// pool keeps the rest in custody.
/// - Each record closes its pool part and its claims: its kept and unwritten bits clear, and the entries,
/// rises and fee mints reopen where no other fence holds a part.
/// - The clear cuts at the lender's loss ratios as they read in the call, spot, not the marks. A clear by
/// anyone but the curator (`guarded`) lands at once where the lender reads no loss on the record, which cuts
/// no one (a kind's ratio rounds a deficit up, so no supply parked at the lender reads one as none). Else,
/// within `FLAMMStore.KEPT_CLEAR_WAIT` of the unwind that left the share, it lands only while each ratio,
/// the collateral's and the supply's, stands within `FLAMMStore.LOSS_MOVE_FLOOR` of its own read right
/// after that unwind ({markKept}), `NothingToClaim` otherwise: a ratio moved for the call,
/// by a supply or a withdrawal around it, the smaller one included, settles no class at a reading of the
/// caller's choosing. Past the wait it lands
/// whatever the lender reads, each ratio held within the floor of the unwind's, so a move made for the
/// call shifts at most the floor's share between the classes and the pool's part.
/// - A curator who wants the clear at the lender's ratio now, a loss grown or covered since the unwind,
/// clears first, unguarded, and sends it privately; the juniors share the loss with the pool's part, as
/// they share the position.
/// - Stated limit: past the wait a stranger's clear of a loss that has since moved by more than the floor
/// settles at the unwind's reading moved by the floor, not at the lender's.
/// - Stated limits, each deferring the clear and moving no value: a senior class whose debt share passes its
/// supply share needs the pair's checked price (`PriceUnchecked`; no junior path reads one, as the junior
/// class owes no debt, so no exit in the window brings the need back once the seniors have settled); the
/// venue's own refusal of a leg, as at full utilisation; and custody holding less than the record's whole
/// debt, the seniors' share included, which the pool fronts (`CustodyMismatch`): a buy into the pool, a
/// flash loan's included, refills it in the clear's transaction.
function clearKept(uint256 m, uint256[] memory usd, bool guarded) public {
FLAMMStore.S storage $ = FLAMMStore.s();
IMMRouter r = $.router;
Split[32] memory x;
for (uint256 k = m; k != 0; k &= k - 1) {
uint256 i = FLAMMFenceLib.low(k);
x[i] = _split($, r, i, guarded);
}
for (uint256 k = m; k != 0; k &= k - 1) {
uint256 i = FLAMMFenceLib.low(k);
uint256 sT = x[i].s;
if (sT == 0) continue;
uint256 got = r.withdrawSupplied(uint16(i), sT, address(this));
if (got < sT) revert VenueRefusedLeg();
x[i].s = got;
FLAMMStore.setHeld($, x[i].debt, FLAMMStore.heldOf($, x[i].debt) + got);
}
for (uint256 k = m; k != 0; k &= k - 1) {
uint256 i = FLAMMFenceLib.low(k);
uint256 d = x[i].d;
if (d == 0) continue;
uint256 t = x[i].debt;
if (FLAMMStore.ownHeld($, t) < d) revert CustodyMismatch();
address dt = FLAMMStore.tokenOf($, t);
FLAMMStore.grant($, dt, d);
uint256 paid = r.repay(uint16(i), d);
if (paid != d) {
(,,,, uint256 left) = r.venuePosition(address(this), uint16(i));
if (left != 0) revert VenueRefusedLeg();
FLAMMStore.revoke($, dt);
}
FLAMMStore.setHeld($, t, FLAMMStore.heldOf($, t) - paid);
}
uint256[] memory none = new uint256[]($.tokenCount);
for (uint256 k = m; k != 0; k &= k - 1) {
uint256 i = FLAMMFenceLib.low(k);
uint256 c = x[i].c;
if (c == 0) continue;
if (r.withdrawCollateral(uint16(i), c, none, true) != c) revert VenueRefusedLeg();
FLAMMStore.setHeld($, x[i].coll, FLAMMStore.heldOf($, x[i].coll) + c);
}
for (uint256 k = m; k != 0; k &= k - 1) {
uint256 i = FLAMMFenceLib.low(k);
Split memory y = x[i];
FLAMMStore.Fence storage f = $.fences[i];
uint32 key = f.key;
if (y.cs | y.j != 0) {
address vault = $.vaults[key];
_pot($, key, vault, SENIOR_POT, y.cS, y.sS, y.dS, y, usd);
_pot($, key, vault, JUNIOR_POT, y.cJ, y.sJ, 0, y, usd);
($.vaulted[key], $.vaulted[uint256(key) | 1 << 32]) = (y.cs, y.j);
$.vaulted[uint256(key) | 2 << 32] = uint256(y.coll) | uint256(y.debt) << 8;
}
(f.live, f.claimed, f.fee) = (0, 0, 0);
$.fenceWord &=
~(uint256(1) << (FLAMMStore.KEPT_SHIFT + i) | uint256(1) << (FLAMMStore.UNWRITTEN_SHIFT + i));
emit FenceUnwound(key, y.k, 0, y.c - y.cS - y.cJ, y.s - y.sS - y.sJ, y.d - y.dS);
}
}
/// @dev Record `i`'s split at a clear ({Split}, {clearKept}). Venue amounts as the Router reads them; the senior
/// shares rounded down past their ratio's cut rounded up, their debt share rounded up; the junior shares of
/// what stays past the seniors' due rounded down, and no debt: their exits paid it
/// (`FLAMMStore.JUNIOR_DEBT_SHIFT`), so the pool repays it; at most what the venue holds.
function _split(FLAMMStore.S storage $, IMMRouter r, uint256 i, bool guarded) private view returns (Split memory y) {
FLAMMStore.Fence storage f = $.fences[i];
(y.k, y.cs) = (f.live, f.fee & FLAMMStore.SENIORS);
y.j = f.claimed - y.cs;
uint256 whole = y.k + f.claimed;
IMMRouter.VenueView memory v = r.venue(address(this), uint16(i));
(y.coll, y.debt) = (v.coll, v.debt);
(, uint256 c,, uint256 s, uint256 d) = r.venuePosition(address(this), uint16(i));
// the lender's ratios as they stand, not the marks, which a reading raised for one call holds up
(uint256 cl, uint256 sl) = IFinancingAccount(v.account).haircut(v.id);
// a stranger's clear: at spot where the lender reads no loss; else, within the wait, only while each ratio
// stands near the unwind's; past it, at spot, each ratio held within the floor of the unwind's
if (guarded && cl | sl != 0) {
uint256 w0 = $.vaulted[uint256(f.key) | FLAMMStore.KEPT_READ];
(uint256 nc, uint256 ns) = (_near(cl, uint64(w0)), _near(sl, uint64(w0 >> 64)));
if (block.timestamp >= (w0 >> 128) + FLAMMStore.KEPT_CLEAR_WAIT) (cl, sl) = (nc, ns);
else if (nc != cl || ns != sl) revert NothingToClaim();
}
(uint256 xc, uint256 xs) = (cl, sl);
if (y.cs != 0) {
uint256 sw = f.fee;
(xc, xs) =
(senior(cl, _r0(sw >> 120), whole, y.cs), senior(sl, _r0(sw >> 168), whole, y.cs));
}
y.d = d;
y.dS = _min(Math.mulDiv(d, y.cs, whole, Math.Rounding.Up), d);
(y.c, y.cS, y.cJ) = _class(c, cl, xc, y.cs, y.j, whole);
(y.s, y.sS, y.sJ) = _class(s, sl, xs, y.cs, y.j, whole);
}
/// @dev One leg `a` of a position of `whole` at a clear: what leaves (`out`: the seniors' share at their ratio
/// `x` and what stays worth past it at the ratio in force `r`), the seniors' (`cs` of `whole`) and the
/// juniors' (`j` of what is not senior).
function _class(uint256 a, uint256 r, uint256 x, uint256 cs, uint256 j, uint256 whole)
private
pure
returns (uint256 out, uint256 sen, uint256 jun)
{
sen = Math.mulDiv(a, cs, whole);
sen -= Math.mulDiv(sen, x, WAD, Math.Rounding.Up);
uint256 worth = a - Math.mulDiv(a, r, WAD, Math.Rounding.Up);
uint256 rest = worth > sen ? worth - sen : 0;
if (whole > cs) jun = Math.mulDiv(rest, j, whole - cs);
out = sen + rest;
}
/// @dev Ratio `x` held within `FLAMMStore.LOSS_MOVE_FLOOR` of `x0`.
function _near(uint256 x, uint256 x0) private pure returns (uint256) {
if (x > x0 + FLAMMStore.LOSS_MOVE_FLOOR) return x0 + FLAMMStore.LOSS_MOVE_FLOOR;
if (x + FLAMMStore.LOSS_MOVE_FLOOR < x0) return x0 - FLAMMStore.LOSS_MOVE_FLOOR;
return x;
}
/// @dev The lower of `a` and `b`.
function _min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
/// @dev One class's pot at a clear ({clearKept}): its collateral `c`, and its supply `s` past its debt `d`, out of
/// custody into `vault`, recorded for `pot`; where `d` is the larger the pool keeps collateral worth the rest
/// at `usd`, rounded up.
function _pot(
FLAMMStore.S storage $,
uint32 key,
address vault,
address pot,
uint256 c,
uint256 s,
uint256 d,
Split memory y,
uint256[] memory usd
) private {
if (s >= d) {
s -= d;
} else {
uint256 f =
FLAMMGateLib.frame(usd[y.debt], usd[y.coll], _tokenScale($, y.debt), _tokenScale($, y.coll));
if (f == 0) revert PriceUnchecked();
uint256 need = Math.mulDiv(d - s, f, 1e36, Math.Rounding.Up);
if (need > c) {
if (!shortByRounding(need - c, f)) revert VenueRefusedLeg();
need = c;
}
(c, s) = (c - need, 0);
}
_out($, key, vault, pot, y.coll, c);
_out($, key, vault, pot, y.debt, s);
}
/// @notice Whether a claim class whose debt past its supply needs `short` more of its collateral than its pot holds
/// ({_pot}, at `f` collateral units per debt unit, scaled 1e36) is short by the clear's rounding alone, not
/// under water: at most what {_split} and {_class} can round against it, 3 units of each of its collateral
/// and supply shares rounded down, 1 unit of its debt share rounded up, and 1 unit of `need` rounded up, so
/// `4 + ceil(4 * f / 1e36)` collateral units. Such a class (a dust claim's) takes nothing, and the pool
/// pays its debt share and keeps its collateral: the pool bears at most that bound per class per clear.
function shortByRounding(uint256 short, uint256 f) internal pure returns (bool) {
return short <= 4 + Math.mulDiv(4, f, 1e36, Math.Rounding.Up);
}
/// @dev Moves `amount` of token `t` out of custody into `vault`, recorded for `pot` of fence `key`.
function _out(FLAMMStore.S storage $, uint32 key, address vault, address pot, uint256 t, uint256 amount) private {
if (amount == 0) return;
address token = FLAMMStore.tokenOf($, t);
FLAMMStore.setHeld($, t, FLAMMStore.heldOf($, t) - amount);
$.parked[key][pot][token] += amount;
FLAMMStore.safeTransfer(token, vault, amount);
}
/// @dev Token `t`'s scale: the pool asset's from the first word.
function _tokenScale(FLAMMStore.S storage $, uint256 t) private view returns (uint256) {
return t == 0 ? $.shareScale : $.tokens[t].scale;
}
// ------------------------------------------------------------------ a lender's reported loss
/// @dev One ratio of a loss mark (`FLAMMStore.S.lossMarks`): 48 bits.
uint256 private constant MARK_FIELD = (1 << 48) - 1;
/// @dev The gas {_worth}'s read of a fenced token's balance gets.
uint256 private constant BALANCE_READ_GAS = 100_000;
/// @notice Records, for each venue slot that keeps a loss mark (`FLAMMStore.S.lossMarks`), the two ratios its
/// lender reports now (`IFinancingAccount.haircut`), each a spot figure that a supply to the lender's
/// reserve lowers, and a withdrawal from it raises, within one call. Every skim runs it first
/// (`FLAMMMaintainLib.crystallize`), so anyone may, at any time (`FLAMM.skimPerformanceFee`), and so does
/// each entry that judges a move or a claim by these ratios. Per ratio:
/// - one over the mark raises the mark at once: a rise is the careful way for every cut;
/// - zero clears the mark at once: only a lender with no deficit reports zero, which no supply reaches;
/// - the largest ratio read since the window opened is kept beside the mark, and where this call finds the
/// window closed (`FLAMMStore.LOSS_WINDOW` after it opened) a new window opens with this call's ratio;
/// - the mark falls only there, to that largest ratio, this call's among them, and only where the closed
/// window held two witnessed readings at least; with fewer it stands.
/// A witnessed reading is one a plain key's own transaction takes (`FLAMMStore.lossWitness`: the caller
/// is the transaction's sender and holds no code), a call nothing runs before or after in its transaction:
/// a reading inside a contract's call, in an operator's signed transaction that any address may execute or
/// from a key delegated to code may be taken under a ratio lowered for that call, at each end of a quiet
/// window too, so those readings alone lower no mark. Whose key it is does not matter: a holder's own
/// deposit, exit or skim counts as the keeper's `recenter` does, which reads here whenever a witnessed
/// reading is due. One counts once every `FLAMMStore.LOSS_WITNESS_GAP` at most (the time of the last is
/// kept for the pool, at `FLAMMStore.LOSS_WITNESS_KEY`), so a window holds six at most and one block's
/// count once; a reading inside that time still raises a mark and the window's largest ratio, as any
/// does. To lower a mark under the lender's ratio as it stands, supply must be held at the lender across
/// separate transactions, at every reading of a whole window.
/// @dev A venue whose ratios both read zero and that holds no mark is not written: one that never reports a loss
/// costs its reads alone. Asked: every such slot the book may read or wake, and a fenced one, whose claims cut
/// their shares by the same ratios (`FLAMMClaimLib.shares`); a slot retired outside a fence is not, as its
/// lender may have stopped answering and nothing reads its ratios. A venue whose haircut is a redemption fee
/// keeps no mark: its fee is what the lender takes, read as it stands; a pool whose loss venues are all such
/// keeps no reading's time either.
function recordLossMarks() public {
FLAMMStore.S storage $ = FLAMMStore.s();
if (_marked($) == 0) return;
bool witness = FLAMMStore.lossWitness($);
if (witness) $.lossMarks[FLAMMStore.LOSS_WITNESS_KEY] = block.timestamp;
uint256 set = _marked($) & (~uint256($.retiredVenues) | $.fenceWord);
IMMRouter r = $.router;
for (uint256 i; set >> i != 0; ++i) {
if ((set >> i) & 1 == 0) continue;
IMMRouter.VenueView memory v = r.venue(address(this), uint16(i));
(uint256 cl, uint256 sl) = IFinancingAccount(v.account).haircut(v.id);
uint256 w = $.lossMarks[i];
uint256 next;
if ((cl | sl) != 0) {
// the open window's start and its witnessed readings, counted to three
(uint256 opened, uint256 seen) = (uint32(w >> 192), (w >> 224) & 3);
bool closed = block.timestamp >= opened + FLAMMStore.LOSS_WINDOW;
bool fall = closed && seen >= 2;
if (closed) (opened, seen) = (uint32(block.timestamp), 0);
if (witness && seen != 3) ++seen;
next = _marks(w, cl, closed, fall) | _marks(w >> 96, sl, closed, fall) << 96 | opened << 192
| seen << 224;
}
if (next != w) {
$.lossMarks[i] = next;
// logged where a mark in force changed, not for the window's fields
if ((next ^ w) & (MARK_FIELD | MARK_FIELD << 96) != 0) {
uint256 u = FLAMMStore.LOSS_MARK_UNIT;
emit LossMarkSet(uint16(i), (next & MARK_FIELD) * u, ((next >> 96) & MARK_FIELD) * u);
}
}
}
}
/// @dev One ratio's two fields after a reading of `spot` (WAD): `half`'s low 96 bits are the mark in force and the
/// largest ratio read in the open window ({recordLossMarks}), in `FLAMMStore.LOSS_MARK_UNIT`s; `spot` is
/// rounded up to that unit, so a mark never reads under the ratio it recorded. `closed`: the window closed, so
/// the next opens with `spot`; `fall`: it held the witnessed readings a fall takes.
function _marks(uint256 half, uint256 spot, bool closed, bool fall) private pure returns (uint256) {
if (spot == 0) return 0;
spot = _units(spot);
(uint256 mark, uint256 top) = (half & MARK_FIELD, (half >> 48) & MARK_FIELD);
if (spot > mark) mark = spot;
if (spot > top) top = spot;
if (closed) {
if (fall) mark = top;
top = spot;
}
return mark | top << 48;
}
/// @dev A ratio (WAD, at most WAD) in a mark's units, rounded up: at most 1e14, under 2^48.
function _units(uint256 spot) private pure returns (uint256) {
if (spot > WAD) spot = WAD;
unchecked {
return (spot + FLAMMStore.LOSS_MARK_UNIT - 1) / FLAMMStore.LOSS_MARK_UNIT;
}
}
/// @dev The venue slots that keep a loss mark: those whose kind reports a loss that is no redemption fee.
function _marked(FLAMMStore.S storage $) private view returns (uint256) {
return $.lossVenues & ~uint256($.feeVenues);
}
/// @notice The loss ratios of venue slot `i` (`id` at `account`), WAD, collateral then supply: per ratio the
/// larger of what the lender reports now and the slot's mark in force ({recordLossMarks}), read as stored, so a
/// view between two skims never reads under the lender's own figure and a ratio lowered within the call
/// lowers nothing. A venue whose haircut is a redemption fee reads the lender's figure alone.
function largerLoss(uint256 i, address account, bytes32 id) public view returns (uint256 cl, uint256 sl) {
(cl, sl) = IFinancingAccount(account).haircut(id);
(cl, sl) = _withMarks(i, cl, sl);
}
/// @dev Slot `i`'s ratios `cl` and `sl` raised to its marks ({largerLoss}); as they are at a slot whose haircut is
/// a redemption fee.
function _withMarks(uint256 i, uint256 cl, uint256 sl) private view returns (uint256, uint256) {
FLAMMStore.S storage $ = FLAMMStore.s();
if (($.feeVenues >> i) & 1 != 0) return (cl, sl);
uint256 w = $.lossMarks[i];
uint256 mark = (w & MARK_FIELD) * FLAMMStore.LOSS_MARK_UNIT;
if (mark > cl) cl = mark;
mark = ((w >> 96) & MARK_FIELD) * FLAMMStore.LOSS_MARK_UNIT;
if (mark > sl) sl = mark;
return (cl, sl);
}
/// @notice Whether a venue slot of `venues` (bit `i` for slot `i`) that keeps a loss mark reads a loss ratio of
/// `FLAMMStore.LOSS_MOVE_FLOOR` or more ({largerLoss}: the larger of the lender's ratio now and the slot's
/// mark) on `leg`: its collateral (`FLAMMStore.LOSS_LEG_COLLATERAL`); its supply, where its supply switch
/// is on (`LOSS_LEG_SUPPLY`); its collateral, where its borrow switch is on (`LOSS_LEG_BORROW`); or either
/// ratio, whatever its switches (`LOSS_LEG_ANY`).
/// @dev NAV counts custody at par and cuts what a venue holds by these ratios, so a move of custody into such a
/// leg lowers NAV by that share of it in the call, and the move back restores it: the pool makes none a
/// caller sizes (`FLAMMMaintainLib.maintain` and `emergency`, a swap's lend, draw and rotation, a flush's lend
/// and a refill's post). A supply to the lender's reserve lowers the lender's ratio for the call and not the
/// mark, so no call opens the way in where a reading has seen the loss; and a ratio raised for a call, by a
/// withdrawal of supply parked at the lender, reads here as it stands, so no stranger settles another's fence
/// claim at it (`FLAMMClaimLib.settleClaim`). A venue whose haircut is a redemption fee is read only where
/// `leg` carries `FLAMMStore.LOSS_LEG_FEES`, and a fee of any size counts there: the lender takes it on every
/// way out and no move back returns it, so no floor bounds what a round trip pays.
function lossAtFloor(uint256 venues, uint256 leg) public view returns (bool) {
FLAMMStore.S storage $ = FLAMMStore.s();
uint256 fees;
if (leg & FLAMMStore.LOSS_LEG_FEES != 0) (fees, leg) = ($.feeVenues, leg ^ FLAMMStore.LOSS_LEG_FEES);
venues &= _marked($) | fees;
IMMRouter r = $.router;
for (uint256 i; venues >> i != 0; ++i) {
if ((venues >> i) & 1 == 0) continue;
IMMRouter.VenueView memory v = r.venue(address(this), uint16(i));
if (leg == FLAMMStore.LOSS_LEG_SUPPLY && !v.supplyEnabled) continue;
if (leg == FLAMMStore.LOSS_LEG_BORROW && !v.borrowEnabled) continue;
(uint256 cl, uint256 sl) = largerLoss(i, v.account, v.id);
if (leg == FLAMMStore.LOSS_LEG_SUPPLY) cl = 0;
else if (leg != FLAMMStore.LOSS_LEG_ANY) sl = 0;
uint256 floor = (fees >> i) & 1 != 0 ? 1 : FLAMMStore.LOSS_MOVE_FLOOR;
if (cl >= floor || sl >= floor) return true;
}
return false;
}
/// @notice Whether a live venue of pair `p`, or a live venue that shares a frame's account with one
/// (`FLAMMFenceLib.matesOf`), reads a loss on its collateral of `FLAMMStore.LOSS_MOVE_FLOOR` or more, or
/// takes a redemption fee of any size on it (`FLAMMStore.LOSS_LEG_FEES`, {lossAtFloor}). The collateral
/// maintainer posts custody at such a venue back to its pair's pin, and covers a frame's venue that takes
/// no post through a mate, in the mate's token (`FLAMMTopUpLib._throughMate`): so a pin lowered at the
/// pair would size a post into the leg that bears the loss, or pays the fee on its way out
/// (`FLAMMPolicyLib.setDials`).
function lossAtPair(uint256 p) public view returns (bool) {
FLAMMStore.S storage $ = FLAMMStore.s();
uint256 venues = $.pairs[p].venues;
uint256 m = venues;
for (uint256 i; venues >> i != 0; ++i) {
if ((venues >> i) & 1 != 0) m |= FLAMMFenceLib.matesOf($, uint16(i));
}
return lossAtFloor(m & ~uint256($.retiredVenues), FLAMMStore.LOSS_LEG_COLLATERAL | FLAMMStore.LOSS_LEG_FEES);
}
/// @notice Whether a live venue that lends token `t` (a venue of a live pair owing it, its supply on) reports a
/// loss on its supply ({lossAtFloor}), or takes a redemption fee of any size on it
/// (`FLAMMStore.LOSS_LEG_FEES`): while one does, the pool lends none of its custody of `t` by the swap's
/// surplus rule (`FLAMMSettleLib`, its step 4) or a flush's (`FLAMMFloatLib.flush`), and the surplus stays
/// in custody; neither call reverts for it. A lend into a fee venue and the withdrawal a later swap makes
/// pay the fee each time round, in calls anyone makes. The operator frees the token's other lenders by
/// turning that venue's supply off.
function lendReportsLoss(uint256 t) public view returns (bool) {
FLAMMStore.S storage $ = FLAMMStore.s();
(uint256 pairs,) = FLAMMStore.lanes($, t);
uint256 venues;
for (uint256 p; pairs >> p != 0; ++p) {
if ((pairs >> p) & 1 != 0) venues |= $.pairs[p].venues;
}
return lossAtFloor(venues, FLAMMStore.LOSS_LEG_SUPPLY | FLAMMStore.LOSS_LEG_FEES);
}
// ------------------------------------------------------------------ a kept share
/// @notice Venue slot `i`'s loss ratios as a claim on its record settles ({largerLoss}, `FLAMMClaimLib.shares`):
/// while the record holds senior claims (`FLAMMStore.SENIORS`), on each leg the lower of the ratio in force
/// and the one read at the unwind that left the kept share, but at least what leaves the claims no more
/// than the whole position `whole` (of `FLAMMFenceLib.ONE`) is worth at the ratio in force ({senior}).
function claimLoss(uint256 i, address account, bytes32 id, uint256 whole)
public
view
returns (uint256 cl, uint256 sl)
{
(cl, sl) = largerLoss(i, account, id);
uint256 sw = FLAMMStore.s().fences[i].fee;
uint256 cs = sw & FLAMMStore.SENIORS;
if (cs == 0) return (cl, sl);
uint256 u = FLAMMStore.LOSS_MARK_UNIT;
(cl, sl) = (senior(cl, uint48(sw >> 120) * u, whole, cs), senior(sl, uint48(sw >> 168) * u, whole, cs));
}
/// @notice A junior part's collateral and supply shares (`FLAMMClaimLib.shares`), its record's kept share given up:
/// of `part` of venue slot `i`'s position of `whole`, posting `c` and supplying `s`, what stays past the
/// senior claims' due at their ratios ({claimLoss}), at the ratios in force ({largerLoss}), its share
/// `part / (whole - seniors)`, rounded down ({_keptLeg}), as the clear shares it, so no junior part takes
/// the seniors' cover.
function juniorLegs(uint256 i, address account, bytes32 id, uint256 c, uint256 s, uint256 whole, uint256 part)
public
view
returns (uint256, uint256)
{
(uint256 cl, uint256 sl) = largerLoss(i, account, id);
uint256 sw = FLAMMStore.s().fences[i].fee;
uint256 cs = sw & FLAMMStore.SENIORS;
return (_keptLeg(c, cl, cs, _r0(sw >> 120), whole, part), _keptLeg(s, sl, cs, _r0(sw >> 168), whole, part));
}
/// @notice What the pool's unwind of `part` takes at face at the records `m` while a claim is open
/// (`FLAMMClaimLib.unwindFence`): `part` less its share at the largest loss ratio, collateral or supply,
/// that a venue of theirs keeping a loss mark reads ({largerLoss}, at most all of it), rounded up, so the
/// claims' fractions of what stays never grow; `part` where none reads one, or where none keeps a mark.
function atFace(uint256 m, uint256 part) public view returns (uint256) {
FLAMMStore.S storage $ = FLAMMStore.s();
IMMRouter r = $.router;
uint256 l;
for (m &= _marked($); m != 0; m &= m - 1) {
uint256 j = FLAMMFenceLib.low(m);
IMMRouter.VenueView memory v = r.venue(address(this), uint16(j));
(uint256 cl, uint256 sl) = largerLoss(j, v.account, v.id);
if (sl > cl) cl = sl;
if (cl > l) l = cl;
}
if (l > WAD) l = WAD;
return part - Math.mulDiv(part, l, WAD, Math.Rounding.Up);
}
/// @notice The senior word of venue `j`'s record (`FLAMMStore.SENIORS`) as the pool's whole part leaves it with
/// `claimed` open: their part and the loss ratios read now, before any leg, rounded down to mark units.
function seniorWord(uint256 j, uint256 claimed) public view returns (uint256) {
IMMRouter.VenueView memory v = FLAMMStore.s().router.venue(address(this), uint16(j));
(uint256 cl, uint256 sl) = largerLoss(j, v.account, v.id);
uint256 u = FLAMMStore.LOSS_MARK_UNIT;
return claimed | (cl / u) << 120 | (sl / u) << 168;
}
/// @notice The ratio senior claims of part `cs` settle at on one leg of a position of `whole`: the lower of `r`,
/// the ratio in force, and `r0`, the one read at the unwind that left the kept share, so the kept share
/// bears the rise its own withdrawal made and any after it; but at least `1 - whole * (1 - r) / cs`, past
/// which the kept share is spent and the claims bear the rest. Rounded up.
function senior(uint256 r, uint256 r0, uint256 whole, uint256 cs) internal pure returns (uint256 x) {
x = r < r0 ? r : r0;
uint256 f = Math.mulDiv(whole, WAD - r, cs);
if (f < WAD && WAD - f > x) x = WAD - f;
}
/// @notice The pool's own part of each kept share (`FLAMMStore.KEPT_SHIFT`), per token of `n`: its collateral and
/// supply at the venue's loss ratios behind the senior claims' due ({claimLoss}), shared pro rata with the
/// junior claims, rounded down, none where the share is written off (its unwritten bit clear); and the
/// debt past the senior claims' share, rounded up, written off or not, as it is still owed: the junior
/// claims' share too, as their exits paid it (`FLAMMStore.JUNIOR_DEBT_SHIFT`). NAV adds them
/// (`FLAMMGateLib.haircut`), and an exit pays its slice of the debt, so a write-off moves no value between
/// a leaver and the holders who stay. A kept share given up while junior claims stood
/// (`FLAMMStore.JUNIOR_DEBT_SHIFT`) owes their debt share alone, till the last settles (the void's is the
/// lender's), so neither the abandon nor a settlement moves NAV by it and an entry nets it as an exit
/// does. `ok` false where a venue's position or its lender's ratios do not read: NAV then refuses, the
/// skim abstains and the entries refuse. With `exit` only the debt is read, never the ratios, and where
/// the position does not read it is the debt the unwind that left the share read ({markKept}), at its
/// share of the record then: an exit never refuses over a lender that stops answering. Bound: the
/// interest accrued since that unwind on the share past the senior claims is not in it, so a leaver in an
/// outage leaves that interest on its slice to the holders who stay.
function keptLegs(uint256 n, bool exit)
public
view
returns (bool ok, uint256[] memory posted, uint256[] memory supplied, uint256[] memory owed)
{
FLAMMStore.S storage $ = FLAMMStore.s();
(posted, supplied, owed) = (new uint256[](n), new uint256[](n), new uint256[](n));
uint256 w = $.fenceWord;
uint256 m = ((w >> FLAMMStore.KEPT_SHIFT) | (w >> FLAMMStore.JUNIOR_DEBT_SHIFT)) & FLAMMStore.FENCE_VENUES;
IMMRouter r = $.router;
for (; m != 0; m &= m - 1) {
uint256 i = FLAMMFenceLib.low(m);
FLAMMStore.Fence storage f = $.fences[i];
(uint256 k, uint256 whole, uint256 cs) = (f.live, uint256(f.live) + f.claimed, f.fee & FLAMMStore.SENIORS);
// past the senior claims: the pool's part and the junior claims', or once given up the junior claims' alone
uint256 j = whole - cs;
uint256 dw = $.vaulted[uint256(f.key) | FLAMMStore.KEPT_DEBT];
if ((w >> (FLAMMStore.KEPT_SHIFT + i)) & 1 == 0) {
uint256 o = $.claims[f.key][FLAMMFenceLib.VOID];
j -= uint128(o) + (o >> 128);
if (j == 0) continue;
}
uint256 c;
uint256 s;
uint256 d;
try r.venuePosition(address(this), uint16(i)) returns (
uint256, uint256 c_, uint256, uint256 s_, uint256 d_
) {
(c, s, d) = (c_, s_, d_);
} catch (bytes memory reason) {
// the Router's lock, held by a callback, is no failure of the lender: a read at it reverts
ReentrancyGuardLib._passOnLock(reason);
if (!exit) return (false, posted, supplied, owed);
// the unwind's debt and its record's whole then ({markKept})
(d, whole) = (uint128(dw), uint120(dw >> 128));
}
// the junior claims' debt share too: their exits paid it (`FLAMMStore.JUNIOR_DEBT_SHIFT`)
owed[dw >> 248] += Math.mulDiv(d, j, whole, Math.Rounding.Up);
if (exit || (w >> (FLAMMStore.UNWRITTEN_SHIFT + i)) & 1 == 0) continue;
IMMRouter.VenueView memory v = r.venue(address(this), uint16(i));
uint256 cl;
uint256 sl;
if (($.lossVenues >> i) & 1 != 0) {
try IFinancingAccount(v.account).haircut(v.id) returns (uint64 a, uint64 b) {
(cl, sl) = (a, b);
} catch {
return (false, posted, supplied, owed);
}
(cl, sl) = _withMarks(i, cl, sl);
}
posted[v.coll] += _keptLeg(c, cl, cs, _r0(f.fee >> 120), whole, k);
supplied[v.debt] += _keptLeg(s, sl, cs, _r0(f.fee >> 168), whole, k);
}
ok = true;
}
/// @dev A stored ratio in mark units, back to WAD.
function _r0(uint256 field) private pure returns (uint256) {
return (field & MARK_FIELD) * FLAMMStore.LOSS_MARK_UNIT;
}
/// @dev The pool's part `k` of one leg `a` of a position of `whole` at ratio `r`: what stays past the senior
/// claims' due (`cs` of `whole` at {senior}'s ratio from `r0`), its share `k / (whole - cs)`, rounded down.
function _keptLeg(uint256 a, uint256 r, uint256 cs, uint256 r0, uint256 whole, uint256 k)
private
pure
returns (uint256)
{
uint256 worth = a - Math.mulDiv(a, r, WAD, Math.Rounding.Up);
if (cs != 0) {
uint256 x = senior(r, r0, whole, cs);
uint256 sc = Math.mulDiv(a, cs, whole, Math.Rounding.Up);
uint256 due = sc - Math.mulDiv(sc, x, WAD);
worth = worth > due ? worth - due : 0;
}
return Math.mulDiv(worth, k, whole - cs);
}
/// @notice Records, for each record of `m` the unwind just left a kept share at (`FLAMMClaimLib.unwindFence`),
/// as they read after the unwind's legs: the lender's loss ratios, spot, not the marks, and the time (the
/// reading a stranger's clear stays near, `clearKept`; read after the legs, as the pool's own withdrawal
/// moves the lender's ratio in a reserve it is much of); and the venue's debt, the record's whole and the
/// debt token, which an exit reads where the position does not ({keptLegs}).
function markKept(uint256 m) public {
FLAMMStore.S storage $ = FLAMMStore.s();
IMMRouter r = $.router;
uint256 w = $.fenceWord;
for (; m != 0; m &= m - 1) {
uint256 i = FLAMMFenceLib.low(m);
if ((w >> (FLAMMStore.KEPT_SHIFT + i)) & 1 == 0) continue;
IMMRouter.VenueView memory v = r.venue(address(this), uint16(i));
(uint256 cl, uint256 sl) = IFinancingAccount(v.account).haircut(v.id);
(,,,, uint256 d) = r.venuePosition(address(this), uint16(i));
FLAMMStore.Fence storage f = $.fences[i];
uint256 key = f.key;
$.vaulted[key | FLAMMStore.KEPT_READ] = cl | sl << 64 | block.timestamp << 128;
$.vaulted[key | FLAMMStore.KEPT_DEBT] = d | (uint256(f.live) + f.claimed) << 128 | uint256(v.debt) << 248;
}
}
/// @notice Pays `holder`'s claim word `word` on fence `key`, whose kept share a clear moved to its vault
/// (`clearKept`), to `to`: its senior part (the word's low 128 bits, where the clear found senior claims)
/// its share of the senior pot, and its junior part (past bit 128, and the low bits where it found none)
/// its share of the junior pot, in each pot's tokens, rounded down; the last part of a pot all of it.
function drawKept(uint32 key, uint256 word, address holder, address to) public {
FLAMMStore.S storage $ = FLAMMStore.s();
uint256 vs = $.vaulted[key];
uint256 sen = vs != 0 ? uint128(word) : 0;
_draw($, key, SENIOR_POT, sen, holder, to);
_draw($, key, JUNIOR_POT, (word >> 128) + uint128(word) - sen, holder, to);
}
/// @dev `part` of `pot`'s tokens in fence `key`'s vault, of the pot's total, paid to `to`; the pot's records and
/// total lowered.
function _draw(FLAMMStore.S storage $, uint32 key, address pot, uint256 part, address holder, address to) private {
if (part == 0) return;
uint256 slot = pot == SENIOR_POT ? uint256(key) : uint256(key) | 1 << 32;
uint256 total = $.vaulted[slot];
$.vaulted[slot] = total - part;
uint256 tk = $.vaulted[uint256(key) | 2 << 32];
for (uint256 n; n < 2; ++n) {
address token = FLAMMStore.tokenOf($, (tk >> (8 * n)) & 0xff);
uint256 have = $.parked[key][pot][token];
uint256 a = Math.mulDiv(have, part, total);
if (a == 0) continue;
$.parked[key][pot][token] = have - a;
FLAMMClaimVault($.vaults[key]).pay(token, to, a);
emit ParkedDrawn(key, holder, token, to, a);
}
}
/// @notice What an exit of `shares` of `supply` owes in token `t`, whose custody a fence holds out, past its
/// custody slice (`need`, a kept share's debt, `FLAMMFlowLib.proRata`): paid first from the part of the
/// pool's part it takes now (`FLAMMFenceLib.recordClaims`, none under `FLAMMFenceLib.DUST`; never a claim
/// standing in storage, which may be its receiver's from before), each `FLAMMFenceLib.ONE` of it worth the
/// lower of the custody the fence moved there (`FLAMMStore.S.strangerFloor`) and what the record holds now
/// ({_worth}). `cut`: the units the claim gives up, rounded up, which stay in the pool's part and so come
/// back to custody at the token's lift; `rest`: what the exit brings in, where the claim falls short, all
/// of `need` where the record holds no pool part (custody at most the fee at the fence, or the part given
/// up). No price: the claim and the debt are in the same token. Where the token's balance does not read
/// (an issuer that reverts `balanceOf`), the pot is the custody the fence moved, even after a burn or a
/// seizure lowered what the record holds: the exit then pays its need from its claim at that price, and
/// the holders who stay bear what the burn took of it.
function fromRecord(FLAMMStore.S storage $, uint256 t, uint256 need, uint256 shares, uint256 supply)
public
view
returns (uint256 cut, uint256 rest)
{
FLAMMStore.Fence storage g = $.fences[32 + t];
(uint256 live, uint256 claimed) = (g.live, g.claimed);
uint256 part = Math.mulDiv(live, shares, supply);
if (part < FLAMMFenceLib.DUST) return (0, need);
uint256 pot = Math.min($.strangerFloor[g.key], _worth($, t, g.fee, live + claimed));
if (pot == 0) return (0, need);
uint256 cover = Math.mulDiv(part, pot, FLAMMFenceLib.ONE);
if (cover >= need) return (Math.mulDiv(need, FLAMMFenceLib.ONE, pot, Math.Rounding.Up), 0);
return (part, need - cover);
}
/// @dev `FLAMMFenceLib.ONE` of token `t`'s record (`whole` its parts, `fee` the protocol's) at its holdings now, as
/// a settlement pays them: the token's balance outside custody past the fee, rounded down, so an issuer's burn
/// or seizure of the pool's balance lowers it. The most a word holds where the balance does not read, in one
/// try of {BALANCE_READ_GAS}, which the call must carry whole (`VenueReads.ReadStarved` otherwise), so no
/// caller starves the read into that answer. A token whose `balanceOf` needs more than that gas always reads
/// as unreadable, and the settlement then pays at the custody the fence moved.
function _worth(FLAMMStore.S storage $, uint256 t, uint256 fee, uint256 whole) private view returns (uint256) {
address token = FLAMMStore.tokenOf($, t);
bool ok;
uint256 bal;
if (gasleft() < BALANCE_READ_GAS * 64 / 63 + 10_000) revert VenueReads.ReadStarved();
assembly ("memory-safe") {
let m := mload(0x40)
mstore(m, shl(224, 0x70a08231)) // balanceOf(address)
mstore(add(m, 4), address())
ok := staticcall(BALANCE_READ_GAS, token, m, 36, 0, 0x20)
if lt(returndatasize(), 0x20) { ok := 0 }
bal := mload(0)
}
if (!ok) return type(uint256).max;
uint256 kept = FLAMMStore.heldOf($, t) + fee;
return bal > kept ? Math.mulDiv(bal - kept, FLAMMFenceLib.ONE, whole) : 0;
}
}
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.