Verified contractExactUNLICENSED
FLAMMTopUpLib
Address0xe4be161081d1c9aa91951ca347cc99da35cfac2e
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.35
- Same code
Only this contract
Details
- Compiler
- solc 0.8.35+commit.47b9dedd
- Language
- solidity
- Optimization
- Yes, 100 runs
- EVM version
- cancun
- Via IR
- yes
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,480,494
- Creation transaction
- 0x642b3d7ffb…87139f4743
- Libraries
- src/core/mm/MMRouterLib.sol:MMRouterLib0x95b3…48ef2csrc/core/flamm/FLAMMLane.sol:FLAMMLane0x5d81…90de37src/core/flamm/FLAMMRoute.sol:FLAMMRoute0xb1ff…7fb0fesrc/periphery/FLAMMMaxima.sol:FLAMMMaxima0x6854…90a91bsrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0xf55c…49cf45src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x0be7…5ecc47src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xa5db…72803esrc/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0x2795…4cfb77src/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0x3a05…434368src/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x70ca…60bee4src/core/mm/CTokenMarketLib.sol:CTokenMarketLib0x60e4…314010src/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0x0b10…1ce950src/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x634d…298fcdsrc/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0x5dc3…aa7e91src/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0x9dbb…798f1asrc/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0x6b2b…518935src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0x99de…929869src/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0xe4be…cfac2esrc/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0x93ab…262861src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x6abb…60ea7esrc/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0x3858…f91f06src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0x4551…33b301src/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xb852…b71005src/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x6a6a…798659src/hooks/everlong/LeverageLib.sol:LeverageLib0x8039…16d055src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0xaa54…b56417src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0x3bc5…2055ddsrc/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xf6d5…9dfeef
52 files
The source code is large: one file is shown at a time. Choose a file in the list.
- src/core/flamm/FLAMMTopUpLib.solmain52.56 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/FLAMMLawLib.sol61.53 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/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/FLAMMTopUpLib.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, NothingToMaintain, CollateralMaintained, 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 {FLAMMFenceLib} from "src/core/flamm/FLAMMFenceLib.sol";
import {ReentrancyGuardLib} from "src/libraries/ReentrancyGuardLib.sol";
import {IMMRouter} from "src/interfaces/core/mm/IMMRouter.sol";
import {IFinancingAccount, IFrameAccount, CAN_POST_COLLATERAL} from "src/interfaces/core/mm/IFinancingAccount.sol";
import {FLAMMSharedLib} from "src/core/flamm/FLAMMSharedLib.sol";
/// @notice The pool's permissionless collateral maintainer ({maintainCollateral}, which the pool's dispatch table
/// routes here): the due venue of lowest health over every pair, posted back to its target from the custody
/// the pool owns, and at a frame's account the frame's due point, its cushion and the post through a mate.
/// Also a swap's rotation ({rotate}), which its settlement runs out of line, and the draw a quote sizes for it
/// ({rotationNeed}). Out of line of every flow.
library FLAMMTopUpLib {
/// @dev The maintainer acts once a debt-bearing venue's LTV has used this share of the room between its target and
/// its threshold: the target is its pair's pin, or the threshold less the pair's gap where a lender's cut
/// leaves less than the gap over the pin but more than the gap, and the pool's custody of the collateral token
/// can still bring the venue under its threshold at the lower price it reads (the venue's own only while the
/// pair's venue-oracle band is on). At 0.612 for a 0.55 pin under 0.86, at 0.897 for a 0.895 pin under 0.905
/// with a 0.005 gap; under a cut to 0.40 with a 0.02 gap, at 0.384, posting back to 0.38.
uint256 internal constant MAINTAIN_ROOM_SHARE_WAD = 0.2e18;
/// @dev A frame's venue (`FLAMMFenceLib.mates`) past its trigger waits for its frame until its LTV has used this
/// share of the same room, the frame's cushion: within it the venue falls due only once the frame is short,
/// its venues' collateral summed under what their triggers ask ({_waits}); past it, it is due on its own, as a
/// pair's own venue past its trigger. So a venue that takes posts never leans on its mates' collateral past
/// this share of its room, which their own borrows and releases could take back; one that takes none is topped
/// up through a mate ({_throughMate}). At 0.798 for a 0.55 pin under 0.86, at 0.903 for a 0.895 pin under
/// 0.905 with a 0.005 gap.
uint256 internal constant FRAME_ROOM_SHARE_WAD = 0.8e18;
/// @dev {frameBound}'s `cover` for a draw of `y` at pair `cover - DRAW`: pairs number under `MAX_POOL_PAIRS`.
uint8 internal constant DRAW = 0x80;
/// @dev How the maintainer posts at the venue it chose: `coll`, its collateral token by index; `worst`, its health
/// on raw collateral at `price36` and its threshold, WAD, which ranks the due venues; `price36`, its price for
/// the maintainer, debt base units per collateral base unit, 1e36 ({_target}); `posted`, its recognized
/// collateral, and `debt`, its debt, in each token's base units; `target`, its target LTV, WAD; `frame`, the
/// live venues of its frame, bit `i` for venue `i` (the venue's bit alone at a pair's own account); `room` and
/// `actions`, at that lone venue, the post room and the actions the choice read (a frame's venue reads none
/// there, and they stay zero); `ignored`, a frame's venue holding collateral its lender counts for nothing
/// ({_ignored}), which takes no post of its own.
struct Due {
uint8 coll;
uint256 worst;
uint256 price36;
uint256 posted;
uint256 debt;
uint256 target;
uint256 frame;
uint256 room;
uint8 actions;
bool ignored;
}
/// @dev {maintainCollateral}'s frames, each read once a call: each slot's live frame venues (`mask`, zero until
/// read; the slot's bit alone at a pair's own account) and, by a frame's lowest slot, whether it was summed
/// (`summed`) and covers its venues' triggers (`waits`, {_waits}). Collateral and debt do not move between the
/// call's runs of {_worstDue}, as a recall withdraws supply alone, so each holds for every run.
struct Frames {
uint256[32] mask;
uint256 summed;
uint256 waits;
}
// ------------------------------------------------------------------ the lock
/// @dev The pool's lock, taken for the entry and cleared when it returns.
modifier nonReentrant() {
ReentrancyGuardLib._guard();
_;
ReentrancyGuardLib._unlockGuard();
}
// ------------------------------------------------------------------ permissionless health maintainer
/// @notice Posts custody of a venue's collateral token at the weakest indebted venue, over every pair whose price
/// it reads, whose LTV has used a fifth of the room between its target and its threshold, back to the
/// target as far as custody and the venue's post room go: its pair's pin, or the threshold less the pair's
/// gap under a lender's cut that leaves less than the gap over the pin but more than the gap, where custody
/// can still bring the venue under its threshold at the lower price it reads. A due venue that takes no
/// post (its cap full, or a post refused) is passed over, save one whose room the pool's own supply of that
/// token fills at venues sharing one reserve's room: that supply is withdrawn first, as far as the
/// shortfall, the only supply it ever withdraws. At a frame's account a venue past that point waits while
/// its frame covers its venues' triggers, within the frame's cushion, and one that takes no post is topped
/// up through a mate; `venueId` is then the mate (`FLAMMTopUpLib`). A venue at a pair's own account that
/// custody cannot bring under its threshold at its lender's price, and that its lender reads unhealthy, is
/// passed over: a post there saves nothing, and past the lender's bad-debt point it only pays that debt.
/// Where its lender's price is not read (its pair's band off, or an oracle that does not answer) the pool's
/// own price sizes it.
/// That threshold is the one its lender liquidates past (`FLAMMGateLib.liquidationWad`), whatever the
/// account's own threshold reads, zero included (a lender's brake on the collateral): where a kind answers
/// none it is one whole, so only a venue that custody leaves under water is passed over there.
/// Permissionless, never paused or feature-gated. A venue whose pair's price is unchecked is passed
/// over, as no price sizes its post: where
/// no other venue takes a post the call reverts `PriceUnchecked` while such a venue owes, and
/// `NothingToMaintain` when none does and no post is due at a venue that takes one. A frame's sum that
/// would read such a venue's debt at a priced collateral token reverts `PriceUnchecked` too, whatever else
/// is due.
/// @dev The rules, in order:
/// - Target: a venue's target is its pair's pin, or, where a lender's cut leaves less than the gap over the
/// pin, its threshold less the gap while that is above zero and the pool's custody of the venue's collateral
/// token could bring the venue's raw collateral under its threshold at the lower of the pool's price and,
/// while the pair's venue-oracle band is on, the venue's own; past that the target stays the pin, as with no
/// cut.
/// - Due: a venue is due once its LTV on recognized collateral passes the target plus
/// `MAINTAIN_ROOM_SHARE_WAD` of the room from there to its threshold. Each venue is priced at that lower
/// price while custody could still bring the venue under its threshold there, and at ours past that. While
/// the band is on, a venue at a pair's own account that custody cannot bring under its threshold at its
/// lender's price, lower than ours or not, and that its lender's own check reads unhealthy
/// (`IMMRouter.venueHealthy`: past its liquidation threshold where the threshold here is a borrow ceiling
/// under it), is not due through this call: the post would save nothing, and
/// past the lender's bad-debt point it would pay that debt from the holders' custody. It is the keeper's to
/// repay or the curator's to fence. At a frame's venue the frame's sums decide, as its lender liquidates on
/// them.
/// - Post: the due venue of lowest health on raw collateral, over every pair, which the venue liquidates on,
/// is posted back to its target at its price as far as custody and the venue's post room
/// (`IFinancingAccount.Capacity.collateralPostable`) go, so a venue not due never hides one that is, nor
/// does a due venue that takes no post. A third-party gift lifts raw collateral only and neither silences
/// nor shrinks the post.
/// - Price: a venue whose pair's price is unchecked is never due through this call, as no price sizes its
/// post: it is passed over and hides no venue outside its own frame. Where no other venue takes a post, the
/// call refuses `PriceUnchecked` while one was passed over so, as a post may be due there, and
/// `NothingToMaintain` while none was. A frame's sum that would read such a venue's debt at a priced
/// collateral token refuses `PriceUnchecked` too ({_waits}, {_throughMate}), and with it the whole call, a
/// due venue of another pair or frame among it: a sum without that debt would read the frame as covering
/// more than it does. At a collateral token with no price no sum reads ({_frameSums}).
/// - Recall: it withdraws supply only where the post room is short at a venue that takes posts and shares one
/// reserve's room with the venues the pool lends the token at in that reserve (`S.sharedVenues` of the
/// venue's kind number, which binds one lender: whose supply fills that room): that supply first, as far as
/// the shortfall ({_recall}). A due venue whose room the recall does not open is passed over for the next
/// worst, so it hides none that takes a post.
/// - Frames: the venues at a frame's account (`FLAMMFenceLib.mates`) share one position at the lender, which
/// liquidates the frame on their sum, so one past its trigger waits for its frame within the frame's cushion
/// (`FRAME_ROOM_SHARE_WAD`, {_waits}): top-ups fall due when the frame is short, not each venue. A due venue
/// of a frame that takes no post (custody holds none of its token, or its room stays shut) is topped up
/// through a mate that takes one ({_throughMate}): the frame's shortfall at its venues' targets, in the
/// mate's token, as far as custody and the mate's room go, the lender counting it for the whole frame.
/// - Counted: a frame's venue that holds collateral its lender counts for nothing
/// (`IFrameAccount.collateralCounted`: at Aave, a posted token whose collateral flag is down) holds none
/// here either, whatever its threshold reads: it adds nothing to its frame's sums ({_frameSums}), and while
/// it owes and its frame is short it is due as a venue holding none, ranked first ({_ignored}). It takes no
/// post of its own, which its lender would count for nothing or which no figure here sizes, and no top-up
/// goes through it: the frame's shortfall, on what the lender counts, goes through a mate the lender counts
/// ({_throughMate}). One the lender counts at a threshold that reads zero (at Aave, a flag up at a zero
/// LTV) is summed and checked at face, as the lender still counts it at its liquidation threshold. A venue
/// that holds nothing is none of these, whatever its lender answers (Aave clears a flag once a release or
/// a seizure takes the last unit): its own target sizes its post, a mate's post through it is the frame's
/// shortfall, and the lender counts either from its first unit.
function maintainCollateral() public nonReentrant returns (uint16 venueId, uint256 posted) {
FLAMMStore.S storage $ = FLAMMStore.s();
FLAMMGateLib.Book memory b = FLAMMGateLib.priced($);
Due memory due;
Frames memory fr;
uint256 skip;
while (true) {
(venueId, due) = _worstDue($, b, skip, fr);
if (due.debt == 0) revert NothingToMaintain();
// Due is short of the trigger's collateral, which is at most the target's: the shortfall is never zero.
// Only the custody the pool owns posts, never the spread fee it keeps for the protocol (the book's `held`).
posted = Math.min(
FLAMMGateLib.requiredPosted(due.debt, due.target, due.price36) - due.posted, b.legs[due.coll].held
);
// nothing moved since the choice read a lone venue's capacity
(uint256 room, uint8 actions) = (due.room, due.actions);
if (due.frame != uint256(1) << venueId && !due.ignored) {
(room, actions) = (FLAMMGateLib.postable($, venueId), $.router.venueActions(address(this), venueId));
}
// supply is recalled only for a venue that takes posts: a frame's venue whose room is shut stays a
// candidate for its mate's post, and one that refuses posts would free room for nothing
if (posted > room && actions & CAN_POST_COLLATERAL != 0) {
_recall($, venueId, due.coll, posted - room);
room = FLAMMGateLib.postable($, venueId);
}
posted = Math.min(posted, room);
if (posted != 0) break;
if (due.frame != uint256(1) << venueId) {
(uint16 mate, uint8 t, uint256 x) = _throughMate($, b, venueId, due.frame);
if (x != 0) {
(venueId, due.coll, posted) = (mate, t, x);
break;
}
}
skip |= uint256(1) << venueId;
}
// tracked custody, read after any recall raised it, so the fee's kept part stays tracked
post($, due.coll, venueId, posted, FLAMMStore.heldOf($, due.coll));
FLAMMStore.reconcile($);
emit CollateralMaintained(venueId, posted, msg.sender);
}
/// @dev {maintainCollateral}'s due venue of lowest health outside `skip` (`due.debt` zero: none). A venue of a
/// frame past its trigger is due only past the frame's cushion or while its frame is short ({_waits}); one
/// whose post room is shut stays a candidate, as a mate may take the post ({_throughMate}). Each frame is read
/// and summed once a call (`fr`), however its venues sit in slot order. An indebted venue whose pair's price
/// is unchecked is passed over before its target is read ({_target}): no price sizes a post there, and it
/// hides no venue of another pair. Where none is due and one was passed over so, it refuses `PriceUnchecked`,
/// as a post may be due there. A frame's venue holding collateral its lender counts for nothing ({_ignored})
/// is read as holding none: due at a health of zero while its frame is short ({_waits}), whose sums count
/// none of its collateral and all of its debt, and a candidate for its mate's post alone, as it takes none of
/// its own; with no live mate it is passed over. One that holds nothing is read as any venue: due on its own
/// target, which its own post meets.
function _worstDue(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 skip, Frames memory fr)
private
view
returns (uint16 venueId, Due memory due)
{
IMMRouter router = $.router;
uint256 n = router.venueCount(address(this));
bool unpriced;
for (uint256 i; i < n; ++i) {
// an idle slot holds nothing the Router recognizes, so it owes nothing (`FLAMMStore.unread`)
if (FLAMMStore.unread($, i) || (skip >> i) & 1 != 0) continue;
(uint256 r, uint256 c,,, uint256 d) = router.venuePosition(address(this), uint16(i));
if (d == 0) continue;
IMMRouter.VenueView memory v = router.venue(address(this), uint16(i));
// no price sizes a post at a pair whose price is unchecked: passed over, it hides no other pair's venue
if (FLAMMGateLib.frameOf(b, v.coll, v.debt) == 0) {
unpriced = true;
continue;
}
(uint256 p, uint256 t, uint256 room, bool lost) = _target($, b, v, r, d);
// what its lender counts for nothing holds up none of the venue's debt, whatever its threshold reads; a
// venue holding nothing is asked nothing, as its lender counts its post from the first unit
bool ignored = c != 0 && _ignored(v);
if (ignored) (r, c) = (0, 0);
if (c >= FLAMMGateLib.requiredPosted(d, t + room * MAINTAIN_ROOM_SHARE_WAD / WAD, p)) continue;
uint256 m = fr.mask[i];
if (m == 0) {
m = _frame($, v, i);
for (uint256 k = m; k != 0; k &= k - 1) {
fr.mask[FLAMMFenceLib.low(k)] = m;
}
}
(uint256 postRoom, uint8 actions) = (0, 0);
if (m != uint256(1) << i) {
// a frame's venue within the cushion waits while its frame covers what its venues' triggers ask, and
// so does one its lender ignores, which only a mate's post tops up; one whose room is shut stays a
// candidate, as a mate may take the post
if (ignored || c >= FLAMMGateLib.requiredPosted(d, t + room * FRAME_ROOM_SHARE_WAD / WAD, p)) {
uint256 lo = m & (~m + 1);
if (fr.summed & lo == 0) {
fr.summed |= lo;
if (_waits($, b, m)) fr.waits |= lo;
}
if (fr.waits & lo != 0) continue;
}
} else {
// one that custody cannot bring back under its threshold at its lender's price, and that its lender
// reads unhealthy, is passed over: a post there saves nothing ({_target})
if (lost && !router.venueHealthy(address(this), uint16(i))) continue;
// A venue whose cap admits no more collateral, or that refuses a post, takes none: it is passed over,
// but where the pool's own supply of the token fills the room it shares. The two fields alone, read as
// `FLAMMGateLib.postable` reads the room; a room proves the post allowed, so the bits are read only
// where there is none.
postRoom = IFinancingAccount(v.account).collateralPostable(v.id);
actions = postRoom != 0 ? CAN_POST_COLLATERAL : IFinancingAccount(v.account).actions(v.id);
if (ignored || (postRoom == 0 && _lentBeside($, i, v.coll, actions) == 0)) continue;
}
uint256 h = Math.mulDiv(Math.mulDiv(r, p, 1e36), v.lltvWad, d);
if (due.debt == 0 || h < due.worst) {
(venueId, due) = (uint16(i), Due(v.coll, h, p, c, d, t, m, postRoom, actions, ignored));
}
}
if (due.debt == 0 && unpriced) revert PriceUnchecked();
}
/// @dev Venue `v`'s price for the maintainer, its target and the room from there to its threshold, at raw
/// collateral `r` and debt `d` ({maintainCollateral}); `PriceUnchecked` where its pair's price is unchecked:
/// {_worstDue} passes such a venue over before this read, and a frame's sums ({_frameSums}) and a draw's
/// bound ({_carried}) refuse with it. `lost`: the pool's custody of the collateral token cannot bring the
/// venue's raw collateral under the threshold its lender liquidates past, at its lender's own price, lower
/// or not, where {_worstDue} passes a pair's own venue over; and at the pool's price where the lender's is
/// not read (the pair's venue-oracle band off, or an oracle that does not answer), as a flush sizes it
/// (`FLAMMBlindLib._liquidation`): sized only where the lender's price read, nothing was lost without it,
/// and all custody was posted into a venue under water. That
/// threshold is the lender's own (`FLAMMGateLib.liquidationWad`): `lltv` where it is that threshold, the
/// kind's own read of it where `lltv` may be a borrow ceiling under it or zero, and one whole where no read
/// answers it. Sized at a borrow ceiling, a post that would restore the lender's health was refused; sized at
/// one whole where a read answers, all custody was posted into a venue its lender still liquidates, past its
/// bad-debt point, where the liquidator takes every unit posted; and at a threshold of zero, which no post
/// reaches, nothing was ever lost, so all custody was posted into a venue under water.
function _target(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
IMMRouter.VenueView memory v,
uint256 r,
uint256 d
) private view returns (uint256 p, uint256 t, uint256 room, bool lost) {
p = FLAMMGateLib.frameOf(b, v.coll, v.debt);
if (p == 0) revert PriceUnchecked();
IMMRouter.PairView memory pv = $.router.pair(address(this), v.pair);
(uint256 gap, uint256 pin) = (pv.safetyGapWad, $.pairs[v.pair].ltvWad);
(uint256 held, uint256 low) = (b.legs[v.coll].held, p);
// The lender's own price, or the pool's where the lender's is not read: a pair whose band is off, or an
// oracle that does not answer.
uint256 q = p;
if (pv.oracleBandWad != 0) {
(bool ok, uint256 own) = IFinancingAccount(v.account).oraclePrice(v.id);
if (ok && own != 0) q = own;
}
// Past what custody can bring back under the threshold at that price, a post there saves nothing: it only
// adds to what the lender seizes and leaves the swaps no custody. A threshold of zero (the lender's brake on
// the collateral) is one no post reaches.
bool far = v.lltvWad == 0 || FLAMMGateLib.requiredPosted(d, v.lltvWad, q) > r + held;
if (q < p) (low, p) = (q, far ? p : q);
if (far) lost = FLAMMGateLib.requiredPosted(d, FLAMMGateLib.liquidationWad(v), q) > r + held;
// The threshold may be a borrow cap (`IFinancingAccount.lltv`): a cut to the gap or under it, or past what
// custody can bring under it at the lower price, keeps the pin as the target, as before the cut.
(t, room) = (pin, v.lltvWad > pin ? v.lltvWad - pin : 0);
if (v.lltvWad < pin + gap && v.lltvWad > gap && FLAMMGateLib.requiredPosted(d, v.lltvWad, low) <= r + held) {
(t, room) = (v.lltvWad - gap, gap);
}
}
/// @dev Whether venue `v` sits at a frame's account whose lender counts its collateral for nothing
/// (`IFrameAccount.collateralCounted`, which every kind that holds a frame answers): at Aave, a posted token
/// whose collateral flag is down, at a zero LTV or one since restored; at Venus, a collateral market at a
/// liquidation threshold of zero; at either, a lender that cannot be read. A pair's own account is not asked:
/// its lender counts what it posts, and its threshold alone speaks. Asked only of a venue that holds
/// collateral: Aave answers a venue holding none as it does a lowered flag.
function _ignored(IMMRouter.VenueView memory v) private view returns (bool) {
return IFinancingAccount(v.account).COLLATERAL_ASSET() == address(0)
&& !IFrameAccount(v.account).collateralCounted(v.id);
}
/// @dev The live venues of venue `i`'s (`v`) frame: every live slot at its account where that is a frame's
/// (`FLAMMFenceLib.mates`), `i`'s bit alone at a pair's own account, which answers its collateral token: one
/// read where it does.
function _frame(FLAMMStore.S storage $, IMMRouter.VenueView memory v, uint256 i) private view returns (uint256 m) {
m = uint256(1) << i;
if (IFinancingAccount(v.account).COLLATERAL_ASSET() == address(0)) {
m = FLAMMFenceLib.matesOf($, uint16(i)) & ~uint256($.retiredVenues);
}
}
/// @dev Whether a frame's live venues `m` still cover what their triggers ask, summed ({_frameSums}): a venue of
/// the frame past its trigger and within the cushion waits then.
function _waits(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 m) private view returns (bool) {
(uint256 have, uint256 trig,) = _frameSums($, b, m);
return have >= trig;
}
/// @dev Over a frame's live venues `m`, in USD at `b`'s prices: what their recognized collateral is worth (`have`),
/// and what it would be at each indebted one's trigger (`trig`) and target (`want`) for its debt, at the
/// venue's own price for the maintainer ({_target}), rounded up. Where a venue holding a position has no USD
/// price for its collateral token (a pool with no band reads none), no sum reads: `trig` is the most and the
/// rest zero, so no venue of the frame waits for it and no mate posts for it. A venue whose collateral its
/// lender counts for nothing (`IFrameAccount.collateralCounted`) adds nothing to `have`, its debt still
/// counting, as Aave counts none of a token whose flag is down (`AaveV3Account.setCollateralFlag`), at a zero
/// LTV or one since restored: it holds up no venue of the frame, its own included. One the lender counts adds
/// its collateral at face whatever its threshold reads (`IMMRouter.VenueView.lltvWad`, zero at Aave's zero
/// LTV with the flag up, where Aave counts the token at its liquidation threshold).
function _frameSums(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 m)
private
view
returns (uint256 have, uint256 trig, uint256 want)
{
IMMRouter router = $.router;
for (uint256 i; m >> i != 0; ++i) {
if ((m >> i) & 1 == 0) continue;
IMMRouter.VenueView memory v = router.venue(address(this), uint16(i));
(uint256 r, uint256 c,,, uint256 d) = router.venuePosition(address(this), uint16(i));
// the collateral token's USD per base unit, scaled by 1e36: zero unchecked
uint256 u = b.usd[v.coll] * b.legs[v.coll].scale;
if (u == 0 && (r | d) != 0) return (0, type(uint256).max, 0);
if (c != 0 && IFrameAccount(v.account).collateralCounted(v.id)) have += Math.mulDiv(c, u, WAD);
if (d == 0) continue;
(uint256 p, uint256 t, uint256 room,) = _target($, b, v, r, d);
trig += Math.mulDiv(
FLAMMGateLib.requiredPosted(d, t + room * MAINTAIN_ROOM_SHARE_WAD / WAD, p), u, WAD, Math.Rounding.Up
);
want += Math.mulDiv(FLAMMGateLib.requiredPosted(d, t, p), u, WAD, Math.Rounding.Up);
}
}
/// @dev Where due venue `id` of a frame (its live venues `m`) takes no post: the first other venue of `m`, in slot
/// order, posting a token the pool owes nowhere that takes some, and what it takes of the frame's shortfall at
/// its venues' targets ({_frameSums}), in that venue's token at `b`'s price, rounded up, as far as custody the
/// pool owns and the venue's room go. None where the frame is at its targets. A venue holding collateral its
/// lender counts for nothing (`IFrameAccount.collateralCounted`) is no mate: the sums count nothing posted
/// there, and where a post would make the lender count it again, the shortfall does not size it; one that
/// holds nothing is a mate as any other, as its lender counts the post from its first unit. Nor is one whose
/// threshold reads zero (`IMMRouter.VenueView.lltvWad`) a mate, though its lender counts it: the lender lends
/// no more on that token, and while that venue owes the Router releases none of what is posted there, so a
/// post would only move custody out of the swaps' reach. The post is that mate's own recorded collateral,
/// which the lender counts for the whole frame: no one holds it there for `id`. A swap, a rotation among its
/// releases (refused past it), and the keeper's release take it back only down to the frame's summed triggers
/// ({frameBound}), the keeper's move of the mate's debt to another account only where the frame stays over
/// them, and an emergency withdrawal at the mate waits for every debt of the frame (`FLAMMMaintainLib`); a
/// redemption takes the same part of every venue of the frame. A cover's proportional release at the mate,
/// held by the plan's ceiling alone, may take it back while `id` sits past its trigger. It buffers the frame
/// until then, and a later call posts again while `id` is due.
function _throughMate(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint16 id, uint256 m)
private
view
returns (uint16 mate, uint8 t, uint256 x)
{
(uint256 have,, uint256 want) = _frameSums($, b, m);
if (want <= have) return (0, 0, 0);
IMMRouter router = $.router;
(uint16 owed,) = router.drawn(address(this));
m &= ~(uint256(1) << id);
for (uint256 i; m >> i != 0; ++i) {
if ((m >> i) & 1 == 0) continue;
IMMRouter.VenueView memory v = router.venue(address(this), uint16(i));
t = v.coll;
uint256 u = b.usd[t] * b.legs[t].scale;
if ((owed >> t) & 1 != 0 || u == 0 || v.lltvWad == 0) continue;
if (!IFrameAccount(v.account).collateralCounted(v.id)) {
(, uint256 c,,,) = router.venuePosition(address(this), uint16(i));
if (c != 0) continue;
}
x = Math.min(Math.mulDiv(want - have, WAD, u, Math.Rounding.Up), b.legs[t].held);
x = Math.min(x, FLAMMGateLib.postable($, uint16(i)));
if (x != 0) return (uint16(i), t, x);
}
}
/// @dev Whether venue `j` lends token `t` into the reserve venue `id` posts it to: a venue sharing one reserve's
/// room (`S.sharedVenues`) of `id`'s kind number, as each kind's deployer binds one lender (one Aave Pool, one
/// comptroller).
function _besideIn(IMMRouter r, uint256 j, uint8 t, uint8 kind) private view returns (bool) {
IMMRouter.VenueView memory w = r.venue(address(this), uint16(j));
return w.debt == t && w.kind == kind;
}
/// @dev What the pool lends of token `t` at the venues sharing the reserve's room venue `id` posts `t` to
/// ({_besideIn}), whose supply fills the room a post there needs: zero unless `id` is one and takes posts
/// (`actions`).
function _lentBeside(FLAMMStore.S storage $, uint256 id, uint8 t, uint8 actions) private view returns (uint256 s) {
uint256 m = $.sharedVenues & ~uint256($.retiredVenues);
if ((m >> id) & 1 == 0 || actions & CAN_POST_COLLATERAL == 0) return 0;
IMMRouter r = $.router;
uint8 kind = r.venue(address(this), uint16(id)).kind;
for (uint256 j; m >> j != 0; ++j) {
if ((m >> j) & 1 == 0 || !_besideIn(r, j, t, kind)) continue;
(,,, uint256 sup,) = r.venuePosition(address(this), uint16(j));
s += sup;
}
}
/// @dev Withdraws up to `short` of token `t` the pool lends beside venue `id`, a venue that takes posts
/// ({_lentBeside}), into custody, venue by venue, a withdrawal its lender refuses passed over, so a post at
/// `id` takes the room it frees: what came back, its tracked custody raised by it.
function _recall(FLAMMStore.S storage $, uint16 id, uint8 t, uint256 short) private returns (uint256 got) {
IMMRouter r = $.router;
uint256 m = $.sharedVenues & ~uint256($.retiredVenues);
if ((m >> id) & 1 == 0) return 0;
uint8 kind = r.venue(address(this), id).kind;
for (uint256 j; m >> j != 0 && got < short; ++j) {
if ((m >> j) & 1 == 0 || !_besideIn(r, j, t, kind)) continue;
(,,, uint256 sup,) = r.venuePosition(address(this), uint16(j));
if (sup == 0) continue;
try r.withdrawSupplied(uint16(j), Math.min(sup, short - got), address(this)) returns (uint256 w) {
got += w;
} catch {}
}
if (got != 0) FLAMMStore.setHeld($, t, FLAMMStore.heldOf($, t) + got);
}
// ------------------------------------------------------------------ what a swap may take of a frame's collateral
/// @notice At most `amount` of `y`'s posted collateral on `b`, and, while a venue of a frame posting `y` lacks, no
/// more than that frame spares. A frame posts `y` where a pair of `y` has a venue there that is not idle
/// (`S.idleVenues`, the venues a read found empty). The venues at a frame's account (`FLAMMFenceLib.mates`)
/// share one position at the lender, which counts `y` there for every debt of the frame, those of pairs
/// that do not post `y` among them. Where each venue covers its own trigger ({_frameSums}), each venue's
/// release rule gives up only what the frame spares, so `amount` stands. Where one does not, the others'
/// collateral holds it up: a release may take the frame's recognized collateral down to what its indebted
/// venues' triggers ask, summed, and no further, in `y` at `b`'s price, rounded down. The Router's reclaim
/// walks one total across `y`'s venues in its own order, so while the frame lacks that bound takes the
/// whole total, what venues outside the frame could give among it. Read only at venues whose kind can
/// refuse an action and shares a reserve's cash (`S.gatedVenues`, `S.sharedVenues`), as both pooled kinds
/// declare, whose accounts alone can be a frame's (`PooledAccount`), and only on a pool with a band, as one
/// with none owes nothing. A swap's plan reads it before a cover's repay, its settlement after it, and a
/// repay at a frame's venue can only raise what that frame spares. So the plan names the cover pair `cover`
/// (`FLAMMStore.NO_PAIR`: none), whose indebted venues at the frame read as repaid in full: their triggers
/// ask nothing, and their whole post counts. The rest of the frame's triggers come out of it, so a debt too
/// small to free a post leaves the post holding up the venue that leans on it, and a repay outside the
/// frame adds nothing to it. With `cover` at `DRAW` plus a pair, `amount` is instead a swap's ceiling for
/// `y` drawn there, whose part past `y`'s custody takes no frame from over its triggers to under them, nor
/// lowers one under them ({_drawBound}).
function frameBound(FLAMMGateLib.Book memory b, uint256 y, uint256 amount, uint8 cover)
public
view
returns (uint256)
{
FLAMMStore.S storage $ = FLAMMStore.s();
uint256 live = ~uint256($.retiredVenues | $.idleVenues);
uint256 pooled = $.gatedVenues & $.sharedVenues & live;
if (amount == 0 || pooled == 0 || $.noBand) return amount;
if (cover >= DRAW && cover != FLAMMStore.NO_PAIR) {
uint256 held = b.legs[y].held;
return amount > held ? held + _drawBound($, b, cover - DRAW, amount - held, pooled, live) : amount;
}
uint256 seen;
uint256 n = $.pairCount;
for (uint256 q; q < n; ++q) {
FLAMMStore.PairCfg storage pc = $.pairs[q];
if (pc.coll != y) continue;
uint256 m = pc.venues & pooled;
while ((m &= ~seen) != 0) {
uint256 f = FLAMMFenceLib.matesOf($, uint16(FLAMMFenceLib.low(m)));
seen |= f;
f &= live;
// a pair's own account, or a frame with one venue not idle: the posting law alone binds it
if (f & (f - 1) == 0) continue;
amount = _frameSpare($, b, y, f, amount, cover);
if (amount == 0) return 0;
}
}
return amount;
}
/// @dev What the collateral pair `pair`'s indebted venues in frame `f` post, as the Router recognizes it, and those
/// venues.
function _postedOwing(FLAMMStore.S storage $, uint8 pair, uint256 f)
private
view
returns (uint256 posted, uint256 owing)
{
IMMRouter r = $.router;
for (uint256 mask = $.pairs[pair].venues & f; mask != 0; mask &= mask - 1) {
uint256 id = FLAMMFenceLib.low(mask);
(, uint256 rec,,, uint256 d) = r.venuePosition(address(this), uint16(id));
if (d != 0) (posted, owing) = (posted + rec, owing | uint256(1) << id);
}
}
/// @dev `amount`, within what frame `f` (its venues not idle or retired) spares of `y` over their triggers, summed,
/// where one of them lacks: its recognized collateral, as {_frameSums} counts it (none its lender ignores),
/// is under its own trigger ({frameBound}), the `cover` pair's indebted venues read as repaid. Each venue's
/// own read, then the frame's and the cover's only where one lacks; a venue holding collateral with no price
/// on `b` reads as lacking, and its frame as sparing none.
function _frameSpare(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
uint256 y,
uint256 f,
uint256 amount,
uint8 cover
) private view returns (uint256) {
bool lacks;
for (uint256 m = f; m != 0 && !lacks; m &= m - 1) {
(uint256 h, uint256 t,) = _frameSums($, b, uint256(1) << FLAMMFenceLib.low(m));
lacks = h < t;
}
if (!lacks) return amount;
(uint256 repaid, uint256 owing) =
cover == FLAMMStore.NO_PAIR ? (uint256(0), uint256(0)) : _postedOwing($, cover, f);
(uint256 have, uint256 trig,) = _frameSums($, b, f & ~owing);
uint256 unit = b.usd[y] * b.legs[y].scale;
have += Math.mulDiv(repaid, unit, WAD);
if (have <= trig) return 0;
uint256 spare = Math.mulDiv(have - trig, WAD, unit);
return spare < amount ? spare : amount;
}
/// @dev `amount`, a draw at pair `bp`, within what each frame holding a venue of `bp` spares over its venues'
/// triggers, summed ({_frameSpare}'s read). A draw there spends that spare within its venue's own room at the
/// pin; past it the Router posts for the draw at the pin at `b`'s price, which raises the frame's sum unless
/// the trigger's price, the lender's where lower ({_target}), values that post under what the draw adds to
/// the trigger. So where that room, at the frame's venues of `bp`, can take no more than the frame spares and
/// every such post raises the sum, the draw stands; else it stops at the debt the spare carries ({_carried}),
/// none where the frame is at or under its triggers. Where every post raises the sum and no venue of the
/// frame lacks, each venue's own room spends at most its own surplus, so the draw stands, as at a venue of
/// no frame. The Router's funding walks one total across `bp`'s venues in its own order, so where a frame
/// binds the bound takes the whole draw, what venues outside the frame would fund among it.
function _drawBound(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
uint8 bp,
uint256 amount,
uint256 pooled,
uint256 live
) private view returns (uint256) {
uint256 venues = $.pairs[bp].venues & pooled;
uint256 seen;
uint256 m = venues;
while ((m &= ~seen) != 0) {
uint256 f = FLAMMFenceLib.matesOf($, uint16(FLAMMFenceLib.low(m)));
seen |= f;
f &= live;
if (f & (f - 1) == 0) continue;
(uint256 have, uint256 trig,) = _frameSums($, b, f);
amount = _carried($, b, f & venues, have > trig ? have - trig : 0, amount);
if (amount == 0) return 0;
}
return amount;
}
/// @dev Within `amount`, a draw at venues `m` of a frame sparing `spare` over its triggers (USD at `b`'s prices, as
/// {_frameSums} sums it): `amount` where what their own room at the pin (the pair's `ltvWad`, which the
/// Router's pin follows, at `b`'s price) would add to their triggers is at most `spare`, and at each the
/// trigger LTV at the trigger's price carries the pin at `b`'s; else the debt `spare` carries, none where that
/// is under the settlement's least draw (`FLAMMSettleLib.MIN_DRAW`), which a short past the drawn token's
/// supply takes at the least. Converts at the lowest trigger LTV and price among `m`, rounded down, so it
/// under-allows, as it does a short within that supply under the least draw.
function _carried(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint256 m, uint256 spare, uint256 amount)
private
view
returns (uint256)
{
IMMRouter router = $.router;
(uint256 spend, uint256 most, bool posts) = (0, amount, true);
for (; m != 0; m &= m - 1) {
uint16 id = uint16(FLAMMFenceLib.low(m));
IMMRouter.VenueView memory v = router.venue(address(this), id);
(uint256 r,,,, uint256 d) = router.venuePosition(address(this), id);
uint256 u = b.usd[v.coll] * b.legs[v.coll].scale;
if (u == 0) return 0;
(uint256 p, uint256 t, uint256 room,) = _target($, b, v, r, d);
t += room * MAINTAIN_ROOM_SHARE_WAD / WAD;
(uint256 frame, uint256 pin) = (FLAMMGateLib.frameOf(b, v.coll, v.debt), $.pairs[v.pair].ltvWad);
uint256 own = Math.mulDiv(Math.mulDiv(r, frame, 1e36), pin, WAD);
if (own > d) spend += Math.mulDiv(FLAMMGateLib.requiredPosted(own - d, t, p), u, WAD, Math.Rounding.Up);
// a post at the pin then backs less than its draw adds to the trigger, so past the own room it spends too
if (Math.mulDiv(t, p, WAD) < Math.mulDiv(pin, frame, WAD)) posts = false;
uint256 cap = Math.mulDiv(Math.mulDiv(Math.mulDiv(spare, WAD, u), t, WAD), p, 1e36);
if (cap < most) most = cap;
}
if (posts && spend <= spare) return amount;
return most < FLAMMSettleLib.MIN_DRAW ? 0 : most;
}
/// @notice Posts `assets` of collateral token `t` (custody `have`) at venue `id`; `FLAMMMaintainLib`'s top-up path
/// posts through it too.
function post(FLAMMStore.S storage $, uint8 t, uint16 id, uint256 assets, uint256 have) internal {
FLAMMStore.setHeld($, t, have - assets);
FLAMMGateLib.wake($, uint256(1) << id);
address token = FLAMMStore.tokenOf($, t);
FLAMMStore.grant($, token, assets);
$.router.postCollateral(id, assets);
FLAMMStore.revoke($, token);
}
// ------------------------------------------------------------------ the swap's rotation
/// @notice A swap's rotation, run by `FLAMMSettleLib` out of line: `short` of the output, which backs the owed
/// token `t` at `rotOut` = (y -> t), released from that pair's venues in their order (a venue that refuses
/// repays passed over), each venue `take` against a repay of its proportional share of the debt plus the
/// margin (the whole debt where it releases the whole collateral, and at a venue that may hold a partial
/// repay short, the whole debt or nothing: {_rotationLeg}); the repays' sum, at least
/// `FLAMMSettleLib.MIN_DRAW`, drawn at `rotIn` = (x -> t) by `fund`, which posts up to `heldX` of the
/// input's custody at the pin and spends the pool's own supply of `t` first; each venue repaid by
/// `repay(id)` (never the token-keyed cascade, which would repay the new draw first in the pool's order);
/// then each released in proportion against its repay's snapshot. Returns what it released (`got`), what it
/// posted of the input (`spentX`) and what it left of `t` in custody (`heldT`: the draw's floor past the
/// repays, and what a venue returned of its repay, which net `t`'s debt). The settlement refuses a rotation
/// whose release would pass what the frames posting the output spare over their venues' triggers
/// (`frameBound`, `RoomExhausted`), before it draws or repays; the draw at the input's pair
/// is not bound.
function rotate(uint8 rotIn, uint8 rotOut, address tokenX, uint256 heldX, uint256 short, uint256[] memory usd)
public
returns (uint256 got, uint256 spentX, uint256 heldT)
{
FLAMMStore.S storage $ = FLAMMStore.s();
IMMRouter r = $.router;
// the plan's verdicts on the venues, where this swap's plan took them (`FLAMMSettleLib.VERDICTS`)
(uint256[] memory pre, uint256[] memory rep, uint256 need, uint256 draw) =
_rotationSize(rotOut, short, FLAMMSettleLib.verdictsOf());
// The draw: `t` stays owed, so the drawn set does not grow; the input's token joins the backing set. On a
// cheap-lane pool the pair's proof goes first (`FLAMMStore.S.pairsFree`).
FLAMMGateLib.wake($, $.pairs[rotIn].venues);
if ($.swapBits & FLAMMStore.SWAP_LANE != 0) FLAMMGateLib.drawAt($, rotIn);
address tokenT = FLAMMStore.tokenOf($, $.pairs[rotOut].debt);
(uint256 bt, uint256 bx) = (FLAMMStore.balanceOfThis(tokenT), FLAMMStore.balanceOfThis(tokenX));
FLAMMStore.approveRouter($, tokenX, heldX);
r.fund(rotIn, draw, address(this), heldX, usd);
FLAMMStore.approveRouter($, tokenX, 0);
spentX = bx - FLAMMStore.balanceOfThis(tokenX);
FLAMMStore.approveRouter($, tokenT, need);
for (uint256 i; i < rep.length; ++i) {
if (rep[i] != 0) r.repay(uint16(i), rep[i]);
}
FLAMMStore.revoke($, tokenT);
heldT = FLAMMStore.balanceOfThis(tokenT) - bt;
got = FLAMMSettleLib.releaseRepaid($, short, pre, usd);
}
/// @notice What {rotate} draws at its input's pair to release `short` from `rotOut`: the sum of its repays, at
/// least `FLAMMSettleLib.MIN_DRAW`, out of line for the quote, which checks the Router can fund it
/// (`FLAMMPairQuoteLib`).
function rotationNeed(uint8 rotOut, uint256 short) public view returns (uint256 draw) {
(,,, draw) = _rotationSize(rotOut, short, 0);
}
/// @dev Per venue of `rotOut`, the release `take` (at most its recognized collateral, and at venues sharing one
/// reserve's cash within the cash they leave for releases, `FLAMMSharedLib.releaseRoom`, where a release
/// redeems a whole unit at least: none while the room left is under one unit's payout, each taking at least
/// that payout of it, as `FLAMMLawLib.rotationCapacity` counts them) and its repay: its proportional share of
/// the debt plus the margin, the whole debt where the whole collateral leaves; each venue's (debt, collateral)
/// before, which the releases are proven against; the repays' sum; and the draw, that sum floored at
/// `FLAMMSettleLib.MIN_DRAW` (a draw of a few units fails the lender's floored health check, as a payout's
/// does). It reads the pool's storage itself, so its two callers share one copy. `verdicts`: the swap's plan's
/// on the venues (`FLAMMSettleLib.VERDICTS`), zero for a quote, which asks each venue.
function _rotationSize(uint8 rotOut, uint256 short, uint256 verdicts)
private
view
returns (uint256[] memory pre, uint256[] memory rep, uint256 need, uint256 draw)
{
FLAMMStore.S storage $ = FLAMMStore.s();
uint256 mask = $.pairs[rotOut].venues;
uint256 n = FLAMMSettleLib.span(mask);
(pre, rep) = (new uint256[](2 * n), new uint256[](n));
// the venues sharing one reserve's cash release within the cash they leave for releases, a unit at least each;
// with none live the room is unbounded with no unit, as `FLAMMSharedLib.releaseRoom` answers there, so it is
// asked only where one is
uint256 room = type(uint256).max;
uint256 unit;
if ($.sharedVenues & ~uint256($.retiredVenues) != 0) (room, unit) = FLAMMSharedLib.releaseRoom(rotOut);
for (uint256 i; mask >> i != 0 && short != 0; ++i) {
if ((mask >> i) & 1 == 0) continue;
bool sh = ($.sharedVenues >> i) & 1 != 0;
uint256 left = !sh ? short : room < unit ? 0 : room < short ? room : short;
uint256 take;
(pre[2 * i], pre[2 * i + 1], rep[i], take) = _rotationLeg($, uint16(i), left, verdicts >> i);
if (sh && take != 0) room -= take > unit ? take : unit;
need += rep[i];
// a venue repaid whole may release past the short
short = take < short ? short - take : 0;
}
draw = need != 0 && need < FLAMMSettleLib.MIN_DRAW ? FLAMMSettleLib.MIN_DRAW : need;
}
/// @dev Venue `id`'s part of a rotation releasing `left` more: its debt and collateral, its repay and its take, of
/// what it can release now ({FLAMMGateLib.releasableOf}); none where it refuses repays
/// ({FLAMMGateLib.repayRefused}) or is past its threshold at its own oracle, where the market refuses the
/// release. A venue whose kind may hold a partial repay short (`FLAMMStore.S.heldRepayVenues`) is repaid whole
/// where it can release all its collateral now and shares no reserve's cash, its take all of it, and is passed
/// over otherwise (`FLAMMLawLib.rotationCapacity` sizes it alike). `verdict`: the swap's plan's on this
/// venue, taken in place of asking it again: bit 0 where it found the venue taking repays and healthy, bit 128
/// where it found it refusing or past its threshold; neither, and the venue is asked.
function _rotationLeg(FLAMMStore.S storage $, uint16 id, uint256 left, uint256 verdict)
private
view
returns (uint256 d, uint256 c, uint256 rp, uint256 take)
{
uint256 rec;
IMMRouter r = $.router;
(c, rec,,, d) = r.venuePosition(address(this), id);
if (d == 0 || rec == 0) return (d, c, 0, 0);
if (
verdict & 1 == 0
&& ((verdict >> 128) & 1 != 0 || FLAMMGateLib.repayRefused($, id) || !r.venueHealthy(address(this), id))
) return (d, c, 0, 0);
uint256 cap = FLAMMGateLib.releasableOf($, id, rec);
if (($.heldRepayVenues >> id) & 1 != 0) {
if (cap < rec || ($.sharedVenues >> id) & 1 != 0) return (d, c, 0, 0);
return (d, c, d, rec);
}
take = left < cap ? left : cap;
rp = take == rec ? d : Math.mulDiv(take, d, rec, Math.Rounding.Up) + FLAMMSettleLib.REPAY_MARGIN;
if (rp > d) rp = d;
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {
"src/core/mm/MMRouterLib.sol": {
"MMRouterLib": "0x95b386d242c061ab2551a0d294c94dfe3948ef2c"
},
"src/core/flamm/FLAMMLane.sol": {
"FLAMMLane": "0x5d81d4a7cfd40c3dfe9e009212545608be90de37"
},
"src/core/flamm/FLAMMRoute.sol": {
"FLAMMRoute": "0xb1ffeae12c53f876aa0e495e9c00c829f47fb0fe"
},
"src/periphery/FLAMMMaxima.sol": {
"FLAMMMaxima": "0x68546ce65986354c5394e4bc2f28027ef490a91b"
},
"src/core/flamm/FLAMMLawLib.sol": {
"FLAMMLawLib": "0xf55c5807b6fbe5555443fd6ddbbd52079849cf45"
},
"src/core/flamm/FLAMMOpsLib.sol": {
"FLAMMOpsLib": "0x0be7fdb3d611b05df90a61778a644654735ecc47"
},
"src/core/mm/AaveV3ReadsLib.sol": {
"AaveV3ReadsLib": "0xa5db415d1af2158dd0a4a3c9c1eada277472803e"
},
"src/core/flamm/FLAMMFlowLib.sol": {
"FLAMMFlowLib": "0x27957f4ddf818de39a1c9dba0bf273a5994cfb77"
},
"src/core/flamm/FLAMMGateLib.sol": {
"FLAMMGateLib": "0x3a05779218510235badcbddcdd78732a16434368"
},
"src/core/flamm/FLAMMKeptLib.sol": {
"FLAMMKeptLib": "0x70cace9076ac8dd6a691ced2f9aa62a5c360bee4"
},
"src/core/mm/CTokenMarketLib.sol": {
"CTokenMarketLib": "0x60e4ab6b6ba72325c58924ee7753b14b37314010"
},
"src/core/flamm/FLAMMAdmitLib.sol": {
"FLAMMAdmitLib": "0x0b107b1f0c64f3716554ccc83b53e492e51ce950"
},
"src/core/flamm/FLAMMBlindLib.sol": {
"FLAMMBlindLib": "0x634d5a14c42fb5bec82a7aea32bf636a8d298fcd"
},
"src/core/flamm/FLAMMClaimLib.sol": {
"FLAMMClaimLib": "0x5dc3bb30c60390ce9522b7e3ca315dd334aa7e91"
},
"src/core/flamm/FLAMMFenceLib.sol": {
"FLAMMFenceLib": "0x9dbba0cbd9d7883f4eedd1c8e08780fac4798f1a"
},
"src/core/flamm/FLAMMFloatLib.sol": {
"FLAMMFloatLib": "0x6b2b25ebba12e78afea697b9ac6d2167a6518935"
},
"src/core/flamm/FLAMMQuoteLib.sol": {
"FLAMMQuoteLib": "0x99de54a108c64ebe23ac7766901c199a91929869"
},
"src/core/flamm/FLAMMTopUpLib.sol": {
"FLAMMTopUpLib": "0xe4be161081d1c9aa91951ca347cc99da35cfac2e"
},
"src/core/mm/CTokenRewardsLib.sol": {
"CTokenRewardsLib": "0x93ab647215a9f9f1050302a76506afcbc0262861"
},
"src/core/mm/MMRouterAdminLib.sol": {
"MMRouterAdminLib": "0x6abb06b1e9cba80888992d366913bb9b7760ea7e"
},
"src/core/flamm/FLAMMPolicyLib.sol": {
"FLAMMPolicyLib": "0x3858e2202cebcb6f12f36a596260dd2ed8f91f06"
},
"src/core/flamm/FLAMMSettleLib.sol": {
"FLAMMSettleLib": "0x4551cddb1de95f5452f6a0f836e047e01833b301"
},
"src/core/flamm/FLAMMSharedLib.sol": {
"FLAMMSharedLib": "0xb852d9cbdda85cbed7da0885bca2714ba1b71005"
},
"src/periphery/FLAMMExitMaxima.sol": {
"FLAMMExitMaxima": "0x6a6a3ff1e834dbbf07dee472e07d1ca977798659"
},
"src/hooks/everlong/LeverageLib.sol": {
"LeverageLib": "0x80396f9f894cc3060dfaa7468c4f576e8b16d055"
},
"src/core/flamm/FLAMMMaintainLib.sol": {
"FLAMMMaintainLib": "0xaa5434e13eb54f37c577229efc981cceceb56417"
},
"src/core/flamm/FLAMMPairQuoteLib.sol": {
"FLAMMPairQuoteLib": "0x3bc57bc05cc9dd1fe18106add8ffc060882055dd"
},
"src/hooks/everlong/EverlongOpsLib.sol": {
"EverlongOpsLib": "0xf6d56f4ed6a7c441fd96c53a327026bac19dfeef"
}
},
"optimizer": {
"runs": 100,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.