Verified contractExactUNLICENSED
MMRouter
Address0xf944e5466601991a8a5dbe9fb72be3e9fd9d8fcd
- 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,540
- Creation transaction
- 0xc86c4ed061…cabb72e8d4
- 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
18 files
- src/core/mm/MMRouter.solmain24.93 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
- src/core/mm/MMRouterAdminLib.sol24.07 KB
- src/core/mm/MMRouterLib.sol72.71 KB
- src/core/mm/VenueReads.sol2.05 KB
- src/interfaces/core/flamm/IFLAMM.sol52.68 KB
- src/interfaces/core/flamm/IFLAMMHooks.sol8.36 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/libraries/Constants.sol2.11 KB
- src/libraries/ReentrancyGuardLib.sol2.52 KB
- src/libraries/SafeTransferLib.sol5.11 KB
src/core/mm/MMRouter.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 {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {IMMRouter, NO_VENUE_LLTV, WAD, VENUE_FENCED} from "src/interfaces/core/mm/IMMRouter.sol";
import {IFinancingAccount} from "src/interfaces/core/mm/IFinancingAccount.sol";
import {IFLAMM} from "src/interfaces/core/flamm/IFLAMM.sol";
import {NonReentrant, ReentrancyGuardLib} from "src/libraries/ReentrancyGuardLib.sol";
import {MMRouterLib} from "src/core/mm/MMRouterLib.sol";
import {MMRouterAdminLib} from "src/core/mm/MMRouterAdminLib.sol";
/// @notice The shared money-market router. It never holds a token: every leg settles between the pool and its own
/// accounts, a pair's at each kind or a frame's its pool shares among pairs at a kind (`FRAME_VENUE`), each
/// pinned to its deployer's CREATE2 address for its bindings. A recognized position is `min(actual, managed)`.
contract MMRouter is IMMRouter, NonReentrant {
/// @notice The Factory that deployed this Router: the one caller of `registerPool`, and the registry of each
/// kind's deployer.
address public immutable factory;
/// @notice The protocol owner's address on chain (`IMMRouter`): the one caller of `setGlobalPaused`, and where
/// every account sends its rewards.
address public immutable protocolSafe;
/// @notice Whether the global pause stands: the legs that add credit risk stop, the legs that unwind stay open
/// (`setGlobalPaused`).
bool public globalPaused;
/// @dev Each registered pool's record.
mapping(address pool => MMRouterLib.PoolRecord) internal _pools;
/// @dev Every account the Router deployed or found for a pool, keyed back to that pool.
mapping(address account => address pool) internal _poolOf;
/// @param protocolSafe_ The protocol owner's address on chain, never zero. The deployer becomes `factory`.
constructor(address protocolSafe_) {
if (protocolSafe_ == address(0)) revert InvalidConfig();
factory = msg.sender;
protocolSafe = protocolSafe_;
}
// ------------------------------------------------------------------ factory / protocol
/// @inheritdoc IMMRouter
function registerPool(address pool, address poolAsset) external nonReentrant {
if (msg.sender != factory) revert NotFactory();
MMRouterLib.PoolRecord storage p = _pools[pool];
if (p.poolAsset != address(0)) revert AlreadyRegistered();
IFLAMM alm = IFLAMM(pool);
if (alm.factory() != factory || alm.router() != address(this) || alm.asset() != poolAsset) revert PoolBindingMismatch();
(p.poolAsset, p.maxDrawnTokens) = (poolAsset, 1);
emit PoolRegistered(pool, poolAsset);
MMRouterAdminLib.addToken(p, pool, poolAsset);
}
/// @inheritdoc IMMRouter
function setGlobalPaused(bool paused) external {
if (msg.sender != protocolSafe) revert NotProtocolSafe();
globalPaused = paused;
emit GlobalPauseSet(paused);
}
// ------------------------------------------------------------------ pool-scoped token and pair set
/// @inheritdoc IMMRouter
function addToken(address token_) external nonReentrant returns (uint8 idx) {
return MMRouterAdminLib.addToken(_pool(), msg.sender, token_);
}
/// @inheritdoc IMMRouter
function setTokenSupplyCap(uint8 idx, uint128 supplyCap) external nonReentrant {
MMRouterLib.Token storage t = MMRouterLib.tokenAt(_pool(), idx);
if (t.retired) revert TokenIsRetired();
(t.supplyCap, t.supplyCapped) = (supplyCap, supplyCap != 0);
emit TokenSupplyCapSet(msg.sender, idx, supplyCap);
}
/// @inheritdoc IMMRouter
function retireToken(uint8 idx) external nonReentrant {
MMRouterAdminLib.retireToken(_pool(), idx);
}
/// @inheritdoc IMMRouter
function addPair(uint8 coll, uint8 debt, uint64 pinLtvWad, uint64 safetyGapWad, uint64 oracleBandWad)
external
nonReentrant
returns (uint8 idx)
{
return MMRouterAdminLib.addPair(_pool(), coll, debt, pinLtvWad, safetyGapWad, oracleBandWad);
}
/// @inheritdoc IMMRouter
function setPairCaps(uint8 pair_, uint128 debtCap, bool borrowEnabled) external nonReentrant {
MMRouterLib.Pair storage pr = MMRouterLib.pairAt(_pool(), pair_);
if (pr.retired) revert PairIsRetired();
(pr.debtCap, pr.debtCapped, pr.borrowEnabled) = (debtCap, debtCap != 0, borrowEnabled);
emit PairCapsSet(msg.sender, pair_, debtCap, borrowEnabled);
}
/// @inheritdoc IMMRouter
/// @dev A retired pair's pin binds nothing: it has no live venue, so a raise reads its bound as one.
function setPin(uint8 pair_, uint64 pinLtvWad) external nonReentrant {
MMRouterLib.PoolRecord storage p = _pool();
MMRouterLib.Pair storage pr = MMRouterLib.pairAt(p, pair_);
if (pinLtvWad == 0) revert InvalidConfig();
if (pinLtvWad >= pr.pinLtvWad) {
uint256 lltv = MMRouterLib.minLltv(p, pair_);
if (uint256(pinLtvWad) + pr.safetyGapWad > (lltv == NO_VENUE_LLTV ? WAD : lltv)) revert InvalidConfig();
}
pr.pinLtvWad = pinLtvWad;
emit PinSet(msg.sender, pair_, pinLtvWad);
}
/// @inheritdoc IMMRouter
function setOracleBand(uint8 pair_, uint64 oracleBandWad) external nonReentrant {
MMRouterLib.pairAt(_pool(), pair_).oracleBandWad = oracleBandWad;
if (oracleBandWad > MMRouterAdminLib.MAX_ORACLE_BAND_WAD) revert InvalidConfig();
emit OracleBandSet(msg.sender, pair_, oracleBandWad);
}
/// @inheritdoc IMMRouter
function retirePair(uint8 pair_) external nonReentrant {
MMRouterAdminLib.retirePair(_pool(), pair_);
}
/// @inheritdoc IMMRouter
function setMaxDrawnTokens(uint8 n) external nonReentrant {
MMRouterLib.PoolRecord storage p = _pool();
if (n == 0 || n >= p.tokenCount) revert InvalidConfig();
p.maxDrawnTokens = n;
emit MaxDrawnTokensSet(msg.sender, n);
}
// ------------------------------------------------------------------ pool-scoped venue configuration
/// @inheritdoc IMMRouter
/// @dev A new kind must meet `IFinancingAccount`'s admission rules; a venue it cannot read stops the pool's flows.
function addVenue(
uint8 kind,
uint8 pair_,
bytes calldata params,
bool borrowEnabled,
bool supplyEnabled,
uint256[] calldata usd
) external nonReentrant returns (uint16 id) {
return MMRouterAdminLib.addVenue(_pool(), _poolOf, factory, kind, pair_, params, borrowEnabled, supplyEnabled, usd);
}
/// @inheritdoc IMMRouter
function setVenueFlags(uint16 id, bool borrowEnabled, bool supplyEnabled) external nonReentrant {
MMRouterLib.PoolRecord storage p = _pool();
MMRouterLib.Venue storage v = MMRouterLib.live(p, id);
if (v.status & VENUE_FENCED != 0 && (borrowEnabled || supplyEnabled)) revert VenueIsFenced();
if (borrowEnabled && !v.borrowEnabled && MMRouterLib.overPinned(p.pairs[v.pair], v)) revert InvalidConfig();
v.borrowEnabled = borrowEnabled;
v.supplyEnabled = supplyEnabled;
emit VenueFlagsSet(msg.sender, id, borrowEnabled, supplyEnabled);
}
/// @inheritdoc IMMRouter
/// @dev Named so that its selector sorts after every selector a flow calls: the dispatcher compares selectors in
/// ascending order, and this cold entry adds no compare to a hot one.
function lockVenue(uint16 id, bool fenced) external nonReentrant {
MMRouterAdminLib.lockVenue(_pool(), id, fenced);
}
/// @inheritdoc IMMRouter
function setVenueCaps(uint16 id, uint128 debtCap, uint128 supplyCap, uint64 maxBorrowRateWad) external nonReentrant {
MMRouterLib.Venue storage v = MMRouterLib.live(_pool(), id);
v.debtCap = debtCap;
v.supplyCap = supplyCap;
v.maxBorrowRateWad = maxBorrowRateWad;
emit VenueCapsSet(msg.sender, id, debtCap, supplyCap, maxBorrowRateWad);
}
/// @inheritdoc IMMRouter
function setPriorities(
uint16[] calldata borrow_,
uint16[] calldata supply_,
uint16[] calldata withdraw_,
uint16[] calldata repay_
) external nonReentrant {
MMRouterAdminLib.setPriorities(_pool(), borrow_, supply_, withdraw_, repay_);
}
/// @inheritdoc IMMRouter
function retireVenue(uint16 id) external nonReentrant {
MMRouterAdminLib.retireVenue(_pool(), id);
}
/// @inheritdoc IMMRouter
function setFundRecheck(bool on) external nonReentrant {
_pool().fundRecheckOff = !on;
emit FundRecheckSet(msg.sender, on);
}
/// @inheritdoc IMMRouter
function syncManaged(uint16 id) external nonReentrant {
MMRouterLib.Venue storage v = MMRouterLib.live(_pool(), id);
(uint256 supplyShares,, uint256 units) = v.account.positionOf(v.id);
if (v.managedCollateralUnits > units) v.managedCollateralUnits = SafeCast.toUint128(units);
if (v.managedSupplyShares > supplyShares) v.managedSupplyShares = SafeCast.toUint128(supplyShares);
}
/// @inheritdoc IMMRouter
function recognizeCollateral(uint16 id, uint256 units) external nonReentrant {
MMRouterLib.Venue storage v = MMRouterLib.live(_pool(), id);
(,, uint256 actual) = v.account.positionOf(v.id);
uint256 next = v.managedCollateralUnits + units;
v.managedCollateralUnits = SafeCast.toUint128(next > actual ? actual : next);
}
// ------------------------------------------------------------------ primitives
/// @inheritdoc IMMRouter
function postCollateral(uint16 id, uint256 assets) external nonReentrant {
MMRouterLib.PoolRecord storage p = _pool();
MMRouterLib.Venue storage v = MMRouterLib.live(p, id);
if (v.status & VENUE_FENCED != 0) revert VenueIsFenced();
if (assets == 0) revert InvalidConfig();
MMRouterLib.pull(MMRouterLib.tokenOf(p, v.coll), address(v.account), assets);
MMRouterLib.mintUnits(v, v.account.supplyCollateral(v.id, assets));
emit CollateralPosted(msg.sender, id, assets);
}
/// @inheritdoc IMMRouter
function withdrawCollateral(uint16 id, uint256 assets, uint256[] calldata usd, bool proportional)
external
nonReentrant
returns (uint256 released)
{
return MMRouterLib.withdrawCollateral(_pool(), id, assets, usd, proportional);
}
/// @inheritdoc IMMRouter
/// @dev A fenced venue's borrow switch is off.
function borrow(uint16 id, uint256 assets, address to, uint256[] calldata usd) external nonReentrant {
MMRouterLib.PoolRecord storage p = _pool();
MMRouterLib.Venue storage v = MMRouterLib.live(p, id);
if (to != msg.sender) revert BadReceiver();
if (assets == 0) revert InvalidConfig();
MMRouterLib.checkPrices(p, usd);
MMRouterLib.Pair storage pr = p.pairs[v.pair];
if (globalPaused) revert GlobalPaused();
if (!v.borrowEnabled || !pr.borrowEnabled) revert VenueDisabled();
(uint256 coll,,, uint256 debt) = v.account.position(v.id);
// An indebted venue's pair owes already, so only a debt-free venue reads the drawn set.
if (debt == 0 && !MMRouterLib.drawable(p, pr, 0)) revert DrawOutsideDrawnSet();
uint256 price = MMRouterLib.priceOf(pr, usd);
if (!MMRouterLib.bandOk(pr, v, price)) revert OracleBand();
MMRouterLib.requireSliceFits(pr, v, debt, coll, assets, price);
if (assets > MMRouterLib.capRoom(p, pr.debtCapped ? pr.debtCap : 0, v.pair, true)) revert DebtCapExceeded();
v.account.borrow(v.id, assets, msg.sender);
emit Borrowed(msg.sender, id, assets, to);
}
/// @inheritdoc IMMRouter
function repay(uint16 id, uint256 assets) external nonReentrant returns (uint256 repaid) {
MMRouterLib.PoolRecord storage p = _pool();
MMRouterLib.Venue storage v = MMRouterLib.venueAt(p, id);
uint256 pay = Math.min(assets, MMRouterLib.snapshotForProportional(v, id));
repaid = MMRouterLib.repayInto(v, MMRouterLib.tokenOf(p, v.debt), pay);
emit Repaid(msg.sender, id, repaid);
}
/// @inheritdoc IMMRouter
/// @dev A fenced venue's supply switch is off.
function supply(uint16 id, uint256 assets) external nonReentrant returns (uint256 shares) {
MMRouterLib.PoolRecord storage p = _pool();
MMRouterLib.Venue storage v = MMRouterLib.live(p, id);
if (assets == 0) revert InvalidConfig();
MMRouterLib.requireSuppliable(v, globalPaused, assets);
MMRouterLib.Token storage t = p.tokens[v.debt];
if (assets > MMRouterLib.capRoom(p, t.supplyCapped ? t.supplyCap : 0, v.debt, false)) revert SupplyCapExceeded();
MMRouterLib.pull(t.token, address(v.account), assets);
shares = v.account.supply(v.id, assets);
MMRouterLib.mintShares(v, shares);
emit Supplied(msg.sender, id, assets);
}
/// @inheritdoc IMMRouter
function withdrawSupplied(uint16 id, uint256 assets, address to) external nonReentrant returns (uint256 withdrawn) {
MMRouterLib.PoolRecord storage p = _pool();
MMRouterLib.Venue storage v = MMRouterLib.venueAt(p, id);
if (to != msg.sender) revert BadReceiver();
withdrawn = MMRouterLib.withdrawSupplied(p, v, assets, msg.sender, true);
emit SuppliedWithdrawn(msg.sender, id, withdrawn, to);
}
/// @inheritdoc IMMRouter
/// @dev The caller's own record: a caller that is no registered pool has no venues, so it accrues nothing. Each
/// account's accrual is caught, so no kind's revert can block the swap that asks for it.
function accrueExcept(uint64 skipVenues, uint8 kept) external nonReentrant {
MMRouterLib.PoolRecord storage p = _pools[msg.sender];
uint256 n = p.venues.length;
for (uint256 i; i < n; ++i) {
MMRouterLib.Venue storage v = p.venues[i];
if (v.status != 0 || ((skipVenues >> i) & 1 != 0 && v.debt != kept)) continue;
try v.account.accrue(v.id) {} catch {}
}
}
// ------------------------------------------------------------------ cascades (bodies in MMRouterLib)
/// @inheritdoc IMMRouter
function fund(uint8 pair_, uint256 assets, address to, uint256 collateralIn, uint256[] calldata usd) external nonReentrant {
if (to != msg.sender) revert BadReceiver();
MMRouterLib.fund(_pool(), globalPaused, pair_, assets, collateralIn, usd);
}
/// @inheritdoc IMMRouter
function repayCascade(uint8 token_, uint256 assets) external nonReentrant returns (uint256 repaid) {
return MMRouterLib.repayCascade(_pool(), token_, assets);
}
/// @inheritdoc IMMRouter
function supplyCascade(uint8 token_, uint256 assets) external nonReentrant returns (uint256 supplied) {
return MMRouterLib.supplyCascade(_pool(), globalPaused, token_, assets);
}
/// @inheritdoc IMMRouter
function withdrawCascade(uint8 token_, uint256 assets, address to) external nonReentrant returns (uint256 withdrawn) {
if (to != msg.sender) revert BadReceiver();
return MMRouterLib.withdrawCascade(_pool(), token_, assets, to);
}
/// @inheritdoc IMMRouter
function reclaim(uint8 token_, uint256 assets, uint256[] calldata usd) external nonReentrant returns (uint256 got) {
got = MMRouterLib.reclaim(_pool(), token_, assets, usd);
if (got != assets) revert InsufficientCollateral(assets - got);
}
/// @inheritdoc IMMRouter
function reclaimBestEffort(uint8 token_, uint256 assets, uint256[] calldata usd) external nonReentrant returns (uint256 got) {
return MMRouterLib.reclaim(_pool(), token_, assets, usd);
}
/// @inheritdoc IMMRouter
function refinanceDebt(uint16 src, uint16 dst, uint256 assets, uint256[] calldata usd) external nonReentrant {
MMRouterLib.refinanceDebt(_pool(), globalPaused, src, dst, assets, usd);
}
/// @inheritdoc IMMRouter
function migrateSupply(uint16 src, uint16 dst, uint256 assets) external nonReentrant {
MMRouterAdminLib.migrateSupply(_pool(), globalPaused, src, dst, assets);
}
// ------------------------------------------------------------------ views
/// @inheritdoc IMMRouter
function tokenCount(address pool) external view returns (uint256) {
return _pools[pool].tokenCount;
}
/// @inheritdoc IMMRouter
function token(address pool, uint8 idx) external view returns (TokenView memory) {
MMRouterLib.Token storage t = MMRouterLib.tokenAt(_pools[pool], idx);
return TokenView(t.token, t.decimals, 10 ** (18 - t.decimals), t.supplyCap, t.retired);
}
/// @inheritdoc IMMRouter
function pairCount(address pool) external view returns (uint256) {
return _pools[pool].pairCount;
}
/// @inheritdoc IMMRouter
function pair(address pool, uint8 idx) external view returns (PairView memory) {
MMRouterLib.Pair storage pr = MMRouterLib.pairAt(_pools[pool], idx);
return PairView(pr.coll, pr.debt, pr.pinLtvWad, pr.safetyGapWad, pr.oracleBandWad, pr.debtCap, pr.borrowEnabled, pr.retired);
}
/// @inheritdoc IMMRouter
function accountOf(address pool, uint8 pair_, uint8 kind) external view returns (address) {
return _pools[pool].pairs[pair_].accounts[kind];
}
/// @inheritdoc IMMRouter
function poolOf(address account) external view returns (address) {
return _poolOf[account];
}
/// @inheritdoc IMMRouter
function venueCount(address pool) external view returns (uint256) {
return _pools[pool].venues.length;
}
/// @inheritdoc IMMRouter
function venue(address pool, uint16 id) external view returns (VenueView memory out) {
MMRouterLib.Venue storage v = MMRouterLib.venueAt(_pools[pool], id);
out = VenueView(
address(v.account),
v.id,
v.kind,
v.pair,
v.coll,
v.debt,
uint64(MMRouterLib.threshold(v)),
v.borrowEnabled,
v.supplyEnabled,
v.status,
v.debtCap,
v.supplyCap,
v.maxBorrowRateWad
);
}
/// @inheritdoc IMMRouter
function priorities(address pool)
external
view
returns (uint16[] memory borrow_, uint16[] memory supply_, uint16[] memory withdraw_, uint16[] memory repay_)
{
MMRouterLib.PoolRecord storage p = _pools[pool];
return (p.borrowOrder, p.supplyOrder, p.withdrawOrder, p.repayOrder);
}
/// @inheritdoc IMMRouter
function maxDrawnTokens(address pool) external view returns (uint8) {
return _pools[pool].maxDrawnTokens;
}
/// @inheritdoc IMMRouter
function drawn(address pool) external view returns (uint16 owed, uint16 backing) {
ReentrancyGuardLib._readGuard();
(uint256 o, uint256 b) = MMRouterLib.sets(_pools[pool], 0);
return (uint16(o), uint16(b));
}
/// @inheritdoc IMMRouter
function venuePosition(address pool, uint16 id)
external
view
returns (uint256 collateral, uint256 recognizedCollateral, uint256 supplied, uint256 recognizedSupplied, uint256 debt)
{
ReentrancyGuardLib._readGuard();
MMRouterLib.Read memory r = MMRouterLib.read(MMRouterLib.venueAt(_pools[pool], id));
return (r.collateral, r.recognizedCollateral, r.supplied, r.recognizedSupplied, r.debt);
}
/// @inheritdoc IMMRouter
/// @dev Here, not in `MMRouterLib`: the pool reads it on every swap, flow and observation, so its answer is encoded
/// once, with no library hop.
function book(address pool, uint64 skipVenues)
external
view
returns (uint256[] memory posted, uint256[] memory supplied, uint256[] memory owed, uint64 emptyVenues)
{
ReentrancyGuardLib._readGuard();
MMRouterLib.PoolRecord storage p = _pools[pool];
uint256 t = p.tokenCount;
(posted, supplied, owed) = (new uint256[](t), new uint256[](t), new uint256[](t));
uint256 n = p.venues.length;
for (uint256 i; i < n; ++i) {
if ((skipVenues >> i) & 1 != 0) continue;
MMRouterLib.Venue storage v = p.venues[i];
if (v.status != 0) continue;
MMRouterLib.Read memory r = MMRouterLib.read(v);
posted[v.coll] += r.recognizedCollateral;
supplied[v.debt] += r.recognizedSupplied;
owed[v.debt] += r.debt;
// Empty on what only the pool's own calls move: no raw debt, no collateral tracker and no recognized
// supply, so a gift, which anyone can post or supply, never decides it, and a venue a lender seized from
// stays read until its tracker goes. Supply cannot be seized, so its recognized part is the pool's own: a
// withdrawal's share dust, worth nothing, leaves the venue empty, and a gift over it is recognized only up
// to that dust.
if (r.debt == 0 && v.managedCollateralUnits == 0 && r.recognizedSupplied == 0) emptyVenues |= uint64(1 << i);
}
}
/// @inheritdoc IMMRouter
function venueHealthy(address pool, uint16 id) external view returns (bool) {
MMRouterLib.Venue storage v = MMRouterLib.venueAt(_pools[pool], id);
return v.account.healthy(v.id);
}
/// @inheritdoc IMMRouter
function venueActions(address pool, uint16 id) external view returns (uint8) {
MMRouterLib.Venue storage v = MMRouterLib.venueAt(_pools[pool], id);
return v.account.actions(v.id);
}
/// @inheritdoc IMMRouter
function minLltv(address pool, uint8 pair_) external view returns (uint256) {
return MMRouterLib.minLltv(_pools[pool], pair_);
}
/// @inheritdoc IMMRouter
function fundingCeiling(
address pool,
uint8 pair_,
uint256 cap,
uint256 collateralIn,
uint256[] calldata usd,
uint16 assumeRepaid
) external view returns (uint256) {
ReentrancyGuardLib._readGuard();
MMRouterLib.PoolRecord storage p = _pools[pool];
if (p.poolAsset == address(0)) return 0;
return cap - MMRouterLib.fundingRest(p, globalPaused, pair_, cap, collateralIn, usd, assumeRepaid);
}
/// @inheritdoc IMMRouter
function fundingCollateral(address pool, uint8 pair_, uint256 assets, uint256 collateralIn, uint256[] calldata usd)
external
view
returns (uint256 posted)
{
ReentrancyGuardLib._readGuard();
MMRouterLib.PoolRecord storage p = _pools[pool];
if (p.poolAsset == address(0)) return 0;
uint256[] memory post = MMRouterLib.buildPlan(p, globalPaused, pair_, assets, collateralIn, usd, 0).post;
for (uint256 i; i < post.length; ++i) {
posted += post[i];
}
}
/// @inheritdoc IMMRouter
function borrowRoom(address pool, uint16 id, uint256 collateralIn, uint256[] calldata usd)
external
view
returns (uint256)
{
ReentrancyGuardLib._readGuard();
return MMRouterAdminLib.borrowRoom(_pools[pool], globalPaused, id, collateralIn, usd);
}
/// @inheritdoc IMMRouter
function supplyRoom(address pool, uint16 id) external view returns (uint256) {
ReentrancyGuardLib._readGuard();
return MMRouterLib.supplyRoomOf(_pools[pool], globalPaused, id);
}
/// @inheritdoc IMMRouter
function reclaimable(address pool, uint8 token_, uint256[] calldata usd) external view returns (uint256) {
ReentrancyGuardLib._readGuard();
return MMRouterLib.reclaimable(_pools[pool], token_, usd);
}
/// @inheritdoc IMMRouter
function venueHealth(address pool, uint16 id, uint256[] calldata usd) external view returns (uint256) {
return MMRouterAdminLib.venueHealth(_pools[pool], id, usd);
}
/// @inheritdoc IMMRouter
function venueCapacity(address pool, uint16 id) external view returns (IFinancingAccount.Capacity memory) {
MMRouterLib.Venue storage v = MMRouterLib.venueAt(_pools[pool], id);
return v.account.capacity(v.id);
}
// ------------------------------------------------------------------ internals
/// @dev The caller's record; `NotRegistered` for a caller that is no registered pool.
function _pool() internal view returns (MMRouterLib.PoolRecord storage p) {
p = _pools[msg.sender];
if (p.poolAsset == address(0)) revert NotRegistered();
}
}
lib/openzeppelin-contracts-compat/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
lib/openzeppelin-contracts-compat/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts-compat/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10**64) {
value /= 10**64;
result += 64;
}
if (value >= 10**32) {
value /= 10**32;
result += 32;
}
if (value >= 10**16) {
value /= 10**16;
result += 16;
}
if (value >= 10**8) {
value /= 10**8;
result += 8;
}
if (value >= 10**4) {
value /= 10**4;
result += 4;
}
if (value >= 10**2) {
value /= 10**2;
result += 2;
}
if (value >= 10**1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
lib/openzeppelin-contracts-compat/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toUint248(uint256 value) internal pure returns (uint248) {
require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toUint240(uint256 value) internal pure returns (uint240) {
require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toUint232(uint256 value) internal pure returns (uint232) {
require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.2._
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toUint216(uint256 value) internal pure returns (uint216) {
require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toUint208(uint256 value) internal pure returns (uint208) {
require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toUint200(uint256 value) internal pure returns (uint200) {
require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toUint192(uint256 value) internal pure returns (uint192) {
require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toUint184(uint256 value) internal pure returns (uint184) {
require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toUint176(uint256 value) internal pure returns (uint176) {
require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toUint168(uint256 value) internal pure returns (uint168) {
require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toUint160(uint256 value) internal pure returns (uint160) {
require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toUint152(uint256 value) internal pure returns (uint152) {
require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toUint144(uint256 value) internal pure returns (uint144) {
require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toUint136(uint256 value) internal pure returns (uint136) {
require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v2.5._
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toUint120(uint256 value) internal pure returns (uint120) {
require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toUint104(uint256 value) internal pure returns (uint104) {
require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.2._
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toUint80(uint256 value) internal pure returns (uint80) {
require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toUint72(uint256 value) internal pure returns (uint72) {
require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v2.5._
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toUint56(uint256 value) internal pure returns (uint56) {
require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toUint48(uint256 value) internal pure returns (uint48) {
require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v2.5._
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toUint24(uint256 value) internal pure returns (uint24) {
require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v2.5._
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v2.5._
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*
* _Available since v3.0._
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.7._
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.7._
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*
* _Available since v3.0._
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
src/core/mm/MMRouterAdminLib.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {
IFinancingAccount,
IFrameAccount,
IActionsOf,
KNOWN_CAPABILITIES,
CAP_SHARED_LIQUIDITY,
CAP_ACTION_GATES,
ALL_ACTIONS
} from "src/interfaces/core/mm/IFinancingAccount.sol";
import {IAccountDeployer, IAccountDeployerRegistry} from "src/interfaces/core/mm/IAccountDeployer.sol";
import "src/interfaces/core/mm/IMMRouter.sol";
import {MMRouterLib} from "src/core/mm/MMRouterLib.sol";
/// @notice The Router's cold bodies, which run by delegatecall against it: the admission and retirement of a pool's
/// tokens, pairs and venues, the deployment of a pair's accounts and of the frame accounts, the priority
/// orders, the migration of supply between venues, and a venue's borrow room and health. None runs on a swap or
/// a flow.
library MMRouterAdminLib {
/// @dev The widest venue-oracle band a pair takes.
uint64 internal constant MAX_ORACLE_BAND_WAD = 0.2e18;
/// @dev Appends `token` to `pool`'s list (`IMMRouter.addToken`); `registerPool` lists the pool asset through it.
/// A listing rule no check here holds: no token with a second entry point (another address that moves the same
/// balances, as an older address forwarding to the token does). The accounts refuse to forward a token whose
/// transfer moves a pair token's balance, but every other check keys a token by its address.
function addToken(MMRouterLib.PoolRecord storage p, address pool, address token) public returns (uint8 idx) {
if (token == address(0)) revert IMMRouter.InvalidConfig();
uint256 n = p.tokenCount;
if (n >= MAX_TOKENS) revert IMMRouter.TooManyTokens();
for (uint256 i; i < n; ++i) {
if (p.tokens[uint8(i)].token == token) revert IMMRouter.DuplicateToken();
}
uint8 decimals = IERC20Metadata(token).decimals();
if (decimals > 18) revert IMMRouter.InvalidConfig();
idx = uint8(n);
(p.tokens[idx].token, p.tokens[idx].decimals) = (token, decimals);
p.tokenCount = idx + 1;
emit IMMRouter.TokenAdded(pool, idx, token);
}
/// @dev Terminal (`IMMRouter.retireToken`): never the pool asset, and only once no live pair names the token.
function retireToken(MMRouterLib.PoolRecord storage p, uint8 idx) public {
if (idx == 0) revert IMMRouter.InvalidConfig();
MMRouterLib.Token storage t = MMRouterLib.tokenAt(p, idx);
if (t.retired) revert IMMRouter.TokenIsRetired();
uint256 n = p.pairCount;
for (uint256 i; i < n; ++i) {
MMRouterLib.Pair storage pr = p.pairs[uint8(i)];
if ((pr.coll == idx || pr.debt == idx) && !pr.retired) revert IMMRouter.TokenInUse();
}
t.retired = true;
emit IMMRouter.TokenRetired(msg.sender, idx);
}
/// @dev `IMMRouter.lockVenue`: a fence takes the venue out of the four priority orders, the others keeping their
/// order, with both switches off, so no cascade or plan reaches it; the lift puts it back in each, last, its
/// switches still off, where the drawn sets stay disjoint.
function lockVenue(MMRouterLib.PoolRecord storage p, uint16 id, bool fenced) public {
MMRouterLib.Venue storage v = MMRouterLib.live(p, id);
if (fenced == (v.status & VENUE_FENCED != 0)) revert IMMRouter.InvalidConfig();
if (fenced) {
if (v.borrowEnabled || v.supplyEnabled) emit IMMRouter.VenueFlagsSet(msg.sender, id, false, false);
(v.status, v.borrowEnabled, v.supplyEnabled) = (VENUE_FENCED, false, false);
_leaveOrders(p, id);
} else {
v.status = 0;
_joinOrders(p, id);
(uint256 owed, uint256 backing) = MMRouterLib.sets(p, 0);
if (owed & backing != 0) revert IMMRouter.DrawOutsideDrawnSet();
}
emit IMMRouter.VenueFenced(msg.sender, id, fenced);
emit IMMRouter.PrioritiesSet(msg.sender, p.borrowOrder, p.supplyOrder, p.withdrawOrder, p.repayOrder);
}
/// @dev Appends a pair (`IMMRouter.addPair`), born with its borrowing off. A pair added once, retired or not, is
/// refused again: its accounts' CREATE2 addresses are taken.
function addPair(
MMRouterLib.PoolRecord storage p,
uint8 coll,
uint8 debt,
uint64 pinLtvWad,
uint64 safetyGapWad,
uint64 oracleBandWad
) public returns (uint8 idx) {
MMRouterLib.Token storage c = MMRouterLib.tokenAt(p, coll);
MMRouterLib.Token storage d = MMRouterLib.tokenAt(p, debt);
if (c.retired || d.retired) revert IMMRouter.TokenIsRetired();
if (coll == debt || oracleBandWad > MAX_ORACLE_BAND_WAD) revert IMMRouter.InvalidConfig();
if (pinLtvWad == 0 || uint256(pinLtvWad) + safetyGapWad >= WAD) revert IMMRouter.InvalidConfig();
uint256 n = p.pairCount;
if (n >= MAX_PAIRS) revert IMMRouter.TooManyPairs();
for (uint256 i; i < n; ++i) {
if (p.pairs[uint8(i)].coll == coll && p.pairs[uint8(i)].debt == debt) revert IMMRouter.DuplicatePair();
}
idx = uint8(n);
MMRouterLib.Pair storage pr = p.pairs[idx];
(pr.coll, pr.debt, pr.collDecimals, pr.debtDecimals) = (coll, debt, c.decimals, d.decimals);
(pr.pinLtvWad, pr.safetyGapWad, pr.oracleBandWad) = (pinLtvWad, safetyGapWad, oracleBandWad);
p.pairCount = idx + 1;
emit IMMRouter.PairAdded(msg.sender, idx, coll, debt, pinLtvWad, safetyGapWad, oracleBandWad);
}
/// @dev Terminal (`IMMRouter.retirePair`): every venue of the pair retired and holding nothing.
function retirePair(MMRouterLib.PoolRecord storage p, uint8 idx) public {
MMRouterLib.Pair storage pr = MMRouterLib.pairAt(p, idx);
if (pr.retired) revert IMMRouter.PairIsRetired();
uint256 n = p.venues.length;
for (uint256 i; i < n; ++i) {
MMRouterLib.Venue storage v = p.venues[i];
if (v.pair == idx && (v.status & VENUE_RETIRED == 0 || !MMRouterLib.holdsNothing(v))) {
revert IMMRouter.PairNotEmpty();
}
}
(pr.retired, pr.borrowEnabled) = (true, false);
emit IMMRouter.PairRetired(msg.sender, idx);
}
/// @dev Finds, or deploys, the account that holds a venue of `kind` for pair `pairIdx` under the kind's deployer of
/// the day, the Factory's registered one, and pins it: it must sit at the CREATE2 address of that deployer,
/// this Router's salt and the init code the deployer advertises for its bindings, and the bindings must read
/// back as requested. The pair's own account (`frame` zero) is bound to the pair's collateral and debt tokens;
/// a frame's account (`frame` nonzero) is bound to (zero, `frame`) and is no pair's. The first venue there
/// deploys it (`AccountDeployed`), and every later one finds it at that address, a frame's by any pair's
/// venue, so a deployer bound later at the kind opens new accounts, the pair's own and each frame's, and no
/// venue lands in the replaced code after. The pair's first own account at the kind stays its record
/// (`IMMRouter.accountOf`). `poolOf`: every account the Router deployed, keyed back to its pool.
function deployAccount(
MMRouterLib.PoolRecord storage p,
mapping(address => address) storage poolOf,
address factory,
uint8 kind,
uint8 pairIdx,
address frame
) public returns (address account) {
MMRouterLib.Pair storage pr = p.pairs[pairIdx];
IAccountDeployer deployer = IAccountDeployer(IAccountDeployerRegistry(factory).accountDeployerOf(kind));
if (address(deployer) == address(0)) revert IMMRouter.KindUnknown();
(address coll, address debt) = frame == address(0)
? (MMRouterLib.tokenOf(p, pr.coll), MMRouterLib.tokenOf(p, pr.debt))
: (address(0), frame);
bytes32 salt = keccak256(abi.encode(address(this), msg.sender, coll, debt));
bytes32 initHash = deployer.initCodeHash(address(this), msg.sender, coll, debt);
address pinned =
address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(deployer), salt, initHash)))));
bool fresh = pinned.code.length == 0;
account = fresh ? deployer.deploy(msg.sender, coll, debt) : pinned;
IFinancingAccount a = IFinancingAccount(account);
if (
account != pinned || account.code.length == 0 || a.ROUTER() != address(this) || a.POOL() != msg.sender
|| a.COLLATERAL_ASSET() != coll || a.LOAN_ASSET() != debt || a.KIND() != kind
) revert IMMRouter.AccountCodeMismatch();
if (frame == address(0) && pr.accounts[kind] == address(0)) pr.accounts[kind] = account;
poolOf[account] = msg.sender;
if (fresh) emit IMMRouter.AccountDeployed(msg.sender, pairIdx, kind, account);
}
/// @dev `IMMRouter.addVenue`: the venue registers at the account its params name, under the kind's deployer of the
/// day ({deployAccount}), and copies the pair and its two tokens. Plain params name the pair's own account at
/// the kind. Params that open with `FRAME_VENUE` (`abi.encode(FRAME_VENUE, frame, params)`) name the frame's
/// account at the kind, a zero frame the pair's own; a frame's account is bound to no pair, so it takes the
/// pair's two tokens before the kind's params (`abi.encode(collateral, debt, params)`) and must name them back
/// for the venue's id (`IFrameAccount.tokensOf`), so an id there names one pair. A pair may hold venues at
/// several accounts of one kind at once (its own, its own under a later deployer, frames'): it changes its
/// mode, its frame or its code by a venue at the other account and a move of its position there
/// (`refinanceDebt`, `migrateSupply`).
function addVenue(
MMRouterLib.PoolRecord storage p,
mapping(address => address) storage poolOf,
address factory,
uint8 kind,
uint8 pairIdx,
bytes calldata params,
bool borrowEnabled,
bool supplyEnabled,
uint256[] calldata usd
) public returns (uint16 id) {
MMRouterLib.checkPrices(p, usd);
MMRouterLib.Pair storage pr = MMRouterLib.pairAt(p, pairIdx);
if (pr.retired) revert IMMRouter.PairIsRetired();
address frame;
bytes memory reg = params;
if (params.length >= 32 && bytes32(params[:32]) == FRAME_VENUE) {
(, frame, reg) = abi.decode(params, (bytes32, address, bytes));
}
address account = deployAccount(p, poolOf, factory, kind, pairIdx, frame);
(address coll, address debt) = (MMRouterLib.tokenOf(p, pr.coll), MMRouterLib.tokenOf(p, pr.debt));
if (frame != address(0)) reg = abi.encode(coll, debt, reg);
(bytes32 venueId, uint64 lltv) = IFinancingAccount(account).registerVenue(reg);
if (frame != address(0)) {
(address c, address d) = IFrameAccount(account).tokensOf(venueId);
if (c != coll || d != debt) revert IMMRouter.VenueMismatch();
}
// The kind's capabilities are read once, here, and refused after the threshold check below.
uint256 declared = IFinancingAccount(account).capabilities();
uint256 n = p.venues.length;
uint256 slot = n;
uint256 same = n; // a retired slot that already names this position: the market returns to it
bool unlike; // a live venue of the kind tells its reserve otherwise
for (uint256 i; i < n; ++i) {
MMRouterLib.Venue storage w = p.venues[i];
bool named = address(w.account) == account && w.id == venueId;
// A frame's venues back each other's debt at the lender: none joins while one is fenced.
if (frame != address(0) && address(w.account) == account && w.status & VENUE_FENCED != 0) {
revert IMMRouter.VenueIsFenced();
}
if (w.status & VENUE_RETIRED != 0) {
if (named) same = i;
else if (slot == n) slot = i;
} else if (named) {
revert IMMRouter.DuplicateVenue();
} else if (w.kind == kind && (uint256(w.capabilities) ^ declared) & CAP_SHARED_LIQUIDITY != 0) {
unlike = true;
}
}
if (same != n) slot = same;
if (slot == n && n >= MAX_VENUES) revert IMMRouter.TooManyVenues();
// A venue admitted with its borrowing off may sit under the pin plus the gap: it binds no pin (`minLltv`), and
// no path lends from it while it is over-pinned (the switch, the borrow primitive, the plan's slices, a
// refinance onto it).
if (borrowEnabled && lltv < uint256(pr.pinLtvWad) + pr.safetyGapWad) revert IMMRouter.InvalidConfig();
// A capability outside `KNOWN_CAPABILITIES` (every bit the Router admits) is refused
// (`UnknownCapability`), as nothing would honour it. One kind number is one lender, whose reserve every account
// of the kind shares or none does (`IFinancingAccount` ADMISSION): a plan nets its posts across the accounts
// only where their venues declare `CAP_SHARED_LIQUIDITY`, so a venue that declares it otherwise than the
// pool's live venues of its kind, as a later deployer at the number might, is refused (`InvalidConfig`).
if (declared & ~KNOWN_CAPABILITIES != 0) revert IMMRouter.UnknownCapability();
if (unlike) revert IMMRouter.InvalidConfig();
id = uint16(slot);
// A retired slot is reused before the array grows, the one naming this position first; the caps and the rate
// ceiling were zeroed by `retireVenue`, and both managed trackers start at zero here, whatever wrote the slot
// since, as they count the units and shares of this venue's own position alone.
MMRouterLib.Venue storage v = slot == n ? p.venues.push() : p.venues[slot];
(v.managedCollateralUnits, v.managedSupplyShares) = (0, 0);
(v.status, v.account, v.id, v.kind) = (0, IFinancingAccount(account), venueId, kind);
(v.pair, v.coll, v.debt, v.lltvWad) = (pairIdx, pr.coll, pr.debt, lltv);
v.capabilities = uint16(declared);
// A gated venue whose account answers `IActionsOf` as its `actions` has its gate read one action at a time.
v.actionsOf = declared & CAP_ACTION_GATES != 0 && _answersActionsOf(account, venueId);
(v.borrowEnabled, v.supplyEnabled) = (borrowEnabled, supplyEnabled);
// A venue admitted with its borrowing off may come unpriced: no path lends from it without its own band check
// at a checked price (the borrow primitive, the plan's slices, a refinance onto it).
uint256 price = MMRouterLib.priceOf(pr, usd);
if ((borrowEnabled || price != 0) && !MMRouterLib.bandOk(pr, v, price)) revert IMMRouter.OracleBand();
_joinOrders(p, id);
emit IMMRouter.VenueAdded(msg.sender, id, kind, pairIdx, venueId);
emit IMMRouter.VenueFlagsSet(msg.sender, id, borrowEnabled, supplyEnabled);
}
/// @dev `IMMRouter.setPriorities`: each of the four orders must list every live, unfenced venue once
/// ({_checkOrder}).
function setPriorities(
MMRouterLib.PoolRecord storage p,
uint16[] calldata borrow_,
uint16[] calldata supply_,
uint16[] calldata withdraw_,
uint16[] calldata repay_
) public {
_checkOrder(p, borrow_);
_checkOrder(p, supply_);
_checkOrder(p, withdraw_);
_checkOrder(p, repay_);
p.borrowOrder = borrow_;
p.supplyOrder = supply_;
p.withdrawOrder = withdraw_;
p.repayOrder = repay_;
emit IMMRouter.PrioritiesSet(msg.sender, borrow_, supply_, withdraw_, repay_);
}
/// @dev Turns both switches off and zeroes caps, rate ceiling and managed trackers: nothing of the old market
/// stays on record. A fenced venue retires out of its fence (`VenueFenced`), and is in no order to leave.
function retireVenue(MMRouterLib.PoolRecord storage p, uint16 id) public {
MMRouterLib.Venue storage v = MMRouterLib.live(p, id);
if (!MMRouterLib.holdsNothing(v)) revert IMMRouter.VenueNotEmpty();
if (v.status & VENUE_FENCED != 0) emit IMMRouter.VenueFenced(msg.sender, id, false);
v.status = VENUE_RETIRED;
v.borrowEnabled = false;
v.supplyEnabled = false;
v.debtCap = 0;
v.supplyCap = 0;
v.maxBorrowRateWad = 0;
v.managedCollateralUnits = 0;
v.managedSupplyShares = 0;
_leaveOrders(p, id);
emit IMMRouter.VenueRetired(msg.sender, id);
}
/// @dev Reverts `BadPriorities` unless `order` lists every live, unfenced venue exactly once.
function _checkOrder(MMRouterLib.PoolRecord storage p, uint16[] calldata order) private view {
uint256 seen;
for (uint256 i; i < order.length; ++i) {
uint16 id = order[i];
if (id >= p.venues.length || p.venues[id].status != 0 || seen & (1 << id) != 0) revert IMMRouter.BadPriorities();
seen |= 1 << id;
}
uint256 expected;
for (uint256 i; i < p.venues.length; ++i) {
if (p.venues[i].status == 0) expected |= 1 << i;
}
if (seen != expected) revert IMMRouter.BadPriorities();
}
/// @dev Whether `account` answers `IActionsOf.actionsOf` for venue `id`, and as its `actions`: a call that reverts,
/// answers no word or another value reads as none, so the Router reads the venue's gate through `actions`.
function _answersActionsOf(address account, bytes32 id) private view returns (bool) {
(bool ok, bytes memory r) = account.staticcall(abi.encodeCall(IActionsOf.actionsOf, (id, ALL_ACTIONS)));
return ok && r.length == 32 && abi.decode(r, (uint256)) == IFinancingAccount(account).actions(id);
}
/// @dev Puts `id` last in each of the four priority orders.
function _joinOrders(MMRouterLib.PoolRecord storage p, uint16 id) private {
p.borrowOrder.push(id);
p.supplyOrder.push(id);
p.withdrawOrder.push(id);
p.repayOrder.push(id);
}
/// @dev Takes `id` out of each of the four priority orders, the others keeping their order.
function _leaveOrders(MMRouterLib.PoolRecord storage p, uint16 id) private {
_drop(p.borrowOrder, id);
_drop(p.supplyOrder, id);
_drop(p.withdrawOrder, id);
_drop(p.repayOrder, id);
}
/// @dev Removes `id` from `order`, the others keeping their order.
function _drop(uint16[] storage order, uint16 id) private {
uint256 n = order.length;
for (uint256 i; i < n; ++i) {
if (order[i] != id) continue;
for (uint256 j = i + 1; j < n; ++j) {
order[j - 1] = order[j];
}
order.pop();
return;
}
}
/// @dev Between two venues lending the same token, of one pair or two. The destination's supply may round the move
/// down by {MMRouterLib.REFINANCE_SLACK}, or, at a destination whose one share is worth more (a Compound-style
/// exchange rate), by that share's worth and one, which bounds a supply's rounding (`IFinancingAccount`
/// ADMISSION), but never by more than {MMRouterLib.MIGRATION_LOSS_DIVISOR}'s part of what it moves nor of one
/// whole token, so no share price, however it was raised (a donation, or mints too small to earn a share),
/// takes more from a move, or from many. The share and the token's decimals are read only past the fixed
/// slack, and a read of the share that reverts or runs out of gas refuses the move. Only the destination is
/// measured: what the source charges to pay `withdrawn` (a redemption fee) is not.
function migrateSupply(MMRouterLib.PoolRecord storage p, bool paused, uint16 src, uint16 dst, uint256 assets)
public
{
if (paused) revert IMMRouter.GlobalPaused();
if (src == dst) revert IMMRouter.VenueMismatch();
MMRouterLib.Venue storage vs = MMRouterLib.venueAt(p, src);
MMRouterLib.Venue storage vd = MMRouterLib.live(p, dst);
if ((vs.status | vd.status) & VENUE_FENCED != 0) revert IMMRouter.VenueIsFenced();
if (vs.debt != vd.debt) revert IMMRouter.VenueMismatch();
if (assets == 0) revert IMMRouter.NothingToMove();
uint256 before = MMRouterLib.recognizedSupplied(vd);
// Bounded by recognized supply, as any withdrawal: moving an unrecognized gift would credit it to `dst`.
uint256 withdrawn = MMRouterLib.withdrawSupplied(p, vs, assets, address(vd.account), false);
if (withdrawn == 0) revert IMMRouter.NothingToMove();
MMRouterLib.requireSuppliable(vd, paused, withdrawn);
MMRouterLib.mintShares(vd, vd.account.supply(vd.id, withdrawn));
uint256 got = MMRouterLib.recognizedSupplied(vd);
if (got + MMRouterLib.REFINANCE_SLACK < before + withdrawn) {
uint256 slack = vd.account.supplySharesToAssets(vd.id, 1) + 1;
uint256 most = withdrawn / MMRouterLib.MIGRATION_LOSS_DIVISOR;
uint256 ceiling;
// A listed token has at most 18 decimals: no overflow, and no checked power shared with the price scale.
unchecked {
ceiling = 10 ** uint256(p.tokens[vd.debt].decimals) / MMRouterLib.MIGRATION_LOSS_DIVISOR;
}
if (ceiling < most) most = ceiling;
if (got + (slack < most ? slack : most) < before + withdrawn) revert IMMRouter.Conservation();
}
emit IMMRouter.SupplyMigrated(msg.sender, src, dst, withdrawn);
}
/// @dev `IMMRouter.borrowRoom`: `MMRouterLib._slice`'s room within the pair's debt room; zero while a switch or the
/// drawn set refuses. A view no flow reads, kept off the flows' library.
function borrowRoom(
MMRouterLib.PoolRecord storage p,
bool paused,
uint16 id,
uint256 collateralIn,
uint256[] calldata usd
) public view returns (uint256 room) {
MMRouterLib.checkPrices(p, usd);
MMRouterLib.Venue storage v = MMRouterLib.venueAt(p, id);
MMRouterLib.Pair storage pr = p.pairs[v.pair];
if (v.status != 0 || paused || !v.borrowEnabled || !pr.borrowEnabled || !MMRouterLib.drawable(p, pr, 0)) {
return 0;
}
MMRouterLib.Read memory none;
uint256 price = MMRouterLib.priceOf(pr, usd);
(room,) = MMRouterLib._slice(pr, v, none, false, type(uint256).max, collateralIn, 0, 0, price, false);
uint256 pairRoom = MMRouterLib.capRoom(p, pr.debtCapped ? pr.debtCap : 0, v.pair, true);
if (pairRoom < room) room = pairRoom;
}
/// @dev `IMMRouter.venueHealth`: the venue's health against its threshold, carried through its pair's pin, at the
/// caller's prices, unchecked against the venue's oracle. A view no flow reads, kept off the Router's own
/// code.
function venueHealth(MMRouterLib.PoolRecord storage p, uint16 id, uint256[] calldata usd)
public
view
returns (uint256 healthWad)
{
MMRouterLib.checkPrices(p, usd);
MMRouterLib.Venue storage v = MMRouterLib.venueAt(p, id);
MMRouterLib.Read memory r = MMRouterLib.read(v);
if (r.debt == 0) return type(uint256).max;
MMRouterLib.Pair storage pr = p.pairs[v.pair];
uint256 maxDebt = MMRouterLib.maxDebtAtPin(pr, r.collateral, MMRouterLib.priceOf(pr, usd));
return maxDebt * MMRouterLib.threshold(v) / pr.pinLtvWad * WAD / r.debt;
}
}
src/core/mm/MMRouterLib.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 {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "src/interfaces/core/mm/IFinancingAccount.sol";
import "src/interfaces/core/mm/IMMRouter.sol";
import {IHeldRepay} from "src/interfaces/core/mm/IHeldRepay.sol";
import {VenueReads} from "src/core/mm/VenueReads.sol";
import {SafeTransferLib} from "src/libraries/SafeTransferLib.sol";
/// @notice The Router's storage shapes, shared risk arithmetic, and the multi-venue bodies (allocator, cascades,
/// refinance, aggregate views) that run by delegatecall against the Router. The cold bodies that admit and
/// retire tokens, pairs and venues, and the supply migration, are `MMRouterAdminLib`'s.
library MMRouterLib {
/// @dev Conservation slack of a two-venue move, in base units of the moved token: the rounding a refinance's
/// repay and borrow together, or a migration's supply, may leave between the two venues. A lender rounds each
/// leg by under one of its debt or share units; Morpho Blue's units are worth under a base unit, and Aave's
/// scaled debt rounds a leg by up to its borrow index, so four covers both legs below an index of 2.0. A
/// refinance at a kind that rounds coarser is refused (`Conservation`). A migration may always lose four; into
/// a kind that rounds coarser it may lose up to one of its shares' worth and one, but past four never more
/// than a millionth of what it moves nor a millionth of one whole token (`MMRouterAdminLib.migrateSupply`).
uint256 internal constant REFINANCE_SLACK = 4;
/// @dev Past {REFINANCE_SLACK}, a supply migration loses at most this part of what it moves, and of one whole token
/// of the moved token: one millionth. The allowance for a shared market's rounding (a proportional release's,
/// a supply leg's) is held to the same part of one whole token and of the leg ({_roundingSlack}).
uint256 internal constant MIGRATION_LOSS_DIVISOR = 1e6;
/// @dev Debt a proportional release does not hold against it once the same transaction's repay has lowered the
/// debt. A lender burns a partial repay's debt units rounded down and reads the debt left rounded up, so the
/// venue may owe up to one of its units over the exact rest, and a pro-rata exit, which repays its debt leg
/// and releases its collateral leg, would be refused by units it cannot control. Four covers a lender whose
/// one debt unit is worth under four base units: Morpho Blue's repay by assets leaves at most one, and Aave's
/// floored burn and rounded-up read leave up to its borrow index rounded up, so it covers indices under 4.0.
/// It comes off the debt after the repay, not off the snapshot's, so it covers an exit of any size (a slack on
/// the snapshot's debt shrinks with the collateral the release leaves). The collateral that stays carries at
/// most this much debt over its exact share, the lender's own health check still binds, and a repay that
/// lowered nothing earns none. Where collateral accrues, that collateral may also fall short of its exact
/// share by a shared market's rounding ({_roundingSlack}), on the same terms.
uint256 internal constant RELEASE_SLACK = 4;
/// @dev The gas a venue's read of its minimum position may take (`IHeldRepay.minimumDebt`): twice Moolah's, whose
/// one guarded read of its core takes at most 500,000 (`MoolahAccount`).
uint256 internal constant MINIMUM_READ_GAS = 1_000_000;
/// @dev Gas well past what one venue's release takes at any listed kind, whose dearest is Venus's: a release of
/// {reclaim} begun with this much that fails with under an eighth of it left was burnt by the lender, never
/// starved by the caller's limit.
uint256 internal constant RELEASE_GAS = 3_000_000;
/// @dev One venue as the Router acts on it: the raw position and the part the Router recognizes as the pool's.
/// `collateral` and `recognizedCollateral` are base units of the pair's collateral token, `supplied`,
/// `recognizedSupplied` and `debt` of its debt token. The two recognized fields are what the managed trackers
/// hold of `collateral` and `supplied`; `debt` is the venue's whole debt, which no tracker bounds.
struct Read {
uint256 collateral;
uint256 recognizedCollateral;
uint256 supplied;
uint256 recognizedSupplied;
uint256 debt;
}
/// @dev A listed token: its address, its decimals (read once, at listing), its retirement and whether a supply cap
/// is set in one slot; the supply the pool's venues may hold of it, across every pair that lends it, in its
/// base units, in the next, which a flow reads only while one is set.
struct Token {
address token;
uint8 decimals;
bool retired;
bool supplyCapped; // `supplyCap != 0`, written with it
uint128 supplyCap;
}
/// @dev A credit pair, which borrows its debt token against its collateral token: both tokens (indices in the
/// pool's list) and their decimals, its switch, its retirement, whether a debt cap is set and its risk in the
/// one slot a priced path reads: the pin (the LTV a borrow is sized to), the safety gap (how far above the pin
/// a venue's threshold must sit) and the band (how far a venue's oracle may sit from the pair's price), all
/// WAD. The pair's debt cap across its venues, in base units of the debt token, sits in the next slot, which a
/// path reads only while one is set. `accounts` keeps the pair's first own account at each kind, bound to its
/// two tokens (`MMRouterAdminLib.deployAccount`); its venues may sit at others, each naming its own.
struct Pair {
uint8 coll;
uint8 debt;
uint8 collDecimals;
uint8 debtDecimals;
bool borrowEnabled;
bool retired;
bool debtCapped; // `debtCap != 0`, written with it
uint64 pinLtvWad;
uint64 safetyGapWad;
uint64 oracleBandWad;
uint128 debtCap;
mapping(uint8 kind => address) accounts;
}
/// @dev Five slots, grouped by what a swap reads together: the account with every flag a cascade tests and the
/// venue's pair and two tokens, copied from the pair at admission and never changed; the venue id at its
/// account; a borrow slice's limits (the venue's debt cap in debt-token base units and its rate ceiling, per
/// second, WAD, each zero for none, and its threshold, WAD); the two managed trackers; the supply cap, in
/// debt-token base units, zero for none. A sell touches the first four, a repay and its release the first,
/// second and fourth. The trackers are uint128 and raised only through `SafeCast`: Morpho Blue bounds
/// collateral and supply shares to uint128, and a leg of any other kind that would carry a tracker past
/// 2^128 - 1 reverts; a burn only lowers one. The status byte holds the `VENUE_RETIRED` and `VENUE_FENCED`
/// bits, so a walk of the venues that passes either tests one byte. A fenced venue has both switches off, and
/// they stay off while it stays fenced (`setVenueFlags`), so a path gated on a switch passes it over with no
/// test of its own; it is in no priority order, so no cascade or plan acts on it, while the caps ({capRoom})
/// and the binding threshold ({minLltv}) still count it.
struct Venue {
IFinancingAccount account;
uint8 kind;
uint8 pair;
uint8 coll; // the pair's collateral token: what the venue holds of the pool's as collateral
uint8 debt; // the pair's debt token: what the venue lends the pool and takes as supply
uint16 capabilities; // the account's, read once at admission: `KNOWN_CAPABILITIES` alone
bool borrowEnabled;
bool supplyEnabled;
uint8 status; // `VENUE_RETIRED`, `VENUE_FENCED`; zero: live, in every priority order
bool actionsOf; // the account answered `IActionsOf.actionsOf` as its `actions` at admission
bytes32 id;
uint128 debtCap;
uint64 maxBorrowRateWad;
uint64 lltvWad; // at admission; read live instead for a kind whose threshold can fall
uint128 managedCollateralUnits; // units the Router posted (assets for a kind that never accrues)
uint128 managedSupplyShares;
uint128 supplyCap;
}
/// @dev The pool asset, the drawn-set limit, the recheck switch and both counts in one slot, so no access to a
/// token or a pair reads a length. `venues` is indexed by venue id, and a retired slot may be reused; each of
/// the four priority orders lists every live, unfenced venue once.
struct PoolRecord {
address poolAsset;
uint8 maxDrawnTokens;
bool fundRecheckOff; // `fund` borrows on its plan's checks alone
uint8 tokenCount;
uint8 pairCount;
mapping(uint8 => Token) tokens;
mapping(uint8 => Pair) pairs;
Venue[] venues;
uint16[] borrowOrder;
uint16[] supplyOrder;
uint16[] withdrawOrder;
uint16[] repayOrder;
}
/// @dev A funding plan, its three lists indexed by venue id: `withdrawTake` the supply to withdraw, `borrowSlice`
/// the debt to borrow, both in base units of the pair's debt token, and `post` the collateral to post for that
/// slice, in base units of its collateral token. `remaining`: what no leg covers, in debt-token base units.
/// `price`: the pair's price the borrow phase sized its slices at ({maxDebtAtPin}), zero where the plan
/// borrows nothing.
struct Plan {
uint256[] withdrawTake;
uint256[] borrowSlice;
uint256[] post;
uint256 remaining;
uint256 price;
}
// ------------------------------------------------------------------ delegatecalled bodies
/// @dev Releases what the venue lets go of now (`releasable`) and returns it; the rest stays posted, recognized and
/// waiting, and a release of nothing reads no snapshot and no price.
function withdrawCollateral(
PoolRecord storage p,
uint16 id,
uint256 assets,
uint256[] calldata usd,
bool proportional
) public returns (uint256) {
checkPrices(p, usd);
Venue storage v = venueAt(p, id);
// One read of the position: its collateral and debt are `collateralOf` and `debtOf` in the same state, which
// the release check alone (a view) does not move.
(uint256 coll,,, uint256 debt) = v.account.position(v.id);
if (assets == 0 || assets > recognizedFrom(v, coll)) revert IMMRouter.InsufficientCollateral(assets);
uint256 rel = releasable(v);
if (rel < assets) assets = rel;
if (assets == 0) return 0;
if (debt != 0) {
if (proportional) {
(uint256 debtBefore, uint256 collBefore) = repaySnapshot(msg.sender, id);
if (collBefore == 0) revert IMMRouter.NoRepaySnapshot();
// The lender's rounding of a repay that lowered the debt is not held against the release, nor, where
// the exact proof fails, the rounding a shared market's rate passed on ({_requireSharedRounding}).
uint256 held = debt < debtBefore ? debt - Math.min(debt, RELEASE_SLACK) : debt;
if (held * collBefore > debtBefore * (coll - assets)) _requireSharedRounding(p, v, id, assets);
} else {
// A fenced venue's debt is unwound by id: what a repay frees, never what a price allows.
if (v.status & VENUE_FENCED != 0) revert IMMRouter.VenueIsFenced();
Pair storage pr = p.pairs[v.pair];
uint256 price = priceOf(pr, usd);
if (!bandOk(pr, v, price)) revert IMMRouter.OracleBand();
if (debt > maxDebtAt(releaseLtv(pr, v), coll - assets, price)) revert IMMRouter.Unhealthy();
}
}
burnUnits(v, v.account.withdrawCollateral(v.id, assets, msg.sender));
emit IMMRouter.CollateralWithdrawn(msg.sender, id, assets);
return assets;
}
/// @dev Executes `buildPlan`. Unless the pool turned it off, each slice is re-checked against its venue as the
/// plan's withdrawals and the slice's own post left it, just before it borrows.
function fund(PoolRecord storage p, bool paused, uint8 pairIdx, uint256 assets, uint256 collateralIn, uint256[] calldata usd)
public
{
Plan memory plan = buildPlan(p, paused, pairIdx, assets, collateralIn, usd, 0);
if (plan.remaining != 0) revert IMMRouter.InsufficientLiquidity(plan.remaining);
uint16[] storage wo = p.withdrawOrder;
for (uint256 i; i < wo.length; ++i) {
uint256 take = plan.withdrawTake[wo[i]];
if (take == 0) continue;
withdrawTracked(p.venues[wo[i]], take, 0, msg.sender);
emit IMMRouter.SuppliedWithdrawn(msg.sender, wo[i], take, msg.sender);
}
if (plan.price == 0) return; // no slice: the plan borrows nothing
Pair storage pr = p.pairs[pairIdx];
uint16[] storage bo = p.borrowOrder;
for (uint256 i; i < bo.length; ++i) {
uint16 id = bo[i];
uint256 slice = plan.borrowSlice[id];
if (slice == 0) continue;
Venue storage v = p.venues[id];
uint256 post = plan.post[id];
if (post != 0) {
pull(tokenOf(p, pr.coll), address(v.account), post);
mintUnits(v, v.account.supplyCollateral(v.id, post));
emit IMMRouter.CollateralPosted(msg.sender, id, post);
}
if (!p.fundRecheckOff) {
(uint256 coll,,, uint256 debt) = v.account.position(v.id);
requireSliceFits(pr, v, debt, coll, slice, plan.price);
}
v.account.borrow(v.id, slice, msg.sender);
emit IMMRouter.Borrowed(msg.sender, id, slice, msg.sender);
}
}
/// @dev A venue that takes less than its pay (a minimum position, a held full exit) returns the rest to the pool
/// ({repayInto}), and the cascade does not spend it again: it pulls at most `assets` from the pool's
/// allowance in all, so a short repay never leaves a later pull without one.
function repayCascade(PoolRecord storage p, uint8 token, uint256 assets) public returns (uint256 repaid) {
address t = tokenAt(p, token).token;
uint16[] storage ro = p.repayOrder;
uint256 remaining = assets;
for (uint256 i; i < ro.length && remaining != 0; ++i) {
Venue storage v = p.venues[ro[i]];
if (v.debt != token) continue;
(uint256 coll,,, uint256 debt) = v.account.position(v.id);
// A venue that owes nothing is passed before its gate is read.
if (debt == 0 || !canAct(v, CAN_REPAY)) continue;
uint256 pay = remaining < debt ? remaining : debt;
_snapshot(ro[i], debt, coll);
uint256 got = repayInto(v, t, pay);
repaid += got;
remaining -= pay;
emit IMMRouter.Repaid(msg.sender, ro[i], got);
}
}
/// @dev Walks the venues lending `token` with supply on, in supply order, within each one's room and the token's
/// cap, and returns what they took; nothing while `paused`. A venue that holds a minimum position takes no
/// leg that leaves it under that minimum ({_underMinimum}); what no venue takes stays with the pool.
function supplyCascade(PoolRecord storage p, bool paused, uint8 token, uint256 assets) public returns (uint256 supplied) {
if (paused) return 0;
Token storage t = tokenAt(p, token);
uint256 remaining = assets;
uint256 tokenRoom = capRoom(p, t.supplyCapped ? t.supplyCap : 0, token, false);
uint16[] storage so = p.supplyOrder;
for (uint256 i; i < so.length && remaining != 0 && tokenRoom != 0; ++i) {
Venue storage v = p.venues[so[i]];
if (v.debt != token || !v.supplyEnabled) continue;
uint256 room = supplyRoom(v);
if (room > tokenRoom) room = tokenRoom;
uint256 take = remaining < room ? remaining : room;
if (take == 0) continue;
if (uint256(v.capabilities) & CAP_HELD_REPAY != 0 && _underMinimum(v, read(v).supplied, take, true)) continue;
pull(t.token, address(v.account), take);
mintShares(v, v.account.supply(v.id, take));
supplied += take;
remaining -= take;
tokenRoom -= take;
emit IMMRouter.Supplied(msg.sender, so[i], take);
}
}
/// @dev Each venue lending `token` gives what it recognizes as the pool's supply and has the cash to pay, in
/// withdraw order; one whose withdrawal reverts at the lender (a pause, a freeze, a cash shortfall) is passed
/// over, so the rest still pay. One whose supply tracker is zero recognizes none and is not read.
function withdrawCascade(PoolRecord storage p, uint8 token, uint256 assets, address to)
public
returns (uint256 withdrawn)
{
tokenAt(p, token);
uint16[] storage wo = p.withdrawOrder;
uint256 remaining = assets;
for (uint256 i; i < wo.length && remaining != 0; ++i) {
uint16 id = wo[i];
Venue storage v = p.venues[id];
if (v.debt != token || v.managedSupplyShares == 0) continue;
uint256 avail = read(v).recognizedSupplied;
if (avail == 0) continue;
uint256 cash = v.account.supplyWithdrawable(v.id);
if (cash < avail) avail = cash;
uint256 take = remaining < avail ? remaining : avail;
if (take == 0) continue;
try v.account.withdraw(v.id, take, 0, to) returns (uint256, uint256 burned) {
v.managedSupplyShares = _less(v.managedSupplyShares, burned);
} catch {
continue;
}
withdrawn += take;
remaining -= take;
emit IMMRouter.SuppliedWithdrawn(msg.sender, id, take, to);
}
}
/// @dev Walks the venues whose collateral is `token`, in reverse borrow order. A venue whose release reverts at the
/// lender (a check at its own price, a pause) is passed over, so a payout out of collateral still draws on
/// the others; one whose collateral tracker is zero recognizes none and is not read. A release that fails with
/// under an eighth of the gas it began with left may have run out of gas some calls down, which a refusal
/// with gas to spare cannot: begun under {RELEASE_GAS}, that is the caller's limit, and the walk reverts
/// `VenueReads.ReadStarved` rather than let the limit pick what stays posted; begun with more, the lender
/// burnt it, and the walk ends there with what it released ({_burnt}). A band read that fails so reverts as
/// well ({freeCollateral}); every other read of the walk reverts by itself when starved, at its kind's guard
/// (`IFinancingAccount` ADMISSION) or out of gas in the walk.
function reclaim(PoolRecord storage p, uint8 token, uint256 assets, uint256[] calldata usd) public returns (uint256 got) {
checkPrices(p, usd);
uint16[] storage bo = p.borrowOrder;
uint256 remaining = assets;
for (uint256 i = bo.length; i > 0 && remaining != 0; --i) {
uint16 id = bo[i - 1];
Venue storage v = p.venues[id];
if (v.coll != token || v.managedCollateralUnits == 0) continue;
uint256 free = freeCollateral(p, v, usd, true);
uint256 take = remaining < free ? remaining : free;
if (take == 0) continue;
uint256 g = gasleft();
try v.account.withdrawCollateral(v.id, take, msg.sender) returns (uint256 units) {
burnUnits(v, units);
} catch {
if (_burnt(g)) break;
continue;
}
got += take;
remaining -= take;
emit IMMRouter.CollateralWithdrawn(msg.sender, id, take);
}
}
/// @dev Whether a failed release of {reclaim} begun with `g` gas left under an eighth of it, which the lender burnt
/// where `g` is at least {RELEASE_GAS}; under it, the caller's limit may have starved the release, and it
/// reverts `VenueReads.ReadStarved` instead.
function _burnt(uint256 g) private view returns (bool) {
if (gasleft() >= g / 8) return false;
if (g < RELEASE_GAS) revert VenueReads.ReadStarved();
return true;
}
/// @dev Within one pair: the destination's pair already owes, as the source does, so the move starts no debt and
/// changes neither the owed set nor the backing set.
function refinanceDebt(PoolRecord storage p, bool paused, uint16 src, uint16 dst, uint256 assets, uint256[] calldata usd) public {
if (paused) revert IMMRouter.GlobalPaused();
checkPrices(p, usd);
if (src == dst) revert IMMRouter.VenueMismatch();
Venue storage vs = venueAt(p, src);
Venue storage vd = live(p, dst);
if ((vs.status | vd.status) & VENUE_FENCED != 0) revert IMMRouter.VenueIsFenced();
if (vs.pair != vd.pair) revert IMMRouter.VenueMismatch();
if (!vd.borrowEnabled) revert IMMRouter.VenueDisabled();
uint256 debtSrc = vs.account.debtOf(vs.id);
if (debtSrc == 0) revert IMMRouter.NothingToMove();
bool full = assets >= debtSrc;
uint256 move = full ? debtSrc : assets;
if (move == 0) revert IMMRouter.NothingToMove();
uint256 collSrc = vs.account.collateralOf(vs.id);
uint256 recognized = recognizedFrom(vs, collSrc);
uint256 collMove = full ? recognized : Math.mulDiv(recognized, move, debtSrc);
if (collMove > releasable(vs)) revert IMMRouter.InsufficientLiquidity(collMove);
uint256 debtDst = vd.account.debtOf(vd.id);
Pair storage pr = p.pairs[vs.pair];
uint256 price = priceOf(pr, usd);
if (!bandOk(pr, vd, price)) revert IMMRouter.OracleBand();
if (overPinned(pr, vd)) revert IMMRouter.VenueOverPinned();
if (!full && !bandOk(pr, vs, price)) revert IMMRouter.OracleBand();
if (vd.account.borrowable(vd.id) < move) revert IMMRouter.InsufficientLiquidity(move);
if (vd.debtCap != 0 && debtDst + move > vd.debtCap) revert IMMRouter.DebtCapExceeded();
requireRate(vd, move);
if (debtDst + move > maxDebtAtPin(pr, vd.account.collateralOf(vd.id) + collMove, price)) revert IMMRouter.Unhealthy();
if (!full && debtSrc - move > maxDebtAtPin(pr, collSrc - collMove, price)) revert IMMRouter.Unhealthy();
// The atomic primitive counts one unit per asset moved, true only where collateral never accrues; the bridge
// reports what each leg burned and minted.
uint256 unitsOut = collMove;
uint256 unitsIn = collMove;
if (
address(vs.account) == address(vd.account)
&& uint256(vs.capabilities) & (CAP_ATOMIC_REFINANCE | CAP_ACCRUING_COLLATERAL) == CAP_ATOMIC_REFINANCE
) {
if (vs.account.refinance(vs.id, vd.id, full ? 0 : move, collMove) != move) revert IMMRouter.ExactDelta();
} else {
(unitsOut, unitsIn) = _bridge(p, vs, vd, move, collMove);
}
burnUnits(vs, unitsOut);
mintUnits(vd, unitsIn);
uint256 totalAfter = vs.account.debtOf(vs.id) + vd.account.debtOf(vd.id);
uint256 totalBefore = debtSrc + debtDst;
if (totalAfter + REFINANCE_SLACK < totalBefore || totalAfter > totalBefore + REFINANCE_SLACK) revert IMMRouter.Conservation();
emit IMMRouter.DebtRefinanced(msg.sender, src, dst, move, collMove);
}
/// @dev Between two accounts of one pair: the pool's granted debt token repays `src`, the collateral crosses
/// account to account, and `dst` borrows the same amount back to the pool.
function _bridge(PoolRecord storage p, Venue storage vs, Venue storage vd, uint256 move, uint256 collMove)
private
returns (uint256 unitsOut, uint256 unitsIn)
{
address token = tokenOf(p, vs.debt);
if (IERC20(token).allowance(msg.sender, address(this)) < move) revert IMMRouter.InsufficientBridge(move);
if (repayInto(vs, token, move) != move) revert IMMRouter.ExactDelta();
if (collMove != 0) {
unitsOut = vs.account.withdrawCollateral(vs.id, collMove, address(vd.account));
unitsIn = vd.account.supplyCollateral(vd.id, collMove);
}
vd.account.borrow(vd.id, move, msg.sender);
}
/// @dev Shared by quote and execution: withdrawals of the pair's debt token at every unfenced venue lending it, in
/// withdraw order, then borrow slices at the pair's venues, in borrow order, each bounded by cash, caps, rate
/// ceiling, oracle band and what `collateralIn` can post at the pair's pin within the venue's post room
/// (`Capacity.collateralPostable`).
/// - The borrow phase runs only while the pair may draw: its switch, the global pause and the drawn set
/// ({drawable}, read with `assumeRepaid`).
/// - A venue's cash and rate are taken net of its own withdrawal and of the legs at venues whose kind shares
/// its cash (`CAP_SHARED_LIQUIDITY`); such a venue's own are net of every earlier leg of the plan, and it
/// gives no withdrawal where those leave its cash under one unit's payout (`supplySharesToAssets(id, 1)`),
/// which a slice there redeems whole: the kind's own read reports none then, but not past legs it does not
/// see.
/// - Such a venue's post room is net, too, of the plan's posts through the pair's other accounts at its kind
/// and of what those accounts may hold for them ({_postRoom}), which its account's report does not see: a
/// slice whose post passes it is sized again within it, so one plan never posts past the room its lender
/// has, wherever the pair's venues there sit; at one account the kind's own report parts that room among the
/// account's venues, each part net of those posts whole, so a plan may leave a part's room to a later plan.
/// - Another pair's venue whose supply tracker is zero is not read: it recognizes no supply, and only the
/// pair's own venues' reads serve the borrow phase.
/// - An unchecked pair borrows nothing, as no slice passes its band at a zero price, so its plan ends there.
function buildPlan(
PoolRecord storage p,
bool paused,
uint8 pairIdx,
uint256 assets,
uint256 collateralIn,
uint256[] calldata usd,
uint16 assumeRepaid
) public view returns (Plan memory plan) {
checkPrices(p, usd);
Pair storage pr = pairAt(p, pairIdx);
uint8 lent = pr.debt;
uint256 n = p.venues.length;
plan.withdrawTake = new uint256[](n);
plan.borrowSlice = new uint256[](n);
plan.post = new uint256[](n);
plan.remaining = assets;
Read[] memory rds = new Read[](n);
uint256 have; // bit `id`: `rds[id]` holds the venue's read (a view: the state cannot move in between)
uint256 wShared; // withdrawn, then borrowed, at venues that share their cash
uint256 bShared;
uint16[] storage wo = p.withdrawOrder;
for (uint256 i; i < wo.length && plan.remaining != 0; ++i) {
Venue storage v = p.venues[wo[i]];
if (v.debt != lent || (v.pair != pairIdx && v.managedSupplyShares == 0)) continue;
rds[wo[i]] = read(v);
have |= uint256(1) << wo[i];
uint256 avail = rds[wo[i]].recognizedSupplied;
if (avail == 0) continue;
bool sh = sharesCash(v);
uint256 used = sh ? assets - plan.remaining : wShared;
uint256 cash = v.account.supplyWithdrawable(v.id);
cash = cash > used ? cash - used : 0;
if (cash < avail) avail = cash;
uint256 take = plan.remaining < avail ? plan.remaining : avail;
if (sh) {
// the earlier legs, netted past the kind's own read, can leave the reserve's cash under one unit's
// payout, which a slice there redeems whole: such a remainder gives nothing
if (take != 0 && cash < v.account.supplySharesToAssets(v.id, 1)) take = 0;
wShared += take;
}
plan.withdrawTake[wo[i]] = take;
plan.remaining -= take;
}
if (plan.remaining == 0 || paused) return plan;
uint256 price = priceOf(pr, usd);
if (price == 0 || !pr.borrowEnabled || !drawableRead(p, pr, pairIdx, lent, assumeRepaid, rds, have)) {
return plan;
}
uint256 wAll = assets - plan.remaining;
uint256 debtRoom = capRoom(p, pr.debtCapped ? pr.debtCap : 0, pairIdx, true);
uint256 collAvail = collateralIn;
uint16[] storage bo = p.borrowOrder;
for (uint256 i; i < bo.length && plan.remaining != 0 && debtRoom != 0; ++i) {
Venue storage v = p.venues[bo[i]];
if (v.pair != pairIdx || !v.borrowEnabled) continue;
uint256 want = plan.remaining < debtRoom ? plan.remaining : debtRoom;
bool sh = sharesCash(v);
(uint256 slice, uint256 post) = _slice(
pr,
v,
rds[bo[i]],
(have >> bo[i]) & 1 != 0,
want,
collAvail,
sh ? wAll : plan.withdrawTake[bo[i]] + wShared,
sh ? assets - plan.remaining - wAll : bShared,
price,
true
);
if (slice == 0) continue;
plan.borrowSlice[bo[i]] = slice;
plan.post[bo[i]] = post;
plan.remaining -= slice;
collAvail -= post;
debtRoom -= slice;
if (sh) {
// A post past what the plan's posts through the pair's other accounts at the lender, and what those
// accounts may hold for them, left of its room ({_postRoom}) is sized again within it, on the same
// reads; none precedes the plan's first slice at a venue that shares its cash (`bShared` zero), so
// that one reads no room.
uint16 id = bo[i];
uint256 q = plan.post[id];
uint256 room = q == 0 || bShared == 0 ? q : _postRoom(p, plan.post, p.venues[id]);
if (q > room) {
(uint256 s, uint256 r) = _slice(
pr,
p.venues[id],
rds[id],
(have >> id) & 1 != 0,
(plan.remaining < debtRoom ? plan.remaining : debtRoom) + slice,
room,
wAll,
assets - plan.remaining - slice - wAll,
price,
true
);
(plan.borrowSlice[id], plan.post[id], plan.remaining) = (s, r, plan.remaining + slice - s);
(collAvail, debtRoom, slice) = (collAvail + q - r, debtRoom + slice - s, s);
if (s == 0) continue;
}
bShared += slice;
}
plan.price = price;
}
}
/// @dev The post room venue `v` keeps in a plan that posts `posts`: what its account reports, less the plan's posts
/// through the pair's other accounts at its kind, which fill the same lender's room (one reserve per token,
/// `IFinancingAccount` ADMISSION) while each account parts it among its own venues alone, each with one unit's
/// assets where collateral accrues: the most that account may hold for the post (one too small to mint a
/// unit), which the post mints with its own and only that account's report nets. No bound where no such post
/// precedes it. A kind that caps no post reports no bound either (`Capacity.collateralPostable`).
function _postRoom(PoolRecord storage p, uint256[] memory posts, Venue storage v) private view returns (uint256) {
uint256 taken;
for (uint256 j; j < posts.length; ++j) {
if (posts[j] == 0) continue;
Venue storage w = p.venues[j];
if (w.kind == v.kind && address(w.account) != address(v.account)) {
taken += posts[j];
if (uint256(w.capabilities) & CAP_ACCRUING_COLLATERAL != 0) {
taken += w.account.collateralUnitsToAssets(w.id, 1);
}
}
}
if (taken == 0) return type(uint256).max;
uint256 room = v.account.collateralPostable(v.id);
return room > taken ? room - taken : 0;
}
/// @dev {drawable} for `buildPlan`, whose withdraw phase read the unfenced venues lending `lent`, the pair's debt
/// token (`have`, `rds`): where one of the pair's own venues owes and `assumeRepaid` reads none of `lent`
/// repaid, the pair may draw, with no scan of every venue. That venue puts `lent` in the owed set and the
/// pair's collateral token in the backing set, so, no token being both, the collateral token is owed nowhere
/// and `lent` backs no debt, and `lent`, owed already, adds no owed token: {drawable}'s answer.
function drawableRead(
PoolRecord storage p,
Pair storage pr,
uint8 pairIdx,
uint8 lent,
uint16 assumeRepaid,
Read[] memory rds,
uint256 have
) internal view returns (bool) {
if (p.pairCount == 1) return true;
if ((assumeRepaid >> lent) & 1 == 0) {
for (uint256 i; have >> i != 0; ++i) {
if ((have >> i) & 1 != 0 && rds[i].debt != 0 && p.venues[i].pair == pairIdx) return true;
}
}
return drawable(p, pr, assumeRepaid);
}
/// @dev `buildPlan`'s `remaining` alone, so `MMRouter.fundingCeiling` takes one word back across the call, not the
/// plan's three venue-length arrays. Its selector sorts last in this library's dispatcher, so no other entry
/// pays one more compare for it.
function fundingRest(
PoolRecord storage p,
bool paused,
uint8 pairIdx,
uint256 assets,
uint256 collateralIn,
uint256[] calldata usd,
uint16 assumeRepaid
) public view returns (uint256) {
return buildPlan(p, paused, pairIdx, assets, collateralIn, usd, assumeRepaid).remaining;
}
/// @dev The sum of {freeCollateral} over the venues {reclaim} walks: live, unfenced, with `token` as collateral and
/// a collateral tracker. A venue whose release would revert at the lender still counts here.
function reclaimable(PoolRecord storage p, uint8 token, uint256[] calldata usd) public view returns (uint256 total) {
checkPrices(p, usd);
uint256 n = p.venues.length;
for (uint256 i; i < n; ++i) {
Venue storage v = p.venues[i];
if (v.status == 0 && v.coll == token && v.managedCollateralUnits != 0) {
total += freeCollateral(p, v, usd, false);
}
}
}
/// @dev The venue's position, from one read of it, with the parts the Router recognizes ({Read}): collateral
/// through {recognizedFrom}, supply as the tracked shares the venue still holds, at their worth there.
function read(Venue storage v) internal view returns (Read memory r) {
uint256 shares;
(r.collateral, shares, r.supplied, r.debt) = v.account.position(v.id);
r.recognizedCollateral = recognizedFrom(v, r.collateral);
uint256 managed = shares < v.managedSupplyShares ? shares : v.managedSupplyShares;
r.recognizedSupplied = managed == shares ? r.supplied : v.account.supplySharesToAssets(v.id, managed);
}
/// @dev `cashUsed` and `borrowUsed`: what the plan's earlier legs withdraw from and borrow out of the venue's cash,
/// which execute before its borrow. Where collateral accrues (`CAP_ACCRUING_COLLATERAL`) the venue credits a
/// post in its own units, rounded down, and checks its own factor on what it credits: a plan's post (`pad`,
/// which `fund` makes) carries one unit's assets and one past what the pin needs, so the venue reads at least
/// that need (`IFinancingAccount` ADMISSION), and the slice is sized on the collateral left to post past
/// them. A post of the need alone could be credited a unit short, and a draw whose need is a unit or two
/// (dust) refused by the venue though the plan allowed it. `MMRouterAdminLib.borrowRoom` pads none: the pool
/// posts its own leg there (`postCollateral`) and `borrow` allows the rounding.
function _slice(
Pair storage pr,
Venue storage v,
Read memory rd,
bool readDone,
uint256 want,
uint256 collAvail,
uint256 cashUsed,
uint256 borrowUsed,
uint256 price,
bool pad
) internal view returns (uint256 slice, uint256 post) {
if (!bandOk(pr, v, price) || overPinned(pr, v)) return (0, 0);
uint256 caps = uint256(v.capabilities);
uint256 cash;
if (caps & (CAP_PROTOCOL_CAPS | CAP_ACTION_GATES) == 0) {
cash = v.account.borrowable(v.id);
} else {
// One read of what the venue can move now (`IFinancingAccount.capacity`), whose fields are its single
// views in the same state but at the one exception `IFinancingAccount`'s ADMISSION names. A post is at
// most what the venue still takes, nothing while it refuses posts, its cap's room otherwise, whatever
// room a later kind reports beside a refusal.
IFinancingAccount.Capacity memory k = v.account.capacity(v.id);
uint256 postable = k.collateralPostable;
if (caps & CAP_ACTION_GATES != 0 && k.actions & CAN_POST_COLLATERAL == 0) postable = 0;
if (postable < collAvail) collAvail = postable;
cash = k.borrowable;
}
uint256 extra;
if (pad && caps & CAP_ACCRUING_COLLATERAL != 0) (extra, collAvail) = _postSlack(pr, v, collAvail);
if (!readDone) rd = read(v);
uint256 debt = rd.debt;
uint256 coll = rd.collateral;
uint256 used = cashUsed + borrowUsed;
cash = cash > used ? cash - used : 0;
slice = want < cash ? want : cash;
if (v.debtCap != 0) {
uint256 room = v.debtCap > debt ? v.debtCap - debt : 0;
if (room < slice) slice = room;
}
uint256 maxDebt = maxDebtAtPin(pr, coll + collAvail, price);
uint256 byColl = maxDebt > debt ? maxDebt - debt : 0;
if (byColl < slice) slice = byColl;
if (slice == 0) return (0, 0);
uint256 ceiling = v.maxBorrowRateWad;
if (ceiling != 0) {
// Priced after the plan's earlier legs (`cashUsed`, `borrowUsed`), which execute before the borrow.
(bool ok, uint256 rate) = v.account.borrowRateAfter(v.id, borrowUsed + slice, cashUsed);
if (!ok) return (0, 0);
if (rate > ceiling) {
// Over the ceiling, trimmed to the largest part under it, not dropped; the account's search errs low,
// and no answer of it widens the slice past the bounds already taken.
uint256 trimmed = v.account.ceilingBorrowSlice(v.id, borrowUsed, cashUsed, slice, ceiling);
if (trimmed < slice) slice = trimmed;
}
if (slice == 0) return (0, 0);
}
// At most `collAvail` with `extra`: `slice` is within `byColl`, and the pin's two roundings never need more
// than the collateral that sized it.
if (caps & CAP_HELD_REPAY != 0 && _underMinimum(v, debt, slice, false)) return (0, 0);
uint256 need = requiredCollateral(pr.pinLtvWad, debt + slice, price);
post = need > coll ? need - coll + extra : 0;
}
/// @dev Whether `add` more at a venue whose kind holds a minimum position (`CAP_HELD_REPAY`) leaves its position
/// `held` under the minimum it values now (`IHeldRepay.minimumDebt`), or over it by less than {RELEASE_SLACK}
/// where the lender's check can read the position under what the Router counts: a `supply`, whose shares the
/// lender mints rounded down, so that even a first supply of exactly the minimum reads a unit under it, and a
/// borrow where the venue owes, whose debt the Router reads rounded up. A first borrow mints its shares
/// rounded up and reads at least what it borrowed, so it needs the minimum alone. The lender refuses a borrow
/// or a supply that leaves the position under its minimum, so the plan's slice and the cascade's take pass
/// the venue over, as they do within the slack, where a lender may still take them. The read is a static call
/// of at most {MINIMUM_READ_GAS} (`VenueReads.peekData`): one that reverts, runs out of that gas or answers
/// short passes the venue over, as no leg there can be sized, and one its caller left short of that gas
/// reverts `VenueReads.ReadStarved`, so no caller makes a venue look unreadable by starving it. False while
/// the venue cannot value its minimum (`ok` false), where it reports nothing borrowable or suppliable.
function _underMinimum(Venue storage v, uint256 held, uint256 add, bool supply) private view returns (bool) {
bytes memory data = abi.encodeCall(IHeldRepay.minimumDebt, (v.id));
if (!VenueReads.peekData(MINIMUM_READ_GAS, address(v.account), data, 2)) return true;
if (VenueReads.word(0) == 0) return false;
uint256 floor = VenueReads.word(1);
uint256 after_ = held + add;
return after_ < floor || ((held != 0 || supply) && after_ - floor < RELEASE_SLACK);
}
/// @dev {_slice}'s post slack at venue `v`, whose collateral accrues: one unit's assets, at most a millionth of one
/// whole collateral token as {_roundingSlack} holds the release side, so a unit a donation raised cannot widen
/// it, and one; at most the `collAvail` the pool can post (none while it can post none), and what that leaves
/// to post past it.
function _postSlack(Pair storage pr, Venue storage v, uint256 collAvail)
private
view
returns (uint256 s, uint256 left)
{
if (collAvail == 0) return (0, 0);
s = v.account.collateralUnitsToAssets(v.id, 1);
// A listed token has at most 18 decimals, so `most` is at most 1e12: no overflow.
unchecked {
uint256 most = 10 ** uint256(pr.collDecimals) / MIGRATION_LOSS_DIVISOR;
s = (s < most ? s : most) + 1;
}
if (s > collAvail) s = collAvail;
left = collAvail - s;
}
/// @dev The lesser of the venue's and its debt token's supply rooms; zero while supply is off.
function supplyRoomOf(PoolRecord storage p, bool paused, uint16 id) public view returns (uint256 room) {
Venue storage v = venueAt(p, id);
if (v.status != 0 || paused || !v.supplyEnabled) return 0;
room = supplyRoom(v);
Token storage t = p.tokens[v.debt];
uint256 tokenRoom = capRoom(p, t.supplyCapped ? t.supplyCap : 0, v.debt, false);
if (tokenRoom < room) room = tokenRoom;
}
/// @dev The binding threshold of pair `pairIdx`: every borrow-enabled venue of the pair and every one that still
/// carries debt, so disabling borrow on an indebted venue cannot let the pair's pin step past its gap. A zero
/// threshold binds like any other; `NO_VENUE_LLTV` where none binds, a pair not added among them.
function minLltv(PoolRecord storage p, uint8 pairIdx) public view returns (uint256 lltv) {
lltv = NO_VENUE_LLTV;
uint256 n = p.venues.length;
for (uint256 i; i < n; ++i) {
Venue storage v = p.venues[i];
if (v.status & VENUE_RETIRED != 0 || v.pair != pairIdx) continue;
if (!v.borrowEnabled && v.account.debtOf(v.id) == 0) continue;
uint256 l = threshold(v);
if (l < lltv) lltv = l;
}
}
// ------------------------------------------------------------------ shared internal helpers
/// @dev Token `idx`'s record, retired or not; `BadTokenIndex` past the list.
function tokenAt(PoolRecord storage p, uint8 idx) internal view returns (Token storage) {
if (idx >= p.tokenCount) revert IMMRouter.BadTokenIndex();
return p.tokens[idx];
}
/// @dev Pair `idx`'s record, retired or not; `BadPairIndex` past the list.
function pairAt(PoolRecord storage p, uint8 idx) internal view returns (Pair storage) {
if (idx >= p.pairCount) revert IMMRouter.BadPairIndex();
return p.pairs[idx];
}
/// @dev Token `idx`'s address: the pool asset's from the record's first slot, which every pool call reads first.
function tokenOf(PoolRecord storage p, uint8 idx) internal view returns (address) {
return idx == 0 ? p.poolAsset : p.tokens[idx].token;
}
/// @dev Venue `id`'s record, whatever its status; `BadVenueId` past the array.
function venueAt(PoolRecord storage p, uint16 id) internal view returns (Venue storage) {
if (id >= p.venues.length) revert IMMRouter.BadVenueId();
return p.venues[id];
}
/// @dev Venue `id`'s record, `VenueIsRetired` for a retired one. A fenced venue passes: a path that refuses one
/// does so itself, and the by-id legs that unwind one or set its caps take it.
function live(PoolRecord storage p, uint16 id) internal view returns (Venue storage v) {
v = venueAt(p, id);
if (v.status & VENUE_RETIRED != 0) revert IMMRouter.VenueIsRetired();
}
/// @dev Every priced call's vector holds one USD price per listed token.
function checkPrices(PoolRecord storage p, uint256[] calldata usd) internal view {
if (usd.length != p.tokenCount) revert IMMRouter.BadPriceVector();
}
/// @dev The pair's price in its venues' price scale, from the pool's USD vector ({pairPrice36}); zero when either
/// token is unchecked.
function priceOf(Pair storage pr, uint256[] calldata usd) internal view returns (uint256) {
return pairPrice36(usd[pr.coll], usd[pr.debt], pr.collDecimals, pr.debtDecimals);
}
/// @dev Pulls exactly `amount` of `token` from the pool's allowance into an account, as OpenZeppelin 4.8's
/// `SafeERC20.safeTransferFrom` does (the same call, verdicts and revert data), through `SafeTransferLib`.
function pull(address token, address to, uint256 amount) internal {
if (amount != 0) SafeTransferLib.safeTransferFrom(token, msg.sender, to, amount);
}
/// @dev Pulls `pay` into the venue's account and repays; a rounding remainder comes straight back.
function repayInto(Venue storage v, address token, uint256 pay) internal returns (uint256 repaid) {
pull(token, address(v.account), pay);
repaid = v.account.repay(v.id, pay);
if (repaid < pay) v.account.returnToPool(token, pay - repaid);
}
/// @dev The owed set (bit `t`: a live, unfenced venue lending token `t` holds borrow shares) and the backing set
/// (bit `t`: token `t` is such a venue's collateral), over the live, unfenced venues whose debt token is
/// outside `skip`.
function sets(PoolRecord storage p, uint256 skip) internal view returns (uint256 owed, uint256 backing) {
uint256 n = p.venues.length;
for (uint256 i; i < n; ++i) {
Venue storage v = p.venues[i];
if (v.status != 0 || (skip >> v.debt) & 1 != 0) continue;
(, uint256 borrowShares,) = v.account.positionOf(v.id);
if (borrowShares != 0) {
owed |= uint256(1) << v.debt;
backing |= uint256(1) << v.coll;
}
}
}
/// @dev Whether pair (a -> b) may start a debt, the drawn set read with every venue lending a token of
/// `assumeRepaid` as debt-free: refused where a is owed, where b backs a debt, or where b would be an owed
/// token past `maxDrawnTokens` (a b already owed adds none). The venues lending b are not read for the first
/// two: their debt is never a and their collateral never b. A pool of one pair has nothing else to read.
function drawable(PoolRecord storage p, Pair storage pr, uint16 assumeRepaid) internal view returns (bool) {
if (p.pairCount == 1) return true;
(uint256 a, uint256 b) = (pr.coll, pr.debt);
(uint256 owed, uint256 backing) = sets(p, uint256(assumeRepaid) | (uint256(1) << b));
if ((owed >> a) & 1 != 0 || (backing >> b) & 1 != 0) return false;
uint256 count;
for (; owed != 0; owed &= owed - 1) {
++count;
}
if (count < p.maxDrawnTokens) return true;
// At the limit only a b already owed adds no owed token; a venue lending b read as repaid owes nothing.
if ((assumeRepaid >> b) & 1 != 0) return false;
(owed,) = sets(p, ~(uint256(1) << b));
return owed != 0;
}
/// @dev The room under a `cap` (zero: none) on the debt of pair `key` (`debtSide`) or on the recognized supply of
/// token `key`, across the live venues it covers; on the supply side a venue whose supply tracker is zero
/// recognizes none and is not read. Its callers pass zero while the pair or token has no cap set
/// (`Pair.debtCapped`, `Token.supplyCapped`), with no read of the cap's slot.
function capRoom(PoolRecord storage p, uint256 cap, uint8 key, bool debtSide) internal view returns (uint256) {
if (cap == 0) return type(uint256).max;
uint256 used;
uint256 n = p.venues.length;
for (uint256 i; i < n; ++i) {
Venue storage v = p.venues[i];
if (v.status & VENUE_RETIRED != 0) continue;
if ((debtSide ? v.pair : v.debt) != key || (!debtSide && v.managedSupplyShares == 0)) continue;
used += debtSide ? v.account.debtOf(v.id) : read(v).recognizedSupplied;
}
return cap > used ? cap - used : 0;
}
/// @dev The Router's bounds a post or a withdrawal can move (threshold, debt room, rate, health at the pin), and
/// all `fund` re-checks: the pause flag it was handed, the switches and drawn set no leg writes, and a venue
/// oracle no leg moves stay as its plan checked them within the call (`IMMRouter.setFundRecheck`). The venue's
/// cash is not read: its borrow reverts on a shortfall itself, and the plan and the quote size every slice to
/// it. `debt` and `coll`: the venue's position as its caller read it (`position`), after any post of its own.
function requireSliceFits(Pair storage pr, Venue storage v, uint256 debt, uint256 coll, uint256 assets, uint256 price)
internal
view
{
if (overPinned(pr, v)) revert IMMRouter.VenueOverPinned();
if (v.debtCap != 0 && debt + assets > v.debtCap) revert IMMRouter.DebtCapExceeded();
requireRate(v, assets);
// Where collateral accrues, a post's two roundings can keep one unit's assets and one: every borrow allows it.
if (uint256(v.capabilities) & CAP_ACCRUING_COLLATERAL != 0) coll += v.account.collateralUnitsToAssets(v.id, 1) + 1;
if (debt + assets > maxDebtAtPin(pr, coll, price)) revert IMMRouter.Unhealthy();
}
/// @dev Supply delta zero on purpose: `fund` has already executed its withdrawals (`refinanceDebt` makes none), so
/// the plan's delta would count twice and refuse the slice `buildPlan` approved.
function requireRate(Venue storage v, uint256 assets) internal view {
if (v.maxBorrowRateWad == 0) return;
(bool ok, uint256 rate) = v.account.borrowRateAfter(v.id, assets, 0);
if (!ok || rate > v.maxBorrowRateWad) revert IMMRouter.RateCeiling();
}
/// @dev Reverts `GlobalPaused` while paused, `VenueDisabled` with the venue's supply switch off and
/// `SupplyCapExceeded` past {supplyRoom}.
function requireSuppliable(Venue storage v, bool paused, uint256 assets) internal view {
if (paused) revert IMMRouter.GlobalPaused();
if (!v.supplyEnabled) revert IMMRouter.VenueDisabled();
if (assets > supplyRoom(v)) revert IMMRouter.SupplyCapExceeded();
}
/// @dev The supply the venue takes now: the lesser of the room under its cap in the Router and what a kind that
/// caps or gates supply reports; unbounded with neither.
function supplyRoom(Venue storage v) internal view returns (uint256 room) {
room = type(uint256).max;
if (v.supplyCap != 0) {
uint256 sup = read(v).recognizedSupplied;
room = v.supplyCap > sup ? v.supplyCap - sup : 0;
}
// The venue's own cap and a refused supply, for a kind that reports either.
if (uint256(v.capabilities) & (CAP_PROTOCOL_CAPS | CAP_ACTION_GATES) != 0) {
uint256 venueRoom = v.account.suppliable(v.id);
if (venueRoom < room) room = venueRoom;
}
}
/// @dev A leg over the venue's recognized supply is refused, unless `leg` (the pool's own withdrawal by id,
/// `IMMRouter.withdrawSupplied`, whose leg a flow may size from a read that an earlier leg's rounding at the
/// same market has since lowered) and {_sharedSupplyRounding} allows it; a migration's never is. `assets` at
/// `type(uint256).max` withdraws every recognized share, by shares; with none it withdraws nothing.
function withdrawSupplied(PoolRecord storage p, Venue storage v, uint256 assets, address to, bool leg)
internal
returns (uint256 withdrawn)
{
if (assets == type(uint256).max) {
uint256 shares = managedShares(v);
if (shares == 0) return 0;
return withdrawTracked(v, 0, shares, to);
}
uint256 rec = recognizedSupplied(v);
if ((assets == 0 || assets > rec) && !(leg && _sharedSupplyRounding(p, v, assets, rec))) {
revert IMMRouter.InsufficientLiquidity(assets);
}
return withdrawTracked(v, assets, 0, to);
}
/// @dev The withdrawal and its tracker, once the caller has bounded it by the recognized supply (`fund`: its plan,
/// same call, same state; `addVenue` keeps (account, id) unique, so another venue's leg cannot move it).
function withdrawTracked(Venue storage v, uint256 assets, uint256 shares, address to) internal returns (uint256 withdrawn) {
uint256 burned;
(withdrawn, burned) = v.account.withdraw(v.id, assets, shares, to);
v.managedSupplyShares = _less(v.managedSupplyShares, burned);
}
/// @dev Retirement emptiness: no raw debt, whether or not the venue sits in an order (a retired venue leaves them,
/// and its slot reads nothing again), no recognized collateral and no recognized supplied assets, so a
/// third-party gift cannot block retirement. Supply counts in assets, as {read}'s recognized supply and the
/// emptiness `book` reports do: the share dust a full withdrawal leaves on the tracker, worth no asset and
/// past any withdrawal's reach, is none.
function holdsNothing(Venue storage v) internal view returns (bool) {
(uint256 supplyShares, uint256 borrowShares, uint256 collateral) = v.account.positionOf(v.id);
if (borrowShares != 0 || (collateral != 0 && v.managedCollateralUnits != 0)) return false;
uint256 managed = supplyShares < v.managedSupplyShares ? supplyShares : v.managedSupplyShares;
return managed == 0 || v.account.supplySharesToAssets(v.id, managed) == 0;
}
/// @dev The supply shares the Router recognizes: its tracker, at most the shares the venue holds.
function managedShares(Venue storage v) internal view returns (uint256) {
(uint256 actual,,) = v.account.positionOf(v.id);
return actual < v.managedSupplyShares ? actual : v.managedSupplyShares;
}
/// @dev Those shares' worth at the venue, in assets.
function recognizedSupplied(Venue storage v) internal view returns (uint256) {
return v.account.supplySharesToAssets(v.id, managedShares(v));
}
/// @dev Of `collateral` (assets), what the Router posted: all of it up to the units it posted, so accrual on
/// its own collateral counts and a donation never does. Where collateral accrues, the units it posted are
/// valued at the accrued state: the position's collateral is its units' value there, by a conversion that
/// never falls as units grow (`IFinancingAccount` ADMISSION), so the lesser of the two is what they hold.
function recognizedFrom(Venue storage v, uint256 collateral) internal view returns (uint256) {
uint256 managed = v.managedCollateralUnits;
if (managed == 0) return 0;
if (uint256(v.capabilities) & CAP_ACCRUING_COLLATERAL != 0) {
managed = v.account.collateralUnitsToAssets(v.id, managed);
}
return collateral < managed ? collateral : managed;
}
/// @dev The collateral tracker less what a release burned ({_less}).
function burnUnits(Venue storage v, uint256 units) internal {
v.managedCollateralUnits = _less(v.managedCollateralUnits, units);
}
/// @dev A tracker less what a leg burned of it, floored at zero: what the leg burned past the tracker was no
/// venue's own (a gift's).
function _less(uint128 managed, uint256 burned) private pure returns (uint128) {
return burned > managed ? 0 : managed - uint128(burned);
}
/// @dev The collateral tracker plus what a post minted; a tracker past 2^128 - 1 reverts.
function mintUnits(Venue storage v, uint256 units) internal {
v.managedCollateralUnits = SafeCast.toUint128(v.managedCollateralUnits + units);
}
/// @dev The supply tracker plus what a supply minted; a tracker past 2^128 - 1 reverts.
function mintShares(Venue storage v, uint256 shares) internal {
v.managedSupplyShares = SafeCast.toUint128(v.managedSupplyShares + shares);
}
/// @dev Recognized collateral above the requirement at {releaseLtv}, at the venue's pair's price, and at most what
/// the venue lets go of now ({releasable}); zero if indebted and the pair is unchecked (either USD price
/// zero), out of band, or with its threshold at or under the gap. `guarded`, as {reclaim} reads it: a band
/// read that fails with under an eighth of the gas it began with left reverts `VenueReads.ReadStarved`, as
/// the one kind that answers a starved read as unreadable (`MorphoBlueAccount`) would let the caller's limit
/// skip the venue.
function freeCollateral(PoolRecord storage p, Venue storage v, uint256[] calldata usd, bool guarded)
internal
view
returns (uint256)
{
Read memory rd = read(v);
uint256 free = rd.recognizedCollateral;
if (rd.debt != 0) {
Pair storage pr = p.pairs[v.pair];
uint256 price = priceOf(pr, usd);
uint256 g = gasleft();
if (price == 0 || !bandOk(pr, v, price)) {
if (guarded && gasleft() < g / 8) revert VenueReads.ReadStarved();
return 0;
}
uint256 ltv = releaseLtv(pr, v);
if (ltv == 0) return 0;
uint256 required = requiredCollateral(ltv, rd.debt, price);
uint256 over = rd.collateral > required ? rd.collateral - required : 0;
if (over < free) free = over;
}
uint256 rel = releasable(v);
return free < rel ? free : rel;
}
/// @dev Whether the venue allows `action` now: always, for a kind that never refuses one (a refusing venue is
/// skipped, never written down); read for that action alone where the account answers `IActionsOf`.
function canAct(Venue storage v, uint8 action) internal view returns (bool) {
if (uint256(v.capabilities) & CAP_ACTION_GATES == 0) return true;
uint8 allowed = v.actionsOf ? IActionsOf(address(v.account)).actionsOf(v.id, action) : v.account.actions(v.id);
return allowed & action != 0;
}
/// @dev Whether the venue's legs can move other venues' cash and rate, and theirs its own: one reserve behind them.
function sharesCash(Venue storage v) internal view returns (bool) {
return uint256(v.capabilities) & CAP_SHARED_LIQUIDITY != 0;
}
/// @dev What the venue lets this position release now: unbounded for a kind that neither lends collateral, refuses
/// a release nor reads its oracle on a release at zero debt, else as its account reports it, owing or not.
/// Every release the Router asks for is bounded by it (`withdrawCollateral`, `reclaim` through
/// {freeCollateral}, a refinance's move), so it never asks a venue for more than it reports it can release;
/// the venue's own health check on an indebted release still stands.
function releasable(Venue storage v) internal view returns (uint256) {
if (uint256(v.capabilities) & (CAP_LENT_COLLATERAL | CAP_ACTION_GATES | CAP_PRICED_RELEASE) == 0) {
return type(uint256).max;
}
return v.account.collateralReleasable(v.id);
}
/// @dev `withdrawCollateral`'s proportional proof where the exact one fails: the release stands if the venue's
/// collateral accrues, the same transaction's repay lowered the debt and the collateral that stays is short of
/// its exact share by no more than {RELEASE_SLACK} of debt and {_roundingSlack} of collateral allow. It reads
/// the debt, the collateral and the repay's snapshot again, in the same state, so the exact proof's passing
/// path, which every release at an indebted venue takes, keeps none of them for it. Where collateral does not
/// accrue the allowance is zero and the exact proof's refusal stands.
function _requireSharedRounding(PoolRecord storage p, Venue storage v, uint16 id, uint256 assets) private view {
if (uint256(v.capabilities) & CAP_ACCRUING_COLLATERAL == 0) revert IMMRouter.Unhealthy();
(uint256 debtBefore, uint256 collBefore) = repaySnapshot(msg.sender, id);
IFinancingAccount a = v.account;
bytes32 vid = v.id;
uint256 debt = a.debtOf(vid);
// A repay that lowered nothing earns no allowance.
if (debt >= debtBefore) revert IMMRouter.Unhealthy();
uint256 held = debt > RELEASE_SLACK ? debt - RELEASE_SLACK : 0;
uint256 slack = _roundingSlack(p, a.collateralUnitsToAssets(vid, 1), v.coll, assets);
if (held * collBefore > debtBefore * (a.collateralOf(vid) - assets + slack)) revert IMMRouter.Unhealthy();
}
/// @dev Whether `IMMRouter.withdrawSupplied` takes a leg over the venue's recognized supply, read only where the
/// leg is over it (or zero): it does if the venue's units accrue at a market other positions hold, it
/// recognizes some supply, and the leg is over it by no more than {_roundingSlack} of the token. The venue's
/// own units then pay it, the market's rounding the rest, as a redemption by amount burns the units it gives
/// rounded down. It takes the recognized supply its caller read (`rec`), so a leg reads it once.
function _sharedSupplyRounding(PoolRecord storage p, Venue storage v, uint256 assets, uint256 rec)
private
view
returns (bool)
{
if (rec == 0 || assets == 0 || uint256(v.capabilities) & CAP_ACCRUING_COLLATERAL == 0) return false;
return assets <= rec + _roundingSlack(p, v.account.supplySharesToAssets(v.id, 1), v.debt, assets);
}
/// @dev What a leg at a venue whose units accrue may ask past what its exact proof allows (a release) or what the
/// venue recognizes (a supply withdrawal): a market whose rate takes every holder's rounding.
/// - A redemption by amount burns the units it gives rounded down (Compound-style), so the market pays up to a
/// unit's worth over what it burns, out of every other position's units, the pool's other venues at that
/// market among them.
/// - A pool's flow sizes its legs from one read before its first, so the exact share of a later venue's
/// position, asked after an earlier leg moved that rate, is a little over what the venue now gives it.
/// - An exit moves a market at most once for each other venue (a venue posts the token there or lends it, not
/// both), each time taking under one unit's worth, rounded up, off this venue's units, which are part of
/// that market.
///
/// So the slack is:
/// - one unit's worth (`unit`, read from the kind) and one, for each venue of the pool;
/// - never more than a millionth of one whole token `token` and one, so a rate raised by a donation cannot
/// widen it;
/// - never more than four base units and a millionth of the leg (`assets`), as a migration may lose: rounding
/// beside the leg, so a flow that repeats a repay and a release gains four base units a cycle at most, as
/// {RELEASE_SLACK} lets it gain four units of debt's worth.
///
/// The allowance answers no particular sibling leg: at a kind whose rate no other position's leg moves (Aave's
/// index), it widens the proof by rounding alone, which the last bound holds to four base units and a
/// millionth of the leg.
function _roundingSlack(PoolRecord storage p, uint256 unit, uint8 token, uint256 assets)
private
view
returns (uint256 slack)
{
uint256 most;
// A listed token has at most 18 decimals, and `unit` under `most` (at most 1e12 + 1) and one, for each of at
// most `MAX_VENUES`, fits a word: no overflow, and no checked power shared with the price scale.
unchecked {
most = 10 ** uint256(p.tokens[token].decimals) / MIGRATION_LOSS_DIVISOR + 1;
if (unit < most && (unit + 1) * p.venues.length < most) most = (unit + 1) * p.venues.length;
}
slack = RELEASE_SLACK + assets / MIGRATION_LOSS_DIVISOR;
if (slack > most) slack = most;
}
/// @dev `price` is in the venue's price scale: debt base units per collateral base unit, scaled by 1e36.
function maxDebtAtPin(Pair storage pr, uint256 collateral, uint256 price) internal view returns (uint256) {
return maxDebtAt(pr.pinLtvWad, collateral, price);
}
/// @dev The most debt `collateral` carries at `ltvWad` and `price`, both steps rounded down, so the debt stays
/// within the LTV.
function maxDebtAt(uint256 ltvWad, uint256 collateral, uint256 price) internal pure returns (uint256) {
return Math.mulDiv(Math.mulDiv(collateral, price, ORACLE_PRICE_SCALE), ltvWad, WAD);
}
/// @dev The least collateral that carries `debt` at `ltvWad` and `price`, both steps rounded up, so the debt stays
/// within the LTV; neither `ltvWad` nor `price` may be zero.
function requiredCollateral(uint256 ltvWad, uint256 debt, uint256 price) internal pure returns (uint256) {
uint256 value = Math.mulDiv(debt, WAD, ltvWad, Math.Rounding.Up);
return Math.mulDiv(value, ORACLE_PRICE_SCALE, price, Math.Rounding.Up);
}
/// @dev The LTV a priced release may leave an indebted venue at: its pair's pin, or the venue's threshold less the
/// pair's gap once that is lower (zero at or under the gap), so a release never takes the venue past what its
/// lender now allows. Only a mutable threshold can fall under the pin plus the gap while the venue owes: the
/// pin rises only within the pair's `minLltv`, which counts every indebted venue of the pair, and an
/// over-pinned venue borrows nothing.
function releaseLtv(Pair storage pr, Venue storage v) internal view returns (uint256 ltv) {
ltv = pr.pinLtvWad;
if (uint256(v.capabilities) & CAP_MUTABLE_THRESHOLD == 0) return ltv;
uint256 t = v.account.lltv(v.id);
uint256 gap = pr.safetyGapWad;
if (t < ltv + gap) ltv = t > gap ? t - gap : 0;
}
/// @dev The pair's price and the venue's oracle speak the same price scale, so they compare directly. A zero band
/// is off: no venue oracle is read and only a zero price fails.
function bandOk(Pair storage pr, Venue storage v, uint256 price) internal view returns (bool) {
uint256 band = pr.oracleBandWad;
if (band == 0) return price != 0;
(bool ok, uint256 oracle) = v.account.oraclePrice(v.id);
if (!ok || price == 0) return false;
uint256 dev = oracle > price ? oracle - price : price - oracle;
return dev <= Math.mulDiv(price, band, WAD);
}
/// @dev The venue's threshold is below its pair's pin plus the pair's gap: a lender cut it after the checks, or its
/// borrowing is off and it owes nothing, which neither its admission nor a pin rise checks. It lends nothing
/// while it stays there (a lower pin ends it, as does a raise of a threshold that can move), and a priced
/// release of an indebted venue whose threshold can fall stops at the threshold less the gap.
function overPinned(Pair storage pr, Venue storage v) internal view returns (bool) {
return threshold(v) < uint256(pr.pinLtvWad) + pr.safetyGapWad;
}
/// @dev The venue's threshold now: read from the account for a kind whose threshold can fall, else the one
/// registered at admission.
function threshold(Venue storage v) internal view returns (uint256) {
return uint256(v.capabilities) & CAP_MUTABLE_THRESHOLD != 0 ? v.account.lltv(v.id) : v.lltvWad;
}
/// @dev The pre-repay (debt, collateral) of a venue, kept in transient storage so a proportional collateral
/// withdrawal in the same transaction can prove it does not worsen the venue without a price; one read of its
/// position, whose debt the repay pays at most.
function snapshotForProportional(Venue storage v, uint16 id) internal returns (uint256 debt) {
uint256 coll;
(coll,,, debt) = v.account.position(v.id);
_snapshot(id, debt, coll);
}
/// @dev `position` answers the same (debt, collateral) as `debtOf` and `collateralOf` in one state. The slot is
/// the pool's address over the venue id ({repaySnapshot}).
function _snapshot(uint16 id, uint256 debt, uint256 coll) private {
uint256 slot = (uint256(uint160(msg.sender)) << 16) | id;
uint256 packed = (debt << 128) | coll;
assembly ("memory-safe") {
tstore(slot, packed)
}
}
/// @dev Pool `pool`'s snapshot of venue `id`, at transient slot `pool << 16 | id`: distinct pools and ids give
/// distinct slots, all at or past 2^16, so none is the reentrancy guard's slot zero.
function repaySnapshot(address pool, uint16 id) internal view returns (uint256 debt, uint256 coll) {
uint256 slot = (uint256(uint160(pool)) << 16) | id;
uint256 packed;
assembly ("memory-safe") {
packed := tload(slot)
}
debt = packed >> 128;
coll = packed & type(uint128).max;
}
}
src/core/mm/VenueReads.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The guarded read a venue kind takes of a protocol that may not answer (`IFinancingAccount` ADMISSION): a
/// static call of bounded gas whose failure reads as unreadable, never as a revert, unless the caller left it
/// short of its budget. Lista Moolah (`MoolahAccount`) reads through it, Aave V3 (`AaveV3Account`) its rate
/// strategy, the Router a venue's minimums (`MMRouterLib._underMinimum`), and every kind that fences its reads
/// reverts its `ReadStarved`.
library VenueReads {
/// @notice A guarded read failed, and the call had too little gas on hand to tell a protocol that cannot answer
/// from a read starved of gas.
error ReadStarved();
/// @dev `data` sent to `target` as a static call with at most `budget` gas: `ok == false` on a revert, no code or
/// an answer under `words` words, which {word} reads until the next call. A read that fails with too little
/// gas on hand to forward `budget` in full may have failed for want of gas: it reverts `ReadStarved` rather
/// than read the venue as unreadable, so no caller makes it look frozen by starving it. Not `try`/`catch`: its
/// decode would revert in this call.
function peekData(uint256 budget, address target, bytes memory data, uint256 words)
internal
view
returns (bool ok)
{
uint256 g = gasleft();
assembly ("memory-safe") {
ok := staticcall(budget, target, add(data, 0x20), mload(data), 0, 0)
if lt(returndatasize(), shl(5, words)) { ok := 0 }
}
if (!ok && g < budget + budget / 63 + 5_000) revert ReadStarved();
}
/// @dev Word `i` of the last call's answer.
function word(uint256 i) internal pure returns (uint256 v) {
assembly ("memory-safe") {
returndatacopy(0, shl(5, i), 0x20)
v := mload(0)
}
}
}
src/interfaces/core/flamm/IFLAMM.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {PoolContext} from "src/interfaces/core/flamm/IFLAMMHooks.sol";
import {PairRequest} from "src/interfaces/core/flamm/IPairHook.sol";
/// @notice The external surface of a pool that periphery, the Router, the Factory and the tranches rely on, and the
/// entries `FLAMMFront` serves or routes (`swap`, `previewSwap`, `pairRequest`, `switches`, `paused`,
/// `tokenConfig`, `pairConfig`, `position`, `collateralReserve`, `pending`, `poke`, `recenter`). The pool lists
/// tokens: token 0 is `asset()`, the share and NAV unit, and token 1 is `loanAsset()`, the numeraire and the
/// hook pair's quote; its credit pairs each borrow a debt token against a collateral token. Entries no contract
/// calls through it (the hook-set ceremony and its view, the governance setters, the admissions,
/// `maintainCollateral`, `maintain`, `emergency`, `executePerformanceFee`) are declared and documented on
/// `FLAMM` alone, and those `FLAMM`'s fallback hands to `FLAMMFloatLib` (the cheap lane's settings,
/// `collectSpreadFee`, the float actions) on that library. The fences' entries are on `IFLAMMFence`, the
/// front's on `IFLAMMLane`.
/// @dev FLAMM stands for financed-leg automated market maker. Who calls whom:
/// - `FLAMMFactory` creates pools for anyone, is their beacon and constructs the one shared `MMRouter`.
/// - A pool is a `FLAMMProxy` over `FLAMMFront`, the Factory's implementation, which hands every entry it does
/// not serve to `FLAMM` and its libraries. The pool keeps the custody, the shares and the pool book.
/// - `MMRouter` (`IMMRouter`) keeps each pool's pairs and venues, takes each pool's calls for its own alone and
/// drives the pool's financing accounts. It never holds a token.
/// - A financing account (`IFinancingAccount`) carries a pool's legs at one lender, a venue kind being one
/// lender's code. The Router calls its normal path and its pool calls the emergency path.
/// - `PriceFeed` (`IPriceFeed`) serves the checked USD prices the pool reads; the Router reads no feed, but takes
/// each price from the pool's call (`usd`).
/// - `core()` (`IEverlongCore`: an `EverlongCore`, or a `DelayedAuthority`, which puts delays on its owner and
/// guardian) names the pool's roles.
/// - The swap hook (`hooks().hook`: `IPairHook`, `IRecenterHook`) prices every pair but a pair hook's; a pair hook
/// (the `setPairHook` slot) prices its own pairs; the controller (`hooks().controller`) holds a routing role.
/// - A PropAMM front (`IPropAMMFront`) is the swap hook of a pool with a cheap lane, for the pool's life, and
/// settles fills through `IFLAMMLane`. The doors in `src/periphery/door` take routers' fills to the front.
///
/// Terms:
/// - Hook pair: tokens 0 and 1, {asset} and {loanAsset}.
/// - Credit pair: a debt token borrowed against a collateral token at venues ({PairConfig}, `IMMRouter`).
/// - Cheap lane: a fill the front prices and the pool settles from tracked custody, never touching the lender
/// (`IFLAMMLane`), on a pool whose front opened it at birth and whose curator set `FEATURE_CHEAP_FILL`. A pool's
/// cheap lane is on from that birth for good (`SWAP_LANE`), whatever `FEATURE_CHEAP_FILL` says; that bit opens
/// and stops its fills.
/// - Credit path: the pool's own {swap} through the swap hook.
/// - The four legs of a token ({position}): held (custody, unlent), supplied (lent at a venue), posted (collateral
/// at a venue) and owed (borrowed from a venue).
/// - Curator: the owner of `core()`, the role `src/propamm` and `src/periphery/door` call the operator.
/// - Guardian: `core()`'s second key, which cancels scheduled changes, tightens settings and calls the emergency
/// path (`FLAMM`).
/// - Keeper: `core()`'s operations key, which moves dials and runs maintenance beside the curator (`FLAMM`).
/// - D: `governanceDelaySec`, the pool's delay, written once at birth ({switches}).
/// - `EverlongHook`: the canonical swap hook, bound to one pool, which carries the Everlong curve and the pool's
/// leverage quote.
/// - Venue fence and price fence are unrelated: core's fence sets a venue or a token's custody apart from the pool
/// (`IFLAMMFence`); the front's price fence holds a fill's levels within a one-sided limit taken from the price
/// its listing is fenced to, where the listing has one (`IPropAMMFront`).
interface IFLAMM is IERC20 {
/// @notice The custody maintenance moves. DO NOT REORDER: the values are part of the ABI; a new member needs a
/// branch in `FLAMMMaintainLib.maintain`.
enum MaintainKind {
TopUp,
Release,
Refinance,
MigrateSupply,
/// `Refinance` with the caller lending what custody cannot bridge: the caller needs an allowance to the pool
/// for this transaction, for at most the move, and is repaid in full in it (`FLAMMMaintainLib.maintain`).
FundedRefinance
}
/// @notice The emergency path's moves. DO NOT REORDER: the values are part of the ABI; a new member needs a
/// branch in `FLAMMMaintainLib.emergency`.
enum EmergencyKind {
Repay,
/// At a fenced venue the post is the curator's alone and pulls part of it from the caller in the venue's
/// collateral token, within the caller's allowance to the pool (`FLAMMMaintainLib.emergency`).
TopUp,
WithdrawSupplied,
WithdrawCollateral
}
/// @dev The pool's hooks: the swap hook, one contract in every pricing role (it prices every pair but a pair
/// hook's, and its own fee, and recenters the pool book it prices), and the optional controller.
struct HookSet {
address hook; // the swap hook (`IPairHook`), which prices every pair but a pair hook's
address controller; // routing role (`setPriorities`, `maintain`, `recenter`, `unwindFence`); zero: none
}
/// @notice A venue of credit pair `pair` (the Router's pair index), as `FLAMM.addVenue` admits it.
struct VenueInit {
uint8 kind; // the venue kind, one lender
uint8 pair; // the Router's pair index
bytes venueParams; // the kind's parameters (`IMMRouter.addVenue`)
bool borrowEnabled; // the venue's borrow switch
bool supplyEnabled; // the venue's supply switch
uint128 debtCap; // the venue's debt cap, debt-token base units; zero: none
uint128 supplyCap; // the venue's supply cap, debt-token base units; zero: none
uint64 maxBorrowRateWad; // the highest borrow rate a borrow there may leave, per second, WAD; zero: none
}
/// @notice One venue's leg of a pro-rata flow, in the venue's own tokens: `collateral` of its pair's collateral
/// token, `owed` and `supplied` of its debt token.
struct VenueLeg {
uint16 id; // the venue's slot at the Router
uint8 pair; // its credit pair's index
uint256 collateral; // base units
uint256 owed; // base units
uint256 supplied; // base units
}
/// @notice One listed token: its binding, its swap policy, its lending policy and its custody. `partner` is the
/// token whose collateral backs a debt in this one, the collateral of the credit pair `pairId` that owes
/// it (`255`: no live pair owes it; `254`: two or more do, `pairId` the first of them); `debtFree` its
/// proven debt-free flag. `pairId` means something only while `partner` is not `255`: it reads zero for a
/// token no pair ever owed, and keeps the retired pair's index after `FLAMMAdmitLib.retirePair`.
struct TokenConfig {
address token; // the token's address
uint8 decimals; // at most 18
uint64 swapPriceBandWad; // how far a fill may stray from the feed, WAD; token 1's is the market band
uint64 feeFloorWad; // the least fee rate a swap of this token takes, WAD
uint256 maxSwapNotional; // the most of it one swap takes or pays, base units; zero: none
uint256 reserveTarget; // the custody a swap keeps unlent and a refill brings back, base units
uint256 minSupplyBatch; // the least surplus over the target a swap lends, base units; `max`: it lends none
uint256 held; // the custody tracked, the fee kept for the protocol included, base units
uint8 partner; // see above
uint8 pairId; // see above
bool debtFree; // a position read showed no unfenced venue lending it to the pool; a draw clears it
}
/// @notice One credit pair, which borrows `debt` against `coll`: its two dials (the LTV, which is the Router's pin,
/// and the credit `phiWad` of incoming collateral when a borrow's room is sized), the room's shave, the
/// dials' write-once envelope, step, structural floor and cooldown, its last dial move, the pool's mirror
/// of its borrow switch and whether it is live (not retired). The credit is at most `1 / (1 + band)` of the
/// pair's tokens' tighter swap band, as a fill inside the band may bring an input worth as little as that
/// share of its output: the admission caps the dial there, a dial move inside the envelope stores at most
/// that as the band stands (never below the envelope's floor), and a draw's or a rotation's room credits no
/// more however the band moves since.
struct PairConfig {
uint8 coll; // the collateral token's index
uint8 debt; // the debt token's index
uint64 ltvWad; // the LTV dial, the Router's pin, WAD
uint64 phiWad; // the credit dial, WAD
uint64 roomEpsilonWad; // the share taken off the room once the credit has lifted it, WAD
uint64 ltvMinWad; // the LTV dial's floor, WAD, write-once
uint64 ltvMaxWad; // the LTV dial's ceiling, WAD, write-once
uint64 phiMinWad; // the credit dial's floor, WAD, write-once
uint64 phiMaxWad; // the credit dial's ceiling, WAD, write-once
uint64 ltvMaxStepWad; // the most one raise moves the LTV dial, WAD
uint64 minStructDistWad; // the least `1 - ltv / lltv` a raise of the LTV leaves, WAD
uint32 ltvCooldownSec; // the seconds a dial move waits after the last one
uint48 lastDialMoveTs; // when the dials last moved, unix seconds; the pair's admission counts as a move
bool borrowOff; // the pool's mirror of the Router's borrow switch for the pair: true when it is off
bool live; // false once retired, for good
}
/// @notice The pool's caps, guards and fee policy in one read.
struct Limits {
uint32 maxPriceAgeSec; // the oldest USD print a swap past the hook pair prices on, seconds; zero: none trades
uint64 feeFloorWad; // the pool's fee floor, WAD; a swap takes the highest of this and its two tokens'
uint64 feeCapWad; // the highest fee rate (`feeWad`) a hook's fill may report, WAD; not a bound on its `feeOut`
/// @dev The curator's rate, charged on the gain over the high-water mark at the pre-mint share price, in
/// minted shares, so the receiver realises bp of the gain diluted by the mint; the rest stays with LPs,
/// never recharged. A rise waits `governanceDelaySec`, and none lands while the pool has no market band; a
/// cut applies at once.
uint16 performanceFeeBp;
/// @dev The high-water mark of the unrealised NAV per share (pool-asset base units per share, WAD), rounded
/// down from the pool's own fee mark, which it carries at 18 decimals of par whatever the pool asset.
/// Seeded at bootstrap and only ever raised, also while both rates are 0, so a fee armed later starts from
/// it. A charged gain is never refunded. On a pool whose cheap lane is on and whose deposit basket is set
/// (`basketTokens()`, every token's entry), it is instead the high-water mark of NAV per share against the
/// basket's value at the same prices, a WAD ratio (the pool carries it times the share scale, as it
/// carries every fee mark): each record of the basket restarts it at 1e18, and only gains above it raise
/// it.
uint128 peakSharePriceWad;
uint16 maxPerformanceFeeBp; // the curator rate's cap, bp, write-once
/// @dev The protocol's rate, charged on the same gain beside the curator's, in shares minted to the Factory's
/// `protocolFeeReceiver`; the Factory sets it, a rise after the longer of its `UPGRADE_DELAY` and ten days
/// and, once the pool is seeded, only while it has a market band.
uint16 protocolFeeBp;
/// @dev The curator's scheduled rise and when anyone may execute it (`executePerformanceFee`); zero when none.
uint16 pendingPerformanceFeeBp;
uint48 performanceFeeExecutableAt; // unix seconds
/// @dev The supply `FLAMM.mintProRata` may lift the pool to, in shares (zero closes that entry).
uint256 mintProRataCap;
}
// identity
/// @notice Token 0: the pool asset, the share and NAV unit.
function asset() external view returns (address);
/// @notice Token 1: the numeraire and the token every periphery binding uses.
function loanAsset() external view returns (address);
/// @notice The tokens the pool lists, the pool asset included.
function tokenCount() external view returns (uint256);
/// @notice The credit pairs the pool holds, retired ones included.
function pairCount() external view returns (uint256);
/// @notice Token `t`'s record ({TokenConfig}); reverts `BadTokenIndex` past the list.
function tokenConfig(uint8 t) external view returns (TokenConfig memory);
/// @notice Pair `p`'s record ({PairConfig}); reverts `BadPairIndex` past the list.
function pairConfig(uint8 p) external view returns (PairConfig memory);
/// @notice Token `t`'s collateral reserve rule (`FLAMMPolicyLib.setCollateralReserve`); `BadTokenIndex` past the list.
/// @param t The token's index.
/// @return venueId The venue the rule names, zero while it is off.
/// @return reserve The custody a release refills up to, in token `t`'s base units, zero while the rule is off.
function collateralReserve(uint8 t) external view returns (uint16 venueId, uint128 reserve);
/// @notice When the pending table's entry `h` may execute, `h` being the keccak256 of the scheduled call (its
/// selector and arguments abi-encoded as one tuple): an admission (`FLAMM.addToken`, `addPair`,
/// `addVenue`), a fence's delayed call (`writeOff`, `abandonFence`, `liftFence`, `liftToken`), the pair
/// hook's installation, a fee floor's cut (`setFeeBounds`, `setTokenConfig`) on a pool whose cheap lane is
/// off, and a cap's raise on one whose lane is on. Zero when none, as once its window has lapsed
/// (past `dueAt` by `governanceDelaySec` or one day, whichever is longer): the identical call then schedules it again.
function pending(bytes32 h) external view returns (uint48 dueAt);
/// @notice The money-market Router (`IMMRouter`) that holds the pool's venues.
function router() external view returns (address);
/// @notice The USD price feed (`IPriceFeed`).
function priceFeed() external view returns (address);
/// @notice The pool's roles (`IEverlongCore`): its curator, guardian, keeper and fee receiver.
function core() external view returns (address);
/// @notice The allowlist that decides who may receive an entry's shares (`IDepositAllowlist`); zero: anyone.
function depositAllowlist() external view returns (address);
/// @notice The Factory, the pool's beacon.
function factory() external view returns (address);
/// @notice The pool's hooks ({HookSet}).
function hooks() external view returns (HookSet memory);
/// @notice Whether the pool is paused (`FLAMM.setPaused`).
function paused() external view returns (bool);
// facts
/// @notice Token `t`'s four legs, as the Router's `book` recognizes them (a retired venue holds none, and a fenced
/// one's stay out of that `book`); reverts `BadTokenIndex` past the list.
/// @dev `held` is less than {tokenConfig}'s `held` by the fee kept for the protocol, which that record counts.
/// @param t The token's index.
/// @return held The custody the pool owns, the fee kept for the protocol left out, in base units.
/// @return supplied What the pool lends at its venues, in base units.
/// @return posted What the pool posts as collateral at its venues, in base units.
/// @return owed What the pool owes at its venues, in base units.
function position(uint8 t) external view returns (uint256 held, uint256 supplied, uint256 posted, uint256 owed);
/// @notice NAV in pool-asset base units at the pool's checked prices: every token's held, supplied and posted legs
/// less its owed one, the pool asset at par and every other token at its checked price, holdings rounded
/// down and debt up, never below zero.
/// @dev Reverts:
/// - `PriceUnchecked` while a token with a position has an unchecked feed.
/// - `PriceUnchecked`, while a fee rate is on and the pool has a band, while the fee mark cannot read, held or
/// not: a cheap-lane pool's deposit basket needs token 1's price, and a pending record of what exits
/// forfeited at frozen venue marks needs its tokens' prices (so nothing priced at NAV trades a fee the skim
/// could not charge).
/// - `VenueFrozen` while a live venue holding a position allows no action, its kind one that can refuse one
/// (`CAP_ACTION_GATES`): such a kind answers a frozen venue mark while its protocol cannot be read
/// (`IFinancingAccount`). A lender that refuses every action while still readable reads the same way, which
/// is conservative. No flow enters at its figures (`VenueFrozen`), and an exit forfeits its slice of such a
/// venue that owes nothing ({redeemProRata}), which no skim counts as performance.
function totalAssets() external view returns (uint256);
/// @notice The pool-wide policy ({Limits}); per-token and per-pair policy live on {tokenConfig} and {pairConfig}.
function limits() external view returns (Limits memory);
/// @notice A cheap-lane pool's deposit basket per 1e18 shares: its first two entries, the pool asset's net legs and
/// token 1's (`FLAMMFloatLib.basket`); zero on any other pool. A basket holds every token's entry
/// ({basketTokens}), against whose whole value `Limits.peakSharePriceWad` is NAV per share.
/// @return basketPool The pool asset's entry, in its base units.
/// @return basketLoan Token 1's entry, in its base units.
function basket() external view returns (uint128 basketPool, uint128 basketLoan);
/// @notice A cheap-lane pool's deposit basket per 1e18 shares, one entry per listed token in its base units
/// (`FLAMMFloatLib.basketTokens`): where it is set, `Limits.peakSharePriceWad` is NAV per share against the
/// value of every entry; all zero on any other pool.
function basketTokens() external view returns (uint256[] memory entries);
/// @notice The venue slots the pool's walks skip, bit `i` for slot `i`: those it has retired, cleared when an
/// admission reuses the slot, and those it has fenced, cleared at the fence's lift (`IFLAMMFence`, whose
/// `fencedVenues` tells the fenced apart). No walk of the pool's venues calls the Router for one, as a
/// retired venue's lender may have stopped answering and a fenced one's takes no leg.
function retiredVenues() external view returns (uint256);
// ERC-4626 conversions at NAV, excluding fees as ERC-4626 asks: at the supply before a pending performance fee is
// minted, which the pro-rata previews include. No synchronous ERC-4626 path: the pro-rata flows below are the entry
// and exit. Both revert as `totalAssets` does: at an unchecked price or, while a fee rate and a band are on, an
// unread fee mark (`PriceUnchecked`), and at a frozen venue mark (`VenueFrozen`).
/// @notice The shares `assets` of the pool asset buy at NAV, rounded down.
function convertToShares(uint256 assets) external view returns (uint256);
/// @notice The pool-asset base units `shares` are worth at NAV, rounded down.
function convertToAssets(uint256 shares) external view returns (uint256);
// proportional flows: no hook or callback runs on an entry, an exit or a redemption
/// @notice A pro-rata entry sized in the pool asset: exactly `poolAssets` of it, for that share of the pool asset
/// the pool holds, posts and lends, and the same share of every other token's legs, each netted per token:
/// `maxLoanAssetIn` and `minLoanAssetOut` bound tokens 1 onwards, and the entry returns token 1's net in
/// and out.
/// @dev Reverts `BookOwesPoolAsset` while the pool owes its pool asset: such a pool book enters through
/// `mintProRata`.
///
/// Either entry refuses, as its preview does and its maximum reads zero:
/// - `CustodyMismatch` while a spread fee is owed past custody, which no call of the pool's leaves (a guard):
/// no venue draws it, so the entrant's slice would come out of the custody kept for it. The next inflow of
/// the token covers it again; where the token is owed, its debt takes that inflow first, so the entries stay
/// closed until the debt is repaid (with strict mode on, a cheap-lane pool's asks wait for that too).
/// - `BasketNotRecorded` on a pool whose cheap lane is on and whose curator's fee cap is nonzero, until the
/// curator's seed of token 1 records the deposit basket (`seedLeg`), the one basket the fee mark is measured
/// against.
///
/// Either entry also refuses `PriceUnchecked` while a fee rate is on, the pool has a band and the fee mark
/// cannot read ({totalAssets}: a cheap-lane pool's basket needs token 1's price, a pending forfeit record its
/// tokens' prices, held or not), as its skim would charge nothing and the next one the gain on the entrant's
/// shares too; its maximum reads zero there.
///
/// On a pool book that owes:
/// - A borrow leg refuses before the entry pulls anything (`PriceUnchecked` where its pair's price is
/// unchecked, `PegBroken` where one of its tokens is off its peg).
/// - The entry gate, the credit law read once the legs have moved, refuses `PriceUnchecked` where a debt its
/// token's holdings and supply do not cover has no checked price against its collateral, as a dust debt
/// whose slice is no borrow leg can: the maximum reads zero there, and an entrant short of its inputs meets
/// its own pull's error first.
///
/// Refused also `Expired`, `Paused`, `FeatureDisabled` with `FEATURE_DEPOSITS` off, `VenueFrozen` while a
/// fence holds a pool part, `DepositNotPermitted` for a receiver the allowlist refuses, `NotBootstrapped`,
/// `ZeroShares` and `Slippage`; a leg past its bound reverts `TokenInExceeded` or `TokenOutBelowMin`.
/// @param poolAssets The pool asset paid in, in its base units, above zero (`InvalidAmount`).
/// @param receiver The receiver of the shares; net outputs go to the caller.
/// @param maxLoanAssetIn The most of each token paid in, token 1 first, `tokenCount - 1` long (`InvalidAmount`).
/// @param minLoanAssetOut The least of each token paid out, token 1 first, `tokenCount - 1` long (`InvalidAmount`).
/// @param minSharesOut The least shares minted.
/// @param deadline The last unix second it executes.
/// @return shares The shares minted, rounded down.
/// @return loanAssetIn Token 1's net input, in its base units.
/// @return loanAssetOut Token 1's net output, in its base units.
function depositProRata(
uint256 poolAssets,
address receiver,
uint256[] calldata maxLoanAssetIn,
uint256[] calldata minLoanAssetOut,
uint256 minSharesOut,
uint256 deadline
) external returns (uint256 shares, uint256 loanAssetIn, uint256 loanAssetOut);
/// @notice A pro-rata entry sized in shares, on any pool book: exactly `shares`, for that slice of every token's
/// legs, its holdings paid in rounded up and its debt borrowed for the entrant rounded down, netted per
/// token. The arrays are `tokenCount` long, token 0 first.
/// @dev Either entry refuses, and the entry maxima read 0 there:
/// - `IMMRouter.Unhealthy` where its borrow leg would leave a venue past its pin in the collateral the pool
/// recognizes, as its preview does.
/// - `VenueFrozen` at a frozen venue mark ({totalAssets}), whose figures are no price to enter at and whose
/// thaw's first skim would charge the entrant for gains made before it entered.
/// - `PriceUnchecked` while a fee rate is on, the pool has a band and the fee mark cannot read, as
/// `depositProRata` does.
///
/// `mintProRata` also refuses:
/// - Under the same rates and band, `PriceUnchecked` where the share price is past the fee mark's range
/// (`type(uint128).max` at 18 decimals of par).
/// - An unchecked price or a broken peg at its borrow legs and its entry gate, as `depositProRata`'s do.
/// - `DepositCapExceeded` past `Limits.mintProRataCap` on the supply after it.
/// - `Expired`, `Paused`, `FeatureDisabled`, `DepositNotPermitted` and `NotBootstrapped` as `depositProRata`.
/// - `TokenInExceeded` or `TokenOutBelowMin` for a leg past its bound.
/// @param shares The shares to mint, above zero (`InvalidAmount`).
/// @param receiver The receiver of the shares; net outputs go to the caller.
/// @param maxIn The most of each token paid in, in its base units.
/// @param minOut The least of each token paid out, in its base units.
/// @param deadline The last unix second it executes.
/// @return tokenIn Each token's net input, in its base units, token 0 first.
/// @return tokenOut Each token's net output, in its base units, token 0 first.
function mintProRata(
uint256 shares,
address receiver,
uint256[] calldata maxIn,
uint256[] calldata minOut,
uint256 deadline
) external returns (uint256[] memory tokenIn, uint256[] memory tokenOut);
/// @notice A pro-rata exit, price-free and never paused: `shares` of `owner`'s for that slice of every token's
/// legs, its debt repaid by the caller rounded up and its holdings paid to `receiver` rounded down, netted
/// per token. The arrays are `tokenCount` long, token 0 first. A caller other than `owner` spends its
/// allowance. Refused also, past the cases below, `Expired`, `BelowMinimumShares` where the supply left
/// would pass under the dead shares, `TokenInExceeded` and `TokenOutBelowMin` past the bounds, and
/// `ExitWorsensLedger`.
/// @dev A venue that takes less of its repay than asked (a minimum position, a lender's remainder past its market's
/// total borrows):
/// - It releases in proportion to what it took. The rest of the repay nets its debt in custody, which pays the
/// slice the venue keeps posted, or the exit refuses (`CustodyMismatch`) past the dust any exit can leave
/// where custody runs dry.
/// - That dust is the venue's last whole units, bounded at the larger of its pair's safety gap and 1 %, the
/// lenders' rounding and a share under one unit's assets and one, which it releases none of. It stays
/// posted, `minOut` bounds it and the fee mark counts it as forfeited.
/// - A repay that leaves the venue owing nothing holds nothing.
/// - The preview reads no such hold, so it can show an exit this refuses.
/// - The exit maximum reads the holds a kind reports (a minimum position, `IHeldRepay`; a lender's bound,
/// `IRepayable`, one per market, spent across the venues borrowing there in the exit's order), so no exit it
/// advertises refuses for one. At a venue past its threshold whose lender holds the repay of its whole debt
/// short, the remainder can keep the release in proportion past what the lender allows, and the maximum
/// reads zero.
/// - An exit the maximum advertises may pay short of its preview by the dust a held venue leaves: floors taken
/// from the preview, less that dust, hold.
///
/// Dust at a venue that still owes:
/// - It releases nothing under one unit's assets and one, which its kind would release by burning a whole
/// unit: a slice that small stays posted with the venue's last whole units, recorded as dust, whether or not
/// the venue held the repay.
/// - Where the venue held the repay, a share under one unit's assets and one of a larger slice releases none,
/// and custody pays that slice, what it cannot of that share staying posted beside the dust.
///
/// At a venue whose threshold equals its pair's LTV, which reads unhealthy once interest accrues, the maximum
/// reads zero below the size that clears the venue, though smaller exits may execute.
///
/// Haircuts: a slice at a venue whose lender cannot pay all of its face (`IFinancingAccount.haircut`) is paid
/// cut by that share, which stays in custody, so the exiter bears its share of the venue's loss, as NAV does,
/// and the holders who stay none of it. Where the haircut is a fee each redemption pays
/// (`CAP_REDEMPTION_FEE`), the slice leaves net of it instead, so the venue burns the exiter's units and no
/// more. This holds for a loss the venue's kind reports; the comptroller kind (`CTokenAccount`) reports only
/// its lender's redemption fee, as that lender records no bad debt, so there a slice leaves at face and the
/// holders who stay bear the exiter's share of a bad debt the lender has not covered.
///
/// At a frozen venue mark (a venue that allows no action and holds a position):
/// - The exit forfeits its slice of such a venue that owes nothing, or no more than the lenders' rounding
/// (`MMRouterLib.RELEASE_SLACK`, whose share it leaves behind), which stays posted for the holders who
/// remain.
/// - It refuses (`VenueFrozen`) where one owes more, as its debt slice cannot be repaid there.
/// - Its preview shows the smaller payout, and `minOut` bounds it.
/// - A forfeit is never performance: the pool records it, and the first skim that reads the fee mark again
/// raises the fee mark by its value per share before it charges either rate.
///
/// The collateral an exit leaves where the venue still owes after it, and a release in the kind's whole units
/// could take it past its threshold, is treated as a forfeit too:
/// - The slice is cut to keep that floor posted, bounded as the held dust is (one unit's assets and one times
/// `lltv / max(lltv - ltv, gap, 1 %)`), and by up to one unit's assets more where the venue holds less than
/// that floor and a unit, as a slice under one unit's assets and one stays posted whole
/// (`FLAMMGateLib.nearUnitsAt`). Only what it leaves is forfeited.
/// - Where that much posted would leave the venue past its threshold, its lender refuses the release and the
/// exit with it.
/// - No move of the pool's own (a dial move, `setDials`; an admission with borrowing on or a switch-on) leaves
/// a pin within that gap under its threshold.
///
/// A collateral slice a venue cannot release now is paid from the custody the pool owns, never the custody
/// kept for the protocol's spread fee: past it the exit refuses (`CustodyMismatch`).
/// @param shares The shares to burn, above zero and at most `owner`'s (`InvalidAmount`).
/// @param receiver The receiver of the holdings, neither zero nor the pool (`InvalidAmount`), who also takes the
/// shares' claims on a fence's part.
/// @param owner The holder of the shares.
/// @param maxIn The most of each token the caller repays, in its base units.
/// @param minOut The least of each token paid out, in its base units.
/// @param deadline The last unix second it executes.
/// @return tokenIn Each token's net repay, in its base units, token 0 first.
/// @return tokenOut Each token's net output, in its base units, token 0 first.
function redeemProRata(
uint256 shares,
address receiver,
address owner,
uint256[] calldata maxIn,
uint256[] calldata minOut,
uint256 deadline
) external returns (uint256[] memory tokenIn, uint256[] memory tokenOut);
/// @notice The legs and net amounts {depositProRata} of `poolAssets` would take now.
/// @dev The previews price at the supply after the performance fee the flow crystallizes first, both parts. Each
/// quotes the legs, not whether the flow executes, but an entry's refuses (`IMMRouter.Unhealthy`) where a
/// borrow leg would leave its venue past its pin in the collateral the pool recognizes, and an exit's where a
/// frozen venue owes more than the lenders' rounding (`VenueFrozen`), as the flow does; an exit's legs carry
/// the flow's haircut cut and forfeit its slice of a frozen venue that owes no more. An exit's reads no hold
/// of its repay at a venue that takes it short, so the exit can refuse (`CustodyMismatch`) where custody
/// cannot pay the slice that venue keeps posted, or pay short of it by the dust (`redeemProRata`). `tokenIn`
/// and `tokenOut` are per token, token 0 first.
/// @param poolAssets The pool asset paid in, in its base units.
/// @return shares The shares it would mint.
/// @return legs The flow's venue legs.
/// @return tokenIn Each token's net input, in its base units.
/// @return tokenOut Each token's net output, in its base units.
function previewDepositProRata(uint256 poolAssets)
external
view
returns (uint256 shares, VenueLeg[] memory legs, uint256[] memory tokenIn, uint256[] memory tokenOut);
/// @notice The legs and net amounts {mintProRata} of `shares` would take now, as {previewDepositProRata}.
/// @param shares The shares to mint.
/// @return legs The flow's venue legs.
/// @return tokenIn Each token's net input, in its base units.
/// @return tokenOut Each token's net output, in its base units.
function previewMintProRata(uint256 shares)
external
view
returns (VenueLeg[] memory legs, uint256[] memory tokenIn, uint256[] memory tokenOut);
/// @notice The legs and net amounts {redeemProRata} of `shares` would take now, as {previewDepositProRata}.
/// @param shares The shares to burn.
/// @return legs The flow's venue legs.
/// @return tokenIn Each token's net repay, in its base units.
/// @return tokenOut Each token's net output, in its base units.
function previewRedeemProRata(uint256 shares)
external
view
returns (VenueLeg[] memory legs, uint256[] memory tokenIn, uint256[] memory tokenOut);
// swap
/// @notice Exact input, any two listed tokens, the pool asset included: the hook that prices the pair (the swap
/// hook, or a pair hook on its pairs) prices the fill (`IPairHook.fillPair`), and core checks it (its fee
/// inside the bounds, its input, the caller's minimum, the ceiling the credit law and the notional caps
/// leave, the tighter band of the two tokens around their USD prices) and settles it through the Router:
/// the input repays what the pool owes of it first, the output pays from custody, collateral, one rotation
/// or a draw on its pair, the input's surplus is lent, and the credit law holds after. It runs no
/// observation.
/// @dev It runs only for a pair in both trade masks (a hook prices it and the curator lets it trade,
/// `FLAMM.tradablePairs`; `PairNotTradable` otherwise), a sale of the pool asset under `FEATURE_SWAP_SELL` and
/// a buy of it under `FEATURE_SWAP_BUY` (`FeatureDisabled`); a pair past the hook pair needs both its USD
/// prints within `maxPriceAgeSec` (`StalePair`).
///
/// Refused also:
/// - `InvalidPair`: a token not listed, or one token twice.
/// - `Paused`: `FLAMM.setPaused` says which swaps run paused.
/// - `PriceUnchecked`: a pair with no checked price, or an owing pool with no band.
/// - `PegBroken`: a draw with a token off its peg.
/// - `RoomExhausted`: no room for an output some live pair owes, the input owing nothing.
/// - `CreditPathOff`: a pair a cheap-lane pool's front prices while its credit path is off.
/// - Past core's checks of the fill, `FeeOutOfBounds`, `FillInvalid`, `OutputAboveCeiling` and `PriceBand`.
/// - `InputUnused`: a fill of less than `amountIn` where the input was found (below).
///
/// The input is found or pulled at the settling step, after the fill is checked and before any venue moves
/// or anything is paid:
/// - Found: where the pool holds the whole `amountIn` past its tracked custody, nothing is pulled and exactly
/// `amountIn` is credited, and a fill of less reverts `InputUnused`. Input sent first therefore fills whole
/// or comes back with the revert. A found fill makes no call that moves the input, unless a venue takes it
/// in that fill (a repay, a post or a lend), so it fills where that token's transfers are paused or refuse
/// the caller, up to what lay past custody. That balance is read only while the pool's balance is at least
/// its tracked custody: under it the pull runs and custody refuses the fill (`CustodyMismatch`), except on
/// the full path (any fill past the custody-only branch) within what custody keeps of the fee in token 0 or
/// 1 and, on a payout, the fill's part and share, which the reconcile does not read: there the swap fills
/// and the shortfall stays.
/// - Pulled: otherwise the pool pulls what the fill uses from the caller, and a fill of less keeps the rest
/// with the caller. A short delivery reverts `CustodyMismatch`.
/// - Any untracked `tokenIn` counts toward that test: a donation, an overpayment, a payment left by an
/// earlier transaction. The next caller it covers spends it, with no pull, and any allowance that caller
/// gave the pool stands; only what lies past `amountIn` stays untracked.
/// - A payer sends and calls in one transaction with no call between, and holds no allowance to the pool. A
/// send short of `amountIn` is left in the pool and the pull runs.
/// - What a payer leaves behind it can swap away itself at the pool's price only where the pair is open and
/// this entry runs: not on a custody-blind pool, nor, with the credit path off, on a pair the front prices.
/// A stray of the pool asset has no lift: it stays until a swap or a paid fill spends it.
/// - On a fee-on-transfer token a payer that declares what arrived fills where no venue moves the token; a
/// repay or a post of its cut reverts. One that declares the gross amount falls to the pull, unless
/// untracked balance covers the fee, which the swap then spends.
/// - A pool must not list two addresses of one ledger: each leg's custody reads as past the other's tracked
/// custody, so a fill found there is paid from the pool's own custody.
/// - A send sized by `previewSwap` takes the preview from the calling address, and it can still clip: its
/// `amountInUsed` may fill less when executed, and a found fill of less reverts.
///
/// The pool's `Swap` event reports the fill: the tokens' indices, the native amounts and fee, and the hook's
/// fee rate, spot after, gross output, coordinate after and the protocol's part of the fee, with
/// `amountInUsed` equal to `amountIn` on a found fill. Its `sender` is the caller, which need not be the
/// account that paid. From the swap `EverlongHook` emits `Levered` on a leverage fill and nothing on a curve
/// fill.
///
/// A swap that would draw at a pair with a venue that borrows, or rotate from a pair, where a venue reports a
/// loss of 1 bp or more on its collateral (`FLAMMKeptLib.lossAtFloor`), or takes a redemption fee of any size
/// on it, reverts `VenueReportsLoss`; the quote reverts the same, on the same check, where its plan draws or
/// rotates (it reads the releases the Router reports, so a venue that releases less than it reports can leave
/// the swap at a draw the quote did not see). A payout the pair's supply would pay is refused too, and a pair
/// whose only venue that borrows stands under a fee draws nothing until the fee ends.
/// The operator or the guardian ends it at once by switching that venue's borrowing off, or the pair's;
/// switching it back on waits the pool's delay where the cheap lane is on.
///
/// The selector is shared with another swap standard, but this returns two words and has none of its views.
/// @param tokenIn The token paid in, found at the pool or pulled from the caller.
/// @param tokenOut The token paid out.
/// @param amountIn The most to pay in, in `tokenIn` base units, above zero (`InvalidAmount`): all of it where the
/// input is found.
/// @param minAmountOut The least net output, in `tokenOut` base units (`Slippage`).
/// @param to The receiver of the output, neither zero nor the pool (`InvalidAmount`).
/// @param deadline The last unix second it executes (`Expired`).
/// @return amountInUsed The input the hook used, in `tokenIn` base units, at most `amountIn`.
/// @return amountOut The net output paid to `to`, in `tokenOut` base units.
function swap(address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut, address to, uint256 deadline)
external
returns (uint256 amountInUsed, uint256 amountOut);
/// @notice Quotes a swap of `amountIn` of `tokenIn` for `tokenOut` on the pool book as it stands: the swap's own
/// branch, plan and checks, the hook's quote of the swap's request (`IPairHook.quotePair`), re-asked at the
/// input it used, rounded to native units, so a swap of the quoted input, the quoted output its minimum,
/// fills the quote. A payout that draws past what the Router can fund for it now reverts as the swap would
/// (`IMMRouter.InsufficientLiquidity`), rather than quoting a smaller fill the swap would not make. No swap
/// fills under its quote, but at a venue that holds a minimum position a quoted payout can still revert by
/// the slice the swap's plan passes over, and a payout the quote refuses can fill (`IFinancingAccount`
/// ADMISSION).
/// @param tokenIn The token paid in.
/// @param tokenOut The token paid out.
/// @param amountIn The most to pay in, in `tokenIn` base units.
/// @return amountInUsed The input the fill uses, in `tokenIn` base units.
/// @return amountOut The net output, in `tokenOut` base units.
/// @return feeWad The fill's fee rate, WAD.
function previewSwap(address tokenIn, address tokenOut, uint256 amountIn)
external
view
returns (uint256 amountInUsed, uint256 amountOut, uint256 feeWad);
/// @notice The pool context a recenter hands the swap hook now (`PoolContext`): every token's legs through the
/// Router and its custody, the rest at their unrounded USD cross, the hook pair's N36 from the feed's pair,
/// the band, the listed pairs and the features; a poke hands the same with every leg zero, as it reads no
/// pool book. Reverts where the observation could not price: a stale pair, the sequencer, an unchecked
/// price it needs. The hook's curve ceremony reads `priceN36` from it as the feed's print
/// (`EverlongOpsLib.curveGate`), so a pool that cannot price its observation refuses that ceremony too.
function hookContext() external view returns (PoolContext memory);
/// @notice The request a swap of `amountIn` (native units of `tokenIn`) hands the pair's hook now
/// (`PairRequest`), on the swap's branch and plan, `sender` the caller. Reverts where the swap
/// refuses before its fill: the pause or a feature bit, a payout without room, a payout off peg wherever
/// its payout pair may borrow, whatever the backing holds, a price it cannot read, a zero input.
function pairRequest(address tokenIn, address tokenOut, uint256 amountIn) external view returns (PairRequest memory);
// lifecycle (factory only)
/// @notice The pool's first entry, the Factory's alone and once (`AlreadyBootstrapped`): pulls `assets` of the pool
/// asset into custody, mints at par, with `FLAMMStore.MINIMUM_SHARES` to a dead address that never burns
/// them, and sets the fee mark at par. `InvalidAmount` on a zero `assets` or `to`; `BelowMinimumShares`
/// unless the shares pass the dead ones.
/// @param assets The pool asset, in its base units.
/// @param to The receiver of the shares past the dead ones.
/// @return shares The shares minted to `to`.
function bootstrap(uint256 assets, address to) external returns (uint256 shares);
/// @notice The protocol's performance fee, at most `FLAMMStore.MAX_PROTOCOL_FEE_BP`; it skims at the old rates
/// first, and a rise reverts `PriceUnchecked` while that skim cannot read the fee mark, as on a seeded pool
/// with no market band, or while a fence holds a pool part. A nonzero rate on a pool whose cheap lane is on
/// reverts `InvalidConfig`. The Factory applies a cut at once and a rise after the longer of its
/// `UPGRADE_DELAY` and ten days; no upgrade moves the Factory, so every implementation keeps this entry.
/// @param feeBp The rate, bp.
function setProtocolFeeBp(uint16 feeBp) external;
/// @notice The protocol's rates (`FLAMMFloatLib.setSpreadFeeRates`), one word: in bits 0-15 the spread rate, at
/// most `FLAMMFloatLib.MAX_SPREAD_FEE_BP`, the share of a hook's fee the protocol takes in kind, of
/// each fill's edge against its fee price (the pull price, or where the listing reads none its desk's
/// word's mid) on a pool whose cheap lane is on; in bits 16-31 and 32-47 the notional rates of the pool's
/// other pairs and of its correlated pairs (two tokens of one peg group at the Factory), each at most
/// `FLAMMFloatLib.MAX_NOTIONAL_RATE`, in `FLAMMStore.NOTIONAL_SCALE` parts of a fill's notional leg, the
/// floor of the protocol's part of every hook-priced fill and every cheap fill. The Factory applies a cut
/// of a field at once and a rise after the longer of its `UPGRADE_DELAY` and ten days; no upgrade moves
/// the Factory, so every implementation keeps this entry.
/// @param rates The word above.
function setSpreadFeeRates(uint48 rates) external;
// code (beacon proxy: the Factory is the beacon; a new implementation must report a higher code version)
/// @notice The code version of the implementation behind the beacon.
function poolCodeVersion() external pure returns (uint32);
/// @notice The feature bitmap (`FLAMMStore.FEATURE_*`) and the governance delay.
/// @return featureBits The bitmap.
/// @return delaySec The governance delay, seconds, write-once.
function switches() external view returns (uint256 featureBits, uint32 delaySec);
/// @notice The committed ceilings (`FLAMMPolicyLib.setBandAndFeeCeilings`): the widest swap band any token may take and the
/// highest fee cap, each set at once under its ceiling, which starts at the widest band of the pool's
/// tokens and its cap at birth (a band ceiling of `type(uint64).max` admits no band at all); then the
/// scheduled raise, which waits `governanceDelaySec` (one of the band's at least ten days), and when the
/// curator may apply it, zero when none.
/// @return bandWad The band ceiling, WAD.
/// @return feeCapWad The fee cap's ceiling, WAD.
/// @return pendingBandWad The scheduled band ceiling, WAD.
/// @return pendingFeeCapWad The scheduled fee cap ceiling, WAD.
/// @return executableAt When the raise may apply, unix seconds; zero when none.
function ceilings()
external
view
returns (uint64 bandWad, uint64 feeCapWad, uint64 pendingBandWad, uint64 pendingFeeCapWad, uint48 executableAt);
// observation
/// @notice Forwards the feed's print to the swap hook, which folds it; permissionless and refused while paused
/// (`Paused`), and on a pool with no band, which has no print to forward (`NoBand`). A
/// swap forwards none: the folds follow the feed as far as pokes and recenters forward it.
function poke() external;
/// @notice Forwards the feed's print (none on a pool with no band) to the swap hook's recenter, which may move its
/// anchor inside the caller's bounds (`AnchorOutOfBounds` otherwise); refused while paused (`Paused`). The
/// keeper, the curator or the controller hook calls it (`NotKeeperOrCurator`), so a recentering rule can
/// live in a controller, which only the genesis set or the delayed hook-set ceremony installs.
/// @param minAnchorN36 The lowest anchor the caller takes, in the hook's N36 price scale.
/// @param maxAnchorN36 The highest anchor the caller takes, in the same scale, at least `minAnchorN36`
/// (`InvalidConfig`).
/// @param deadline The last unix second it executes (`Expired`).
function recenter(uint256 minAnchorN36, uint256 maxAnchorN36, uint256 deadline) external;
/// @notice Crystallizes the performance fee at the current fee mark, minting the curator's part to the core fee
/// receiver and the protocol's to the Factory's `protocolFeeReceiver`; permissionless. With both parts
/// off it still raises `peakSharePriceWad`, silently.
function skimPerformanceFee() external;
}
/// @notice What a pool and the lens read of the Factory's protocol fee: the receiver of the protocol's part (never
/// zero on the Factory) and a pool's scheduled rise (`feeBp` zero: none).
interface IFLAMMProtocolFee {
/// @notice The receiver of the protocol's part of every pool's fees.
function protocolFeeReceiver() external view returns (address);
/// @notice `pool`'s scheduled rise of its protocol performance fee.
/// @param pool The pool.
/// @return feeBp The scheduled rate, bp; zero: none, or one lapsed.
/// @return executableAt When it may apply, unix seconds.
function pendingProtocolFee(address pool) external view returns (uint16 feeBp, uint48 executableAt);
}
src/interfaces/core/flamm/IFLAMMHooks.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The pool state in a hook's observation (`ObservationContext`), which `FLAMMOpsLib.hookContext` also reads, built
/// by core from its custody, the Router's positions and one checked price. A fill's hook gets a `PairRequest`
/// instead. The pool lists tokens `t0, t1, ...`: `t0` is the pool asset (the share and NAV unit, the base),
/// `t1` the numeraire (the quote), the hook pair. Each holds four legs: held (custody, unlent), supplied
/// (lent at a venue), posted (collateral at a venue) and owed (borrowed from a venue). Base
/// fields are `t0` base units; quote fields are `t1` in N18 (its value at 18 decimals); the rest sum every
/// token from `t2` on in N18 at its USD cross with `t1`, holdings rounded down and debt up, leg by leg.
/// `priceN36` is `t1`'s value at 36 decimals per `t0` base unit (N18 scaled by 1e18), so a cheap 18-decimal
/// pool asset keeps its digits; every hook price below is in the same price scale. A pool with no market band
/// hands `priceN36` zero. A poke's observation reads no pool book: it carries the print, the band, the pairs
/// and the features, every leg zero (`IRecenterHook.observe`).
/// @dev Flat, so core copies it into a call in one move. `bookScale` is reserved and zero. `bandWad` is the hook
/// pair's live swap band (zero: none). `pairs` holds the `CONTEXT_PAIR_*` bits of the credit pairs the pool
/// lists; `features` the pool's `FEATURE_*` bits and, on a custody-blind pool, whose swap hook is its front for
/// life, the law's bit past them (`FLAMMStore.CUSTODY_BLIND`).
struct PoolContext {
uint256 baseHeld; // `t0` held, base units
uint256 baseSupplied; // `t0` supplied, base units
uint256 basePosted; // `t0` posted, base units
uint256 baseOwed; // `t0` owed, base units
uint256 quoteHeld; // `t1` held, N18
uint256 quoteSupplied; // `t1` supplied, N18
uint256 quotePosted; // `t1` posted, N18
uint256 quoteOwed; // `t1` owed, N18
uint256 restHeldN18; // the held, supplied and posted legs of every token from `t2` on, N18, rounded down
uint256 restOwedN18; // the owed legs of every token from `t2` on, N18, rounded up
uint256 priceN36; // `t1` per `t0` base unit, N36; zero with no market band
uint256 bookScale; // reserved, zero
uint64 bandWad; // the hook pair's live swap band, WAD; zero: none
uint32 pairs; // `CONTEXT_PAIR_*` bits
uint32 features; // the pool's `FEATURE_*` bits, and `FLAMMStore.CUSTODY_BLIND` past them
}
/// @notice `EverlongHook`'s own form of a fill of the hook pair, which it builds from the pair request
/// (`PairRequest`): the pool context, the side, the input and the ceiling in its units (token 1 in N18), and
/// the pool's fee bounds. Core hands no hook this struct.
struct SwapContext {
PoolContext pool; // the pool book as the request carries it
bool poolAssetIn; // the input is the pool asset: the pool buys it
uint256 amountIn; // `t0` base units where `poolAssetIn`, else `t1` in N18
uint256 maxAmountOut; // `t1` in N18 where `poolAssetIn`, a ceiling past a word read as none, else `t0` base units
uint64 feeFloorWad; // the least fee rate, WAD
uint64 feeCapWad; // the most fee rate, WAD
}
/// @notice `EverlongHook`'s own fill in its units (`t0` in base units, `t1` leg N18): input used, the curve's gross
/// output, the fee kept from it, the fee rate, the spot after the fill and the curve coordinate after it
/// (`xAfter`, WAD). The hook converts it to the pair fill core settles (`PairFill`).
struct FillResult {
uint256 amountInUsed; // in `SwapContext.amountIn`'s units
uint256 grossOut; // in `SwapContext.maxAmountOut`'s units
uint256 feeOut; // in `SwapContext.maxAmountOut`'s units
uint256 feeWad; // WAD
uint256 spotAfterN36; // N36
uint256 xAfter; // WAD
}
/// @notice One checked reference print and its source timestamp. `poke` and `recenter` forward the feed's current
/// print, which may repeat an `observedAt` already forwarded, even with a moved `referenceN36` (a cross carries
/// its older leg's stamp). A hook MUST treat `observedAt` as non-monotonic, clamp its own elapsed-time step and
/// decline a value it has already folded. A swap forwards none: its request carries the two prices, which a
/// hook may fold itself. A recenter's `pool` is the pool book at that print; a poke's carries the hook pair's
/// N36, the band, the pairs and the features with every leg zero, as core reads no pool book for it. A pool
/// with no market band reads no price: its `poke` refuses (`NoBand`), and its recenter hands a zero reference
/// and stamp.
struct ObservationContext {
PoolContext pool; // the pool book, or the terms beside it, as above
uint256 referenceN36; // the hook pair's print, `t1` per `t0` base unit, N36
uint48 observedAt; // the print's source timestamp, unix seconds; the older leg's
}
/// @notice The swap hook's spot, for readers outside the pool: core reads none, as every swap hook only folds on a
/// poke (`HOOK_CAP_FOLD_ONLY`). The swap hook prices its fills and its own fee through `IPairHook`.
interface IInvariantHook {
/// @notice The hook's marginal price, in `PoolContext.priceN36`'s price scale.
/// @param ctx The pool state. A hook may ignore it, as `EverlongHook` does.
/// @return spotN36 The spot, N36. A hook that holds no curve answers zero.
function spot(PoolContext calldata ctx) external view returns (uint256 spotN36);
}
/// @notice The observation and anchor policy: fold one observation, or fold it and move the anchor. Core runs
/// `observe` on `poke`, and `recenter` on the pool's `recenter` (the keeper's, the curator's or the controller
/// hook's), whose anchor bounds core checks on the anchor the hook returns.
interface IRecenterHook {
/// @notice Folds the print, moving nothing `spot` reads (`HOOK_CAP_FOLD_ONLY`). Core calls it on `IFLAMM.poke`,
/// which anyone may run. A revert reverts the poke.
/// @param ctx The print, with every leg of its context zero.
function observe(ObservationContext calldata ctx) external;
/// @notice Folds the print and moves the anchor where the hook's policy says so. Core calls it on
/// `IFLAMM.recenter`.
/// @param ctx The print and the pool book at it.
/// @return moved Whether the anchor moved; core checks `anchorN36` only then (`AnchorOutOfBounds`).
/// @return anchorN36 The anchor after the call, N36.
function recenter(ObservationContext calldata ctx) external returns (bool moved, uint256 anchorN36);
}
/// @notice A hook's identity, which core checks at installation (`FLAMMOpsLib.checkIdentity`). Every hook must hold
/// code. A hook that prices (the swap hook and a pair hook) must answer both and name its pool; the
/// controller may stay silent, but a nonzero `boundPool` must name the pool and a declared version must match.
interface IHookIdentity {
/// @notice The hook interface version the hook implements, `HOOK_INTERFACE_VERSION`.
function hookInterfaceVersion() external view returns (uint16);
/// @notice The pool the hook serves. A hook shared by many pools answers the pool asking.
function boundPool() external view returns (address);
}
/// @dev The one hook interface version core accepts (`IHookIdentity.hookInterfaceVersion`).
uint16 constant HOOK_INTERFACE_VERSION = 3;
// `PoolContext.pairs`: the credit pairs the pool lists (live, not retired) and whether each borrows.
/// @dev The forward pair, `t1` borrowed against `t0`, is listed.
uint32 constant CONTEXT_PAIR_FORWARD = 1 << 0;
/// @dev The forward pair's borrowing is on.
uint32 constant CONTEXT_PAIR_FORWARD_BORROWS = 1 << 1;
/// @dev The reverse pair, `t0` borrowed against `t1`, is listed.
uint32 constant CONTEXT_PAIR_REVERSE = 1 << 2;
/// @dev The reverse pair's borrowing is on.
uint32 constant CONTEXT_PAIR_REVERSE_BORROWS = 1 << 3;
/// @dev Another pair that owes `t0` or posts a token other than `t0` is listed.
uint32 constant CONTEXT_PAIR_OTHER = 1 << 4;
src/interfaces/core/flamm/IPairHook.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice One exact-input fill request for any two of the pool's tokens, in native units: every pair, the pool asset
/// included, and every mode (cover, borrow, rotation, custody only). Flat, so core writes it into a call in a
/// few moves. `sender` is the swap's caller. `mode` holds the `PAIR_MODE_*` bits of the plan, `features` the
/// pool's `FEATURE_*` bits, `protocolFeeBp` the pool's protocol spread rate (zero where none is set).
/// `IFLAMM.pairRequest` reads the request a swap would send now.
/// @dev Core refuses:
/// - a fill whose `feeWad` is under `feeFloorWad` or over `feeCapWad` (`FeeOutOfBounds`);
/// - one whose net output's value at `usdOut` is outside `bandWad` around the input's value at `usdIn`
/// (`PriceBand`; both prices zero on a pool with no band, which checks none);
/// - one whose `protocolFeeOut` passes `feeOut` or `net * protocolFeeBp / (1e4 - protocolFeeBp)`, where `net` is
/// `grossOut - feeOut` (`FeeOutOfBounds`).
///
/// The amounts:
/// - `amountIn` is at most the input's notional cap.
/// - `maxAmountOut` is core's ceiling for this request, not the pool's depth (where the band's top for the input
/// is under custody it counts the output's supply whole, as no fill the band passes reaches it), less, at a
/// notional rate, the room the protocol's floor needs beside a payout under it: the payout's ceiling times
/// `1e7 / (1e7 + extension)`, rounded down.
/// - Each token's legs are held, supplied, posted and owed, native, as the plan read them.
/// - `restHeldN18` and `restOwedN18` are the USD values (WAD) of every other token's held, supplied and posted
/// legs and of its owed leg, at the feed, so a hook that values the whole pool book (`EverlongHook`'s leverage)
/// sees the tokens outside the pair.
struct PairRequest {
address sender; // the swap's caller
address tokenIn; // the token the pool takes
address tokenOut; // the token the pool pays
uint8 indexIn; // `tokenIn`'s index in the pool
uint8 indexOut; // `tokenOut`'s index in the pool
uint16 mode; // `PAIR_MODE_*` bits
uint16 features; // the pool's `FEATURE_*` bits
uint16 protocolFeeBp; // the pool's protocol spread rate, bp
uint64 feeFloorWad; // the least `PairFill.feeWad`, WAD
uint64 feeCapWad; // the most `PairFill.feeWad`, WAD
uint64 bandWad; // the tighter of the two tokens' swap bands, WAD
uint256 usdIn; // `tokenIn`'s USD per whole token, WAD
uint256 usdOut; // `tokenOut`'s USD per whole token, WAD
uint256 amountIn; // the input, `tokenIn` base units
uint256 maxAmountOut; // core's ceiling on the net output, `tokenOut` base units
uint256 heldIn; // `tokenIn` held, base units
uint256 suppliedIn; // `tokenIn` supplied, base units
uint256 postedIn; // `tokenIn` posted, base units
uint256 owedIn; // `tokenIn` owed, base units
uint256 heldOut; // `tokenOut` held, base units
uint256 suppliedOut; // `tokenOut` supplied, base units
uint256 postedOut; // `tokenOut` posted, base units
uint256 owedOut; // `tokenOut` owed, base units
uint256 restHeldN18; // every other token's held, supplied and posted legs, USD, WAD
uint256 restOwedN18; // every other token's owed leg, USD, WAD
/// @dev In bits 0-15 the pair's notional rate, parts per 1e7 of the net payout, by the pair's kind
/// (`FLAMMStore.rateOf`; zero where none is set): the floor of the protocol's part, which core books whatever
/// `protocolFeeOut` reports ({PairFill}). In bits 16-31, where `features` carry `FLAMMStore.OPERATOR_SHARE`,
/// the operator's share's rate, bp, which core books beside the part but on a cover ({PairFill}); zero
/// otherwise. A later core may widen this word without changing this interface's selectors; a hook must not
/// read more into it than that.
uint256 extension;
}
/// @notice A hook's fill, native units: input used (at most `amountIn`), gross output, the fee kept from it, the
/// fee rate the fill was computed at, two words the pool only reports, and the protocol's share of this fill's
/// spread in the output token (`protocolFeeOut`), which the pool never mints. `spotAfterN36` is the hook's
/// marginal price after the fill (a fill the hook absorbs without moving its price, such as EverlongHook's
/// leverage fills, reports it unchanged); `xAfter` is a coordinate the hook defines.
/// @dev Core pays `grossOut - feeOut`, never alters a committed fill, and asks the hook once per swap. Only the hook
/// that prices the pair sets a swap's amounts, and no hook runs on a deposit's exit or a redemption.
///
/// The protocol's part core books is its own, in kind, out of the pool's custody in the token paid, after
/// `fillPair` returns: `max(min(protocolFeeOut, bound), net * rate / 1e7)`, where `rate` is the notional rate
/// (`extension`'s bits 0-15) and `bound` is `net * band * protocolFeeBp / (1e18 * 1e4)` (`band` the wider of
/// `bandWad` and core's least fee band), cut to the room the net leaves under the request's ceiling
/// (`maxAmountOut * rate / 1e7 + maxAmountOut - net`).
/// It can be more or less than `protocolFeeOut`, and more than `feeOut`; the pool's `Swap` log reports it. A hook
/// that keeps its own reserves must take out the part core booked, not its own report, or re-read its legs from
/// each request.
///
/// Where the pool sets an operator's share (`FLAMMFloatLib.setOperatorShareBp`, rate `share` in bp; the request's
/// `features` carry `FLAMMStore.OPERATOR_SHARE` then), core books it beside the part, the same way and in the same
/// token: at most `min((base - part) * share / 1e4, room - part)` where `base`, the fee read at most at the fill's
/// own rate (`min(feeOut, net * feeWad / (1e18 - feeWad))`, none at a rate of 1e18), passes the part; `room` is
/// the part's. A cover (`PAIR_MODE_COVER`) pays no share: its fee past the part stays with the LPs. Core cuts it
/// further, never past that bound: where a live pair owes the token paid, `room` counts at `1 - ltv * phiWad`, the
/// highest of those pairs', as a payout room may credit the input and the share brings none; on a rotation, to
/// what the output's custody leaves past the rotation's keep, the net and the part; to the room left in the
/// operator's counter of the token paid and to what fits beside the part under 2^128; and at its booking to what
/// custody holds beside the fee owed and the part (`FLAMMLane.post`). No log reports it per fill. A hook that
/// keeps its own reserves must take it out too: the bound is at least what core books. A hook whose spread is in
/// its price reports no fee but its protocol's part; with the share on it may report the spread it earned as
/// `feeOut` instead, and that spread's rate of the gross as `feeWad`, within the request's fee floor and cap (the
/// PropAMM front reports the desk's edge, capped at the band of the quote leg), so the share is of that spread.
struct PairFill {
uint256 amountInUsed; // the input used, base units; zero or past `PairRequest.amountIn` refuses (`FillInvalid`)
uint256 grossOut; // the gross output, base units
uint256 feeOut; // the fee kept from `grossOut`, base units; a zero net refuses (`FillInvalid`)
uint256 feeWad; // the rate the fill was computed at, WAD
uint256 spotAfterN36; // reported only
uint256 xAfter; // reported only
uint256 protocolFeeOut; // the hook's report of the protocol's share, `tokenOut` base units
}
/// @notice The one pricing interface, of the swap hook and of a pair hook, for every pool and pair: the quote, a view,
/// and the committed fill. Equal requests get equal answers, and the request never lets the sender set the
/// price. A hook must not price from the pool's balances: a fill sent first shows it the input, a quote and a
/// pulled fill do not.
interface IPairHook {
/// @notice The fill `r` would get now, with nothing written: the one `fillPair` commits on the same state. The
/// pool's `previewSwap` reads it by a static call and runs the swap's checks on the answer, asking again at
/// the input the hook used while that is under the one asked. A revert bubbles up through the preview; an
/// answer under seven words reverts empty.
/// @param r The request.
/// @return The fill, native units.
function quotePair(PairRequest calldata r) external view returns (PairFill memory);
/// @notice The committed fill of `r`. The pool's swap calls it once, before any token of the fill moves, then runs
/// its checks on the answer ({PairRequest}, {PairFill}) and settles it. A revert bubbles up through the
/// swap, a failed check reverts the hook's writes with it, and an answer under seven words reverts empty.
/// @param r The request.
/// @return The fill, native units.
function fillPair(PairRequest calldata r) external returns (PairFill memory);
/// @notice Whether this hook prices fills of `tokenIn` for `tokenOut` on `pool`. Core asks it for every ordered
/// pair of the pool's listed tokens when the hook is installed and when a token is listed, and caches the
/// answers in one word: a pair the hook does not price never trades, whatever the curator's trade mask
/// says. A cheap-lane pool asks its front again at the listings' resync (`IFLAMMLane.syncListings`) and at
/// a pair hook's removal, and at a pair hook's schedule and installation of the pairs that hook would
/// price, which the front must not: there a front's revert reads as a pair it prices, and the hook's as one
/// it does not. A view that never reverts: equal arguments, equal answer; on a cheap-lane pool a sync reads
/// an answer not given (a revert, or a word that is not a bool) as no change to that pair.
/// @param pool The pool asked of.
/// @param tokenIn The token the pool would take.
/// @param tokenOut The token the pool would pay.
/// @return Whether the hook prices that ordered pair on `pool`.
function pricesPair(address pool, address tokenIn, address tokenOut) external view returns (bool);
}
/// @notice A pool's second hook, for named pairs (`FLAMMFloatLib.setPairHook`): the hook and the unordered pairs it
/// prices, bit `160 + hi * (hi - 1) / 2 + lo` of `mask` for tokens `lo < hi`; zero when none. The curator
/// installs or replaces it after D, the pool's own delay (`governanceDelaySec`), the curator's choice and risk;
/// a removal, the curator's or the guardian's, applies at once.
interface IPairHookSlot {
/// @notice Installs, replaces or removes the pair hook. A nonzero `hook` is the curator's: the first call schedules
/// it, the identical call applies it from D on and for one more D (`HookSetNotReady` sooner), and the
/// curator or the guardian cancels it (`FLAMMAdmitLib.cancel`). A zero `hook` with a zero `mask` removes the hook
/// at once and closes its pairs. `NotGuardianOrCurator` for any other caller, `GuardianMayOnlyTighten` for
/// a guardian naming a hook, `HookInvalid` for a hook that fails its identity or capability checks, and
/// `InvalidConfig` for a removal with a mask or with no hook set, a pool whose credit law is custody-blind,
/// a mask empty or naming a pair outside its tokens or the hook pair, or a pair the hook does not price
/// both ways or, on a cheap-lane pool, one the front prices. The full rules are on
/// `FLAMMFloatLib.setPairHook`.
/// @param hook The hook; zero removes the one set.
/// @param mask The unordered pairs it prices, in the layout above.
function setPairHook(address hook, uint256 mask) external;
/// @notice The pair hook and its pairs; both zero when none.
/// @return hook The pair hook.
/// @return mask The unordered pairs it prices, in the layout above.
function pairHook() external view returns (address hook, uint256 mask);
}
/// @dev The hook prices fills whose payout may move a debt the output backs onto the input (`PAIR_MODE_ROTATE`); core
/// plans no rotation unless the swap hook declares it and, while one is set, the pair hook too. Its sibling
/// `HOOK_CAP_*` bits are in IHookCapabilities.sol.
uint256 constant HOOK_CAP_ROTATE = 1 << 3;
// `PairRequest.mode`
/// @dev The input is owed: the settlement repays it first and draws nothing.
uint16 constant PAIR_MODE_COVER = 1 << 0;
/// @dev A payout past custody and free collateral may draw the output on its pair.
uint16 constant PAIR_MODE_BORROW = 1 << 1;
/// @dev A payout may move a debt the output backs onto the input.
uint16 constant PAIR_MODE_ROTATE = 1 << 2;
/// @dev The pool is paused: the fill runs only where it draws nothing and lends nothing.
uint16 constant PAIR_MODE_PAUSED = 1 << 3;
/// @dev The venue legs were not read (a fill from custody alone): the supplied, posted and owed legs are zero.
uint16 constant PAIR_MODE_HELD_ONLY = 1 << 4;
/// @dev The input repays all of one debt and the output is borrowed on another pair (a crossing).
uint16 constant PAIR_MODE_CROSS = 1 << 5;
/// @dev Some fence holds a pool part (`FLAMMStore.parted`): a fenced venue's position or a fenced token's custody that
/// the pool still owns a part of is out of the book, so the request's legs and its rest of the book leave it out
/// until the part returns or is given up. A hook that marks the whole book from them reads one short of that part.
/// A custody-only request (`PAIR_MODE_HELD_ONLY`) does not carry it: its venue legs read zero either way.
uint16 constant PAIR_MODE_PARTED = 1 << 6;
src/interfaces/core/mm/IAccountDeployer.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice A stateless deployer of one account kind. The Factory registers one per kind: a kind's first at once, a
/// replacement through its delayed ceremony. `deploy` binds the account to its caller as router and creates
/// it with CREATE2 under
/// `keccak256(abi.encode(msg.sender, pool, collateralAsset, loanAsset))`, so no other caller can occupy a
/// router's account address, and a pair and its reverse sit at distinct addresses. A frame's account is bound
/// to (zero, frame) (`FRAME_VENUE`), so it sits apart from every pair's, as no listed token is zero;
/// a kind that holds no frame answers no `IFrameAccount.tokensOf` there, which the Router reads of every
/// frame venue, and may refuse such an account where it deploys it. The Router pins every account it deploys
/// or finds to the CREATE2 address of this deployer, that salt and `initCodeHash`, and reads its bindings
/// back: it finds an account at that address at every venue it admits, the pair's own and a frame's alike.
interface IAccountDeployer {
/// @notice The venue kind this deployer's accounts serve.
function kind() external view returns (uint8);
/// @notice The CREATE2 init-code hash of the account `deploy(pool, collateralAsset, loanAsset)` creates for
/// `router`.
/// @dev Depends only on the bindings (and this deployer's own constants), never on storage that can change, the
/// caller or the block, and answers non-zero without reverting for any bindings, identical addresses included:
/// the Router pins each account it deploys to the CREATE2 address this hash gives, and finds it there again at
/// every venue it admits, so an answer that moved would open a second account for the same bindings. For a
/// frame's (zero, frame) it reads nothing of the frame, a tag the pool picks rather than a token.
function initCodeHash(address router, address pool, address collateralAsset, address loanAsset)
external
view
returns (bytes32);
/// @notice Creates the account for `pool` with its caller as router, at the address `initCodeHash` gives.
/// @param pool The pool whose positions the account holds.
/// @param collateralAsset The pair's collateral token; zero for a frame's account.
/// @param loanAsset The pair's loan token; for a frame's account, the frame.
/// @return account The new account.
function deploy(address pool, address collateralAsset, address loanAsset) external returns (address account);
}
/// @notice The Factory's list of account deployers, which the Router reads when it admits a venue.
interface IAccountDeployerRegistry {
/// @notice The deployer of `kind`; zero for none, which the Router refuses (`IMMRouter.KindUnknown`).
function accountDeployerOf(uint8 kind) external view returns (address);
}
src/interfaces/core/mm/IFinancingAccount.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @dev A `Capacity.actions` bit, what the venue lets this position do now: a borrow.
uint8 constant CAN_BORROW = 1;
/// @dev A `Capacity.actions` bit: a repay.
uint8 constant CAN_REPAY = 2;
/// @dev A `Capacity.actions` bit: a supply.
uint8 constant CAN_SUPPLY = 4;
/// @dev A `Capacity.actions` bit: a withdrawal of supply.
uint8 constant CAN_WITHDRAW_SUPPLY = 8;
/// @dev A `Capacity.actions` bit: a post of collateral.
uint8 constant CAN_POST_COLLATERAL = 16;
/// @dev A `Capacity.actions` bit: a release of collateral.
uint8 constant CAN_RELEASE_COLLATERAL = 32;
/// @dev Every `Capacity.actions` bit.
uint8 constant ALL_ACTIONS = 63;
/// @dev A `capabilities()` bit, what a kind may do, fixed per kind: `refinance` moves debt between two of its ids in
/// one step.
uint256 constant CAP_ATOMIC_REFINANCE = 1;
/// @dev A `capabilities()` bit: a collateral release depends on the venue's liquidity.
uint256 constant CAP_LENT_COLLATERAL = 2;
/// @dev A `capabilities()` bit: `lltv` can fall after admission.
uint256 constant CAP_MUTABLE_THRESHOLD = 4;
/// @dev A `capabilities()` bit: collateral units grow in assets.
uint256 constant CAP_ACCRUING_COLLATERAL = 8;
/// @dev A `capabilities()` bit: the venue can refuse an action (pause, freeze, hooks).
uint256 constant CAP_ACTION_GATES = 16;
/// @dev A `capabilities()` bit: the venue caps or rate-limits a leg.
uint256 constant CAP_PROTOCOL_CAPS = 32;
/// @dev A `capabilities()` bit: its legs can move other venues' cash and rate (one reserve behind them).
uint256 constant CAP_SHARED_LIQUIDITY = 64;
/// @dev A `capabilities()` bit: a collateral release reads the venue's oracle, owing or not.
uint256 constant CAP_PRICED_RELEASE = 128;
/// @dev A `capabilities()` bit: `haircut` can answer nonzero.
uint256 constant CAP_REPORTED_LOSS = 256;
/// @dev A `capabilities()` bit: a partial repay can be held short (a minimum, `IHeldRepay`); the pool reads it.
uint256 constant CAP_HELD_REPAY = 512;
/// @dev A `capabilities()` bit: `haircut` is a fee each redemption pays, not a loss; the pool reads it.
uint256 constant CAP_REDEMPTION_FEE = 1024;
/// @dev Every bit the Router admits: the sixteen of its record. Bits 11 to 15 (2048 to 32768) are spare, for
/// capabilities a later pool may read and the Router never does: the Router admits them, so a later pool
/// implementation can give one a meaning without a new Router. This pool gives none of them a meaning and refuses
/// a kind that declares any of them (`InvalidConfig`, when it admits the venue), so no kind declares one until a
/// pool reads it.
uint256 constant KNOWN_CAPABILITIES = 65535;
/// @notice A read a kind whose `lltv` can fall (`CAP_MUTABLE_THRESHOLD`) answers beside `IFinancingAccount`: the
/// threshold its lender liquidates a venue's position past. Such a kind's `lltv` is the tighter of what its
/// lender lets the position borrow at and that threshold (`lltv`'s rule), so it may be a borrow ceiling under
/// it, or zero where the lender brakes the collateral, while the lender still liquidates at its own
/// threshold. The pool sizes "past saving" by this read (`FLAMMGateLib.liquidationWad`); a kind with no such
/// read is sized at one whole.
interface ILiquidationThreshold {
/// @dev The pool's read of {liquidationThreshold} failed with under a thirty-second of its gas left: the read ran
/// out of gas, which is no answer, so the pool's call reverts (`FLAMMGateLib.liquidationWad`).
error ThresholdReadStarved();
/// @notice The liquidation threshold of venue `id`'s position at its lender, WAD, live: at least `lltv(id)` and at
/// most one whole; zero where it cannot say (the lender unread, an id never registered, a position the
/// lender may liquidate past its health check).
function liquidationThreshold(bytes32 id) external view returns (uint64);
}
/// @notice One pool's account at one venue kind for one credit pair: it posts the pair's collateral token and borrows
/// and lends its loan token. Venues are `bytes32` ids for the protocol's parameters, validated against the
/// bound token pair at registration; positions are held in the account's own name. A frame's account, bound
/// to (zero, frame) (`FRAME_VENUE`), is one pool's account at one kind for every pair the pool puts
/// in the frame: it validates each venue against the pair the Router names at its registration and names that
/// pair's two tokens back for the venue's id ({IFrameAccount}). The Router
/// drives the normal path; only the bound pool drives the risk-reducing emergency path. Every mutator is
/// exact-delta: it reverts unless the venue's change matches the request. The Router pins each account to its
/// deployer's CREATE2 address for its bindings (`IAccountDeployer`), not to a shared codehash, so a kind may
/// keep its bindings as immutables.
/// @dev ADMISSION. The Router and the pool assume the following of every kind, and cannot be changed to relax it (the
/// first capability rule's spare bits and the two capability rules after it are the pool's: it refuses such a
/// kind when it admits the venue, which for a scheduled admission is when the schedule executes, as the account
/// exists only then):
/// - `capabilities()` declares only the bits above that the Router or the pool reads (0 to 10), which the Router
/// reads once, when it admits a venue, as the pool does: the Router refuses a kind that declares a bit outside
/// `KNOWN_CAPABILITIES` (`IMMRouter.UnknownCapability`), as it could not honour it, and admits the spare bits
/// 11 to 15, which this pool refuses (`InvalidConfig`), as it gives none of them a meaning;
/// - a kind that declares `CAP_LENT_COLLATERAL`, `CAP_PRICED_RELEASE` or `CAP_HELD_REPAY` also declares
/// `CAP_ACTION_GATES`: the Router caps every release at `collateralReleasable` under the gates and either of the
/// first two, and the pool asks what a venue can release now only where it is gated
/// (`FLAMMGateLib.releasableOf`), as an entry's preview reads a minimum position only there
/// (`FLAMMSharedLib.heldLegsCheck`);
/// - each one-field view ({actions}, {collateralReleasable}, {supplyWithdrawable} and the others beside
/// {capacity}) answers that field of {capacity} in the same state, but at the Aave V3 kind where one reserve's
/// configuration word cannot be read and the other's can, which only an upgrade of its Pool reaches: that word
/// refuses the whole capacity, but only the views that read it (`AaveV3ReadsLib._gate`). The pool reads the
/// action bits of a frozen venue mark, of an exit's and the emergency top-up's frozen-venue tests and of a
/// repay's refusal, what a gated venue can release, and a shared reserve's release and withdrawal figures, from
/// these views (`FLAMMGateLib.frozen`, `FLAMMFlowLib.proRata`, `FLAMMMaintainLib.emergency`,
/// `FLAMMGateLib.repayRefused`, `FLAMMGateLib.releasableOf`, `FLAMMGateLib.sharedFit` and `coverReleases`,
/// `FLAMMSharedLib.releaseRoom`'s legs), as the Router's hot paths do;
/// - a kind that declares `CAP_SHARED_LIQUIDITY` also declares `CAP_REPORTED_LOSS`: one reserve behind many
/// borrowers is a lender whose losses its suppliers bear, and an exit's slices there leave one unit's assets
/// and one per venue of the pool where they would take all but a millionth of a position
/// (`FLAMMFlowLib.proRata`), as each sibling leg can lower the position's read by that much. One kind number
/// is one reserve per token (a kind's deployer binds one lender: one Aave Pool, one comptroller), which the
/// pool's cash budget for covers and draws keys on (`FLAMMGateLib.sharedFit`): a second lender takes a
/// second kind number, and no lender is listed under two;
/// - supply and collateral are held in units that never rebase; `position` converts them at the accrued state;
/// - every read the Router takes values those units at their face, as the venue owes them: a loss that face
/// values overstate (a lender's reserve deficit) is reported through {haircut} alone, by a kind that declares
/// `CAP_REPORTED_LOSS` (the pool asks no other), which the pool applies to its NAV and to an exit's slices and
/// the Router never reads, so the post and supply bounds below hold at face. A kind reports only a loss its
/// lender records where the kind can read it: the comptroller kind (`CTokenAccount`) reports a redemption fee
/// alone, so its venues stay at face in NAV and in an exit's slices however much of that face the lender
/// cannot pay;
/// - a kind whose {haircut} is a fee the lender takes on each redemption (a Compound-style redemption fee), not a
/// loss face values overstate, declares `CAP_REDEMPTION_FEE` beside `CAP_REPORTED_LOSS` (the pool refuses the
/// fee bit alone when it admits the venue, as it does the shared one): a redemption of `assets` there burns them
/// grossed up by the fee, so the pool sizes an exit's collateral and supply legs there net of the haircut, which
/// burns the exiter's units exactly, and its exit maximum reads those net legs against what the venue can pay.
/// Without the bit an exit's slices leave at face and its payout is cut by the haircut, which custody keeps. The
/// pool records the bit when it admits the venue (`FLAMMStore.S.feeVenues`);
/// - where collateral accrues, a post of `assets` raises the position's collateral by at least `assets` less one
/// unit's assets (`collateralUnitsToAssets(id, 1)`) and one, and one unit is worth a negligible amount: every
/// borrow's health check allows that much, and the Router's plan pads each post there by that much, the unit's
/// assets capped at a millionth of one whole token as the release side's allowance is (`MMRouterLib._postSlack`,
/// `MMRouterLib._roundingSlack`): at a market whose unit a donation has raised (a nearly empty market) the pad
/// stays at that millionth, so a dust draw its rounding refuses is refused, and the market keeps no unit of a
/// post;
/// - where collateral accrues, {collateralOf} is `collateralUnitsToAssets` of {positionOf}'s collateral units in
/// the same state, by a conversion that never falls as the units grow: the Router values the units it posted
/// by it and recognizes the lesser of that and the collateral, with no read of the units (a frame kind keeps
/// the rule for each venue's part);
/// - where collateral accrues, a leg of another position at the same market (a sibling venue's redemption,
/// which lowers the shared exchange rate) lowers this position's collateral by less than one unit's assets plus
/// one: the Router allows that much collateral-side slack after a repay that lowers the debt, at
/// `CAP_ACCRUING_COLLATERAL` kinds only;
/// - a supply of `assets` raises the position's supplied assets by at least `assets` less one share's assets
/// (`supplySharesToAssets(id, 1)`) and one, and one share is worth a negligible amount, or the supply reverts:
/// the Router values no supply but a migration's, so a share price anyone can raise (a donation to a nearly
/// empty vault) would otherwise take the deposit;
/// - one id is one health basis: a liquidation of one id never reaches another's collateral (a kind whose
/// positions share one basis gives each id its own address, sub-account or position). A frame's account is the
/// one exception:
/// - its ids are the venues of every pair the pool put in the frame, which share one position at the lender and
/// so one health basis, and a liquidation there may reach every venue posting the seized token;
/// - its kind gives each token there the roles its lender's book allows (posted, or borrowed and supplied), and
/// a token supplied there is never seizable as another venue's collateral;
/// - venues sharing a collateral, a loan or a supply market each hold a recorded part of it and read that part
/// alone, the collateral parts never summing past what the account holds there, the debt parts never under
/// what it owes, the supply parts never past what it supplied, and units past the parts (a gift to the
/// account) are no venue's;
/// - a part moves with its venue's own legs and the lender's index: another venue's leg moves it by the lender's
/// rounding alone, never a debt part up nor a collateral part down, so the four-unit allowances below hold at
/// a frame as at a pair's own account;
/// - a liquidation moves the parts of the markets it reaches in proportion, and where it leaves a market at or
/// under a millionth of what its parts record and of the next post or borrow there, that leg may restart them:
/// what is left, at most a millionth of the leg, is then no venue's, or the borrowing venue's to owe; past
/// either, the parts stay in proportion;
/// - where a liquidation, or anyone's repay, left a shared loan market's debt off its parts' records, a part's
/// own legs there round by up to one more of the lender's units: a release's allowance covers that below a
/// lender index of about one and a half, any move into or out of that market rounds as much, and a refinance
/// that moves such a part may pass its own (`IMMRouter.Conservation`: the move is sized again);
/// - where a seizure left a shared collateral market's holding under its records, a post's part there may land
/// one more of the lender's units short of the post bound above, which the Router's plan pad and a borrow's
/// allowance absorb (about two units' worth);
/// - a kind that holds no frame answers no {IFrameAccount.tokensOf}, or no tokens for the id, which the Router
/// reads of every frame venue, and may refuse such an account where it deploys it or a venue where it
/// registers it;
/// - at a frame's account, each id names one pair:
/// - the id commits to the two tokens the Router wrapped into its registration, which {IFrameAccount.tokensOf}
/// answers (the Router refuses a venue whose id names others, `IMMRouter.VenueMismatch`), and a registration
/// changes neither another venue's threshold nor the account's mode at the lender (one e-mode, one pool
/// group, fixed by its first venue);
/// - its {borrowable}, {collateralReleasable} and {collateralPostable} report what the lender's liquidity, caps
/// and gates allow, as at a pair's own account, while the frame's other venues hold no net deficit at the
/// lender's prices and thresholds, as each venue's pin then keeps the frame whole;
/// - while they hold one, a borrow and a release are bounded too by the frame's spare room at the lender, so the
/// lender's own check passes on them; that room never raises a figure;
/// - the Router reads them before its own legs (a refinance reads its source's release before its bridge repays
/// there and its destination's borrow before the collateral lands, a plan each borrow before its own post)
/// and holds each venue at its pair's pin itself, so every leg it takes passes at the lender;
/// - a figure the spare room bounds counts no collateral those legs bring after the read, so a plan lends less
/// there and a move into such a frame may be refused; a kind's notes name any interest its read of that room
/// leaves out (`CTokenAccount` reads every market but the venue's own two as stored);
/// - its {returnToPool} takes the loan token of any of its venues;
/// - {collateralPostable} reports the room its lender leaves the venue's collateral market, net of what the
/// account holds for the venue's next post and parted among the account's own venues there, so one plan's
/// posts at one account fit that room together (`CTokenAccount` gives each an equal part):
/// - a post adds to the lender's market at most its assets and, where collateral accrues, what the account held
/// for it: a post too small to mint a unit, so under one unit's assets (`collateralUnitsToAssets(id, 1)`),
/// which the next post mints with its own;
/// - where the kind declares `CAP_SHARED_LIQUIDITY` (one reserve per token, as every deployer bound at its
/// number declares it, which the Router holds the pool's venues of the kind to when it admits one:
/// `IMMRouter.addVenue`) that room is one for every account of the kind, and the Router sizes each post of a
/// plan within what the plan's posts through the pair's other accounts there, each with one unit's assets
/// where collateral accrues, left of its venue's report (`MMRouterLib.buildPlan`), so a pair whose venues sit
/// at several of them (its own, its own under a later deployer, frames') never posts past it;
/// - an account that parts the room among several venues there has each part held to its share less those
/// posts whole, so a plan may leave room unposted that a later plan posts;
/// - at a kind without it, no two accounts' posts share one cap: its markets cap no post, or each position's
/// own;
/// - the Router bounds a pool's venues by their number alone (`MAX_VENUES`), never a pro-rata exit's gas, which
/// grows with the pool's live positions, each repaid and released in the exit, and with what each kind's legs
/// price (a lender that prices more markets or reserves on a release, a frame's release every market its account
/// entered, a gift's collateral flag left set), nor a releasing swap's, which grows with the venues it reads,
/// those where its input repays a debt and those it walks to release collateral of the token it pays out, and
/// with what their legs price, and can grow faster per venue than an exit's, against the 2^24 gas one
/// transaction may take (EIP-7825). The curator keeps a pool's positions within what one exit and one releasing
/// swap carry; nothing checks it on chain;
/// - a repay never reverts on its size or on a price:
/// - where a venue refuses a partial repay (a minimum position valued at its own oracle, a burn of zero scaled
/// units), the kind repays what the venue takes, down to that minimum, or nothing while that price cannot be
/// read, and the Router returns the rest to the pool; a repay of the whole debt reads no price;
/// - a kind whose venue can hold a partial repay of more than dust short (a minimum position) declares
/// `CAP_HELD_REPAY` and answers `IHeldRepay.minimumDebt`, never reverting and within
/// `MMRouterLib.MINIMUM_READ_GAS` (1,000,000 gas): the Router reads it by a static call of that much gas and
/// passes over a venue whose read reverts, answers short or runs past it. The pool records the bit when it
/// admits the venue (`FLAMMStore.S.heldRepayVenues`);
/// - such a venue refuses a borrow or a supply that leaves its position under the minimum, and the Router's plan
/// and supply cascade pass over a slice or a take there that would;
/// - a curator's or keeper's move into such a venue (`IMMRouter.migrateSupply`, `IMMRouter.refinanceDebt`) that
/// would leave its position under the minimum is not passed over: it reverts at the venue, which refuses it,
/// and the move's caller sizes it again;
/// - an entry's preview refuses such a leg as the entry does, and one reaching the minimum exactly, which the
/// lender's rounding decides (`FLAMMSharedLib.heldLegsCheck`);
/// - a payout's or a rotation's quote, which reads the plan, refuses where the swap's plan does on the state
/// both read. Two settlement steps move that state between the quote's read and the swap's plan: the
/// withdrawal of the payout pair's lent backing, which frees post room under the posting market's supply cap,
/// and a release out of a reserve the draw's venue shares while that venue is held under the reserve's cash by
/// its debt cap, its collateral or its rate ceiling. There a quoted swap can revert
/// `IMMRouter.InsufficientLiquidity` by the slice its plan passes over, which is under one minimum position,
/// and a swap the quote refuses can fill; a swap never fills under its quote;
/// - a cover's quote counts the release of a partial repay only where the repay leaves the debt over that
/// minimum by the lenders' rounding (`FLAMMGateLib.holdsRepay`; at a shared reserve, what it may release still
/// comes off the reserve's cash), and a rotation repays the venue whole or passes it over;
/// - a kind whose venue refuses every repay for a while (a pause, a broker) clears `CAN_REPAY` under
/// `CAP_ACTION_GATES` while it does;
/// - a lender's rounding moves debt by at most four base units: a partial repay leaves at most four over the
/// exact rest (`MMRouterLib.RELEASE_SLACK`), and a refinance's repay and borrow together change the two venues'
/// summed debt by at most four (`MMRouterLib.REFINANCE_SLACK`). A kind that rounds coarser has those releases
/// and refinances refused by the excess;
/// - a collateral release reads no price at zero debt unless the kind reports `CAP_PRICED_RELEASE`: its release
/// then reads the venue's oracle, owing or not, and while that oracle cannot be read its {collateralReleasable}
/// is zero, so the Router leaves the collateral posted, waiting for the oracle, and never asks the venue for a
/// release that would fail on that oracle;
/// - what {collateralReleasable} and {supplyWithdrawable} report can be paid: a venue that pays a release or a
/// withdrawal in whole units (a Compound-style market, whose redemption burns at least one unit) reports
/// nothing while its cash is under one unit's payout, as no redemption can be paid then; the pool's exit
/// maximum and its cash budget read those figures as payable;
/// - no view the Router or the pool reads reverts ({capacity} and its single fields {borrowable},
/// {supplyWithdrawable}, {suppliable}, {collateralReleasable}, {collateralPostable} and {actions}, with
/// `IActionsOf.actionsOf` where the kind answers it,
/// {positionOf}, {position}, {debtOf}, {collateralOf}, {lltv}, the two conversions, {healthy}, {oraclePrice},
/// {borrowRateAfter}, {ceilingBorrowSlice} and {haircut}): the pool reads every live venue on every flow, and
/// retiring a venue reads it, so one revert would stop every flow of the pool and keep the venue from being
/// retired:
/// - while its protocol cannot be read, a kind catches the revert, answers from its last good position, neither
/// zeroed nor marked down, and refuses every action: `actions` all clear, every capacity zero, {healthy} false
/// while it owes, {oraclePrice} and {borrowRateAfter} `ok == false` (so {ceilingBorrowSlice} zero), and every
/// leg refused; but at the Aave V3 kind while only one reserve's configuration word cannot be read, only the
/// views that read that word refuse, and a leg whose views read only the other still goes (the one-field
/// views' bullet above);
/// - a kind never answers so when the failed call ran out of gas (it left the kind at most 1/64 of the gas it
/// forwarded): it reverts instead, so no caller can make a venue look frozen by starving it;
/// - only under `CAP_ACTION_GATES` does the Router read every refusal (`actions` and each capacity), so a kind
/// that can become unreadable declares it;
/// - kind 0 cannot become so, as the immutable Morpho Blue it binds and the rate model whose codehash it pins
/// answer every read; a kind built from it for another venue that can refuse an action, cap a leg or become
/// unreadable (a pausable or upgradeable core, a rate model behind a proxy) declares `CAP_ACTION_GATES` and
/// `CAP_PROTOCOL_CAPS`;
/// - the pool reads a venue that holds a position and allows no action as a frozen venue mark: its value views
/// refuse (`VenueFrozen`), and no flow moves that venue's share through idle cash;
/// - {position}'s `debt` is zero exactly when {positionOf}'s `borrowShares` is: the Router tells an owing venue
/// from either read (its drawn sets and a retirement from the raw shares, a plan's draw test and its `book` from
/// the debt), so the two must agree;
/// - {positionOf} is a raw read of the position's units, with no accrual and no rate model, that answers wherever
/// {position} does: the Router's drawn sets and retirements and the pool's emergency path read it while a
/// venue's rate model cannot be read;
/// - debt never matures and is prepayable whenever its venue takes a repay (a kind under `CAP_ACTION_GATES`
/// reports a refused repay as a cleared `CAN_REPAY`), credit and debt never net, and one id fails as a unit;
/// - a position without debt gains none until the Router borrows or refinances onto it: no one else can borrow
/// for it or move debt onto it, as a redistribution of other borrowers' debt would (the pool's debt-free flags,
/// `FLAMMStore.TokenCfg.debtFree`, rely on it);
/// - one position's collateral units and supply shares fit in 128 bits, and so do its debt and its collateral
/// assets: the Router tracks what it posted and supplied as uint128, and a leg that would carry either past
/// 2^128 - 1 reverts; a repay's snapshot packs the venue's debt and collateral assets in 128 bits each.
/// What varies by kind is reported, never assumed: each leg's liquidity, caps and rate limits through
/// {capacity}, a refused action as zero capacity and a cleared `actions` bit, the threshold through {lltv}, and
/// the position's own borrow rate through {borrowRateAfter}.
interface IFinancingAccount {
/// @notice {refinance} at a kind with no atomic move.
error Unsupported();
/// @notice What one position can move now, within the venue's liquidity, caps and rate limits; a refused action
/// reads zero, an unbounded leg `type(uint256).max`. Native units: `borrowable`, `suppliable` and
/// `supplyWithdrawable` of the loan token, `collateralReleasable` of the collateral token before any health
/// check (a kind that never lends collateral bounds it by nothing while it allows a release; under
/// `CAP_PRICED_RELEASE`, zero while the venue's oracle cannot be read), and `collateralPostable` of the
/// collateral token a post may add before the venue's own cap on its collateral refuses (a kind that caps
/// no post bounds it by nothing while it takes posts).
struct Capacity {
uint256 borrowable; // loan-token base units
uint256 suppliable; // loan-token base units
uint256 supplyWithdrawable; // loan-token base units
uint256 collateralReleasable; // collateral-token base units
uint8 actions; // the `CAN_` bits of what the venue lets this position do now
uint256 collateralPostable; // collateral-token base units
}
/// @notice The Router, the one caller of the normal path (`NotRouter`, on the kind's base, for any other).
function ROUTER() external view returns (address);
/// @notice The pool whose positions this account holds, the one caller of the emergency path (`NotPool` for any
/// other).
function POOL() external view returns (address);
/// @notice The account's collateral token, which it posts; zero for a frame's account, whose venues name their own.
function COLLATERAL_ASSET() external view returns (address);
/// @notice The account's loan token, which it borrows and lends; for a frame's account, its frame.
function LOAN_ASSET() external view returns (address);
/// @notice The account's venue kind; one kind number is one lender (ADMISSION).
function KIND() external view returns (uint8);
/// @notice The kind's `CAP_` bits, which the Router and the pool read once, when each admits a venue.
function capabilities() external view returns (uint256);
// ---- normal path (router)
/// @notice Registers a venue from protocol-specific params; returns its id and current threshold. Idempotent. A
/// frame's account takes `abi.encode(collateral, debt, params)`: the venue's pair's two tokens, then its
/// params.
/// @param venueParams The kind's parameters, or a frame's wrapped form.
/// @return id The venue's id at this account.
/// @return lltvWad The venue's threshold now, WAD ({lltv}).
function registerVenue(bytes calldata venueParams) external returns (bytes32 id, uint64 lltvWad);
/// @notice Posts `assets` of the collateral token the Router has moved here.
/// @param id The venue's id.
/// @param assets The amount, in collateral-token base units.
/// @return units The collateral units minted.
function supplyCollateral(bytes32 id, uint256 assets) external returns (uint256 units);
/// @notice Releases exactly `assets` of collateral.
/// @param id The venue's id.
/// @param assets The amount, in collateral-token base units.
/// @param to The pool, or another account the Router registered for it (`BadReceiver` otherwise).
/// @return units The collateral units burned.
function withdrawCollateral(bytes32 id, uint256 assets, address to) external returns (uint256 units);
/// @notice Borrows exactly `assets` of the loan token for the pool, or reverts.
/// @param id The venue's id.
/// @param assets The amount, in loan-token base units.
/// @param to The receiver, which must be the pool (`BadReceiver`).
function borrow(bytes32 id, uint256 assets, address to) external;
/// @notice Repays up to `assets` from the loan tokens held here: in full where `assets` covers the accrued debt,
/// else what the venue takes of it (a minimum position, a held full exit: ADMISSION); never reverts on
/// either.
/// @param id The venue's id.
/// @param assets The most to repay, in loan-token base units.
/// @return repaid What the venue took; the Router sends the rest back through {returnToPool}.
function repay(bytes32 id, uint256 assets) external returns (uint256 repaid);
/// @notice Lends `assets` of the loan token the Router has moved here.
/// @param id The venue's id.
/// @param assets The amount, in loan-token base units.
/// @return shares The supply shares minted: zero only where a kind holds a supply too small to mint one for its
/// next (ADMISSION's bound on a supply); a kind whose lender would take it for nothing reverts.
function supply(bytes32 id, uint256 assets) external returns (uint256 shares);
/// @notice Withdraws supplied loan asset by exact `assets` or exact `shares` (exactly one nonzero) to the
/// pool, to this account, or to another account of the same pool.
/// @param id The venue's id.
/// @param assets The exact amount, in loan-token base units, or zero.
/// @param shares The exact supply shares, or zero.
/// @param to The receiver (`BadReceiver` for any other than the three above).
/// @return withdrawn What the venue paid, in loan-token base units.
/// @return sharesBurned The supply shares burned.
function withdraw(bytes32 id, uint256 assets, uint256 shares, address to)
external
returns (uint256 withdrawn, uint256 sharesBurned);
/// @notice Returns exactly `amount` of `token`, the loan token of the venue the Router repays (the account's loan
/// asset, or at a frame's account any of its venues'), to the pool; never a balance sweep. Any other token
/// reverts `VenueMismatch`.
/// @param token The loan token.
/// @param amount The amount, in the token's base units.
function returnToPool(address token, uint256 amount) external;
/// @notice Brings the venue's interest to now, so the reads that follow in the block take the accrued state. Best
/// effort: a failed accrual changes nothing, and a kind that never accrues does nothing.
/// @param id The venue's id.
function accrue(bytes32 id) external;
/// @notice Moves `assets` of debt (`0` = all) and `collateralMove` collateral from `src` to `dst` in one
/// step; a kind without `CAP_ATOMIC_REFINANCE` reverts `Unsupported`. The Router counts the move one
/// collateral unit per asset, so it bridges a kind whose collateral accrues instead.
/// @param src The source venue's id.
/// @param dst The destination venue's id.
/// @param assets The debt to move, in loan-token base units.
/// @param collateralMove The collateral to move, in collateral-token base units.
/// @return moved The debt moved.
function refinance(bytes32 src, bytes32 dst, uint256 assets, uint256 collateralMove) external returns (uint256 moved);
// ---- emergency path (bound pool only)
/// @notice Repays up to `assets` from the loan tokens the pool has moved here, and sends back to the pool what the
/// venue does not take.
/// @dev Each kind must state which of these survive each of its outage modes; the pool assumes none does. Morpho
/// Blue with its IRM unreadable: only `emergencyTopUp` on an indebted position stays live (`supplyCollateral`
/// alone does not accrue), and an `emergencyRepay` at a position with no debt repays nothing and returns the
/// assets; the rest revert until the market reads again.
/// @param id The venue's id.
/// @param assets The most to repay, in loan-token base units.
/// @return repaid What the venue took.
function emergencyRepay(bytes32 id, uint256 assets) external returns (uint256 repaid);
/// @notice Posts `assets` of the collateral token the pool has moved here onto a position that owes (`NoDebt`
/// otherwise).
/// @param id The venue's id.
/// @param assets The amount, in collateral-token base units.
/// @return units The collateral units minted.
function emergencyTopUp(bytes32 id, uint256 assets) external returns (uint256 units);
/// @notice Withdraws supplied loan asset to the pool by exact `assets` or exact `shares`, as {withdraw}. A kind may
/// read a request for the whole balance in its own form (`AaveV3Account`).
/// @param id The venue's id.
/// @param assets The amount, in loan-token base units, or zero.
/// @param shares The supply shares, or zero.
/// @return withdrawn What the venue paid, in loan-token base units.
function emergencyWithdrawSupplied(bytes32 id, uint256 assets, uint256 shares) external returns (uint256 withdrawn);
/// @notice Releases `assets` of collateral to the pool from a position that owes nothing (`DebtOutstanding`
/// otherwise).
/// @param id The venue's id.
/// @param assets The amount, in collateral-token base units.
function emergencyWithdrawCollateral(bytes32 id, uint256 assets) external;
// ---- views
/// @notice The lowest threshold this position can be held to without a new action of the pool, live: the tighter
/// of the venue's borrow ceiling and liquidation threshold, a ramp's target included.
/// @param id The venue's id.
/// @return The threshold, WAD.
function lltv(bytes32 id) external view returns (uint64);
/// @notice The position's raw units, with no accrual and no rate model (ADMISSION).
/// @param id The venue's id.
/// @return supplyShares The supply shares it holds.
/// @return borrowShares The borrow shares it owes.
/// @return collateralUnits The collateral units it holds.
function positionOf(bytes32 id)
external
view
returns (uint256 supplyShares, uint256 borrowShares, uint256 collateralUnits);
/// @notice The position at the accrued state, or the last good one while the protocol cannot be read: it never
/// reverts (ADMISSION). Its `collateral` and `debt` are {collateralOf} and {debtOf} in the same state: the
/// Router reuses them.
/// @param id The venue's id.
/// @return collateral The collateral, in collateral-token base units.
/// @return supplyShares The supply shares it holds.
/// @return supplied Those shares' worth, in loan-token base units.
/// @return debt The debt, in loan-token base units.
function position(bytes32 id)
external
view
returns (uint256 collateral, uint256 supplyShares, uint256 supplied, uint256 debt);
/// @notice The position's debt at the accrued state, in loan-token base units.
function debtOf(bytes32 id) external view returns (uint256);
/// @notice The position's collateral at the accrued state, in collateral-token base units.
function collateralOf(bytes32 id) external view returns (uint256);
/// @notice What `units` of collateral are worth at the accrued state, rounded down.
/// @param id The venue's id.
/// @param units The collateral units ({positionOf}).
/// @return The worth, in collateral-token base units.
function collateralUnitsToAssets(bytes32 id, uint256 units) external view returns (uint256);
/// @notice What `shares` of supply are worth at the accrued state, rounded down.
/// @param id The venue's id.
/// @param shares The supply shares ({positionOf}).
/// @return The worth, in loan-token base units.
function supplySharesToAssets(bytes32 id, uint256 shares) external view returns (uint256);
/// @notice `capacity(id).borrowable` alone, in the same state; so is each view below its own field of {capacity}
/// (`supplyWithdrawable`, `suppliable`, `collateralReleasable`, `collateralPostable`, `actions`), but at
/// the one exception ADMISSION names. The Router's hot paths read the one field they need where
/// {capacity} would build them all.
function borrowable(bytes32 id) external view returns (uint256);
/// @notice `capacity(id).supplyWithdrawable` alone, in the same state, but at the Aave V3 kind while only the
/// collateral reserve's configuration word cannot be read (ADMISSION).
function supplyWithdrawable(bytes32 id) external view returns (uint256);
/// @notice `capacity(id).suppliable` alone, in the same state.
function suppliable(bytes32 id) external view returns (uint256);
/// @notice `capacity(id).collateralReleasable` alone, in the same state, but at the Aave V3 kind while only the
/// loan reserve's configuration word cannot be read (ADMISSION).
function collateralReleasable(bytes32 id) external view returns (uint256);
/// @notice `capacity(id).collateralPostable` alone, in the same state, but at the Aave V3 kind while only the
/// loan reserve's configuration word cannot be read (ADMISSION).
function collateralPostable(bytes32 id) external view returns (uint256);
/// @notice `capacity(id).actions` alone, in the same state.
function actions(bytes32 id) external view returns (uint8);
/// @notice What the position can move now: each leg's room and the actions the venue allows.
function capacity(bytes32 id) external view returns (Capacity memory);
/// @notice The borrow rate this position pays after its leg (`deltaBorrow` more debt, `deltaSupplyDown` less
/// supply), at the accrued state, so a quote before any leg and the check after the withdrawal agree.
/// `ok == false`, never a clamped answer, when `deltaSupplyDown` would reach the venue's supply, the
/// post-state is undefined or the rate cannot be read.
/// @param id The venue's id.
/// @param deltaBorrow The added debt, in loan-token base units.
/// @param deltaSupplyDown The supply taken out, in loan-token base units.
/// @return ok Whether the rate reads.
/// @return ratePerSecWad The rate, per second, WAD.
function borrowRateAfter(bytes32 id, uint256 deltaBorrow, uint256 deltaSupplyDown)
external
view
returns (bool ok, uint256 ratePerSecWad);
/// @notice The Router's trim of a borrow slice over the venue's rate ceiling: zero where {borrowRateAfter}
/// `(id, deltaBorrow, deltaSupplyDown)`, at the slice's start, is not `ok` or reads over `maxRate`; else
/// the low end `lo` of a bisection of `[0, hi]` that, while `hi - lo > hi / 10_000 + 1` (`hi` its
/// shrinking upper end), reads {borrowRateAfter}`(id, deltaBorrow + mid, deltaSupplyDown)` at
/// `mid = lo + (hi - lo) / 2` and moves `lo` up to `mid` where that read is `ok` and at most `maxRate`,
/// else `hi` down to it. It answers exactly what that search over {borrowRateAfter} would, so it errs low;
/// a kind may take the reads no step moves once.
/// @param id The venue's id.
/// @param deltaBorrow The debt the plan already adds here, in loan-token base units.
/// @param deltaSupplyDown The supply the plan already takes out, in loan-token base units.
/// @param hi The slice's upper end, in loan-token base units.
/// @param maxRate The rate ceiling, per second, WAD.
/// @return slice The slice, in loan-token base units.
function ceilingBorrowSlice(bytes32 id, uint256 deltaBorrow, uint256 deltaSupplyDown, uint256 hi, uint256 maxRate)
external
view
returns (uint256 slice);
/// @notice The venue's own price: loan base units per collateral base unit, scaled by 1e36. While its pair's
/// venue-oracle band is on, `ok == false` refuses the paths the venue prices (a borrow, a priced release
/// of an indebted venue's collateral, a refinance onto it) and an admission given a price; with the band
/// off no path reads it and the venue's own checks stand alone.
/// @param id The venue's id.
/// @return ok Whether the price reads.
/// @return price The price, scaled by 1e36.
function oraclePrice(bytes32 id) external view returns (bool ok, uint256 price);
/// @notice The venue's own health predicate, as the market enforces it when collateral leaves. Morpho Blue: no
/// borrow shares, or `collateral * price / 1e36 * LLTV >= debt` at the accrued state (debt rounded up,
/// bound down); with debt, false when the oracle cannot be read.
function healthy(bytes32 id) external view returns (bool);
/// @notice The share of face value the venue cannot pay on this position's collateral and on its supply, WAD each
/// (a lender's reserve deficit spread over its suppliers), zero where it can pay all. Every other read
/// values units at face; the pool applies this to its NAV and to an exit's slices, and the Router never
/// reads it. A kind that can answer nonzero declares `CAP_REPORTED_LOSS`: the pool asks no other. It is
/// only as complete as what the lender records: the comptroller kind (`CTokenAccount`) answers a
/// redemption fee alone, as its lender records no bad debt, so a loss there reads zero.
/// @param id The venue's id.
/// @return collateralLossWad The share lost on its collateral, WAD.
/// @return supplyLossWad The share lost on its supply, WAD.
function haircut(bytes32 id) external view returns (uint64 collateralLossWad, uint64 supplyLossWad);
}
/// @notice A frame's account (`FRAME_VENUE`), which a kind that holds frames answers: the Router reads it of
/// every venue it admits there and refuses one whose tokens are not its pair's (`IMMRouter.VenueMismatch`),
/// so an id there names one pair for good, and a kind that answers nothing takes no frame venue.
interface IFrameAccount {
/// @notice The two tokens venue `id` was registered for, as the Router wrapped them; zero for an id never
/// registered. Never reverts.
/// @param id The venue's id.
/// @return collateral The venue's collateral token.
/// @return debt The venue's debt token.
function tokensOf(bytes32 id) external view returns (address collateral, address debt);
/// @notice Whether the lender counts venue `id`'s posted collateral in the account's health now, whatever the
/// venue's threshold reads: {IFinancingAccount.lltv} may be a borrow ceiling, which reads zero where the
/// lender lends nothing more on a collateral it still counts at its liquidation threshold, and reads live
/// where the lender counts the collateral for nothing (Aave V3: the account's collateral flag on the token
/// is down). False while that cannot be read, and for an id never registered. The pool reads it of a
/// frame's venues alone, for the frame's sums, its due venues and its top-ups through a mate
/// (`FLAMMTopUpLib`); the Router never reads it. Never reverts.
/// @param id The venue's id.
/// @return Whether the lender counts the venue's collateral.
function collateralCounted(bytes32 id) external view returns (bool);
}
/// @notice A view a kind may answer beside {IFinancingAccount.actions}, sized to the actions a reader wants: the Router
/// reads a venue's gate through it (`MMRouterLib.canAct`) where the venue's account answered it at admission
/// as its `actions` (`IMMRouter.addVenue`), and through `actions` elsewhere, so a kind may add it or not.
interface IActionsOf {
/// @notice `actions(id) & want`, in the same state, reading only what those actions need: a bit reads the same
/// whatever else `want` names, but at the Aave V3 kind where one reserve's configuration word cannot be
/// read and the other's can: {IFinancingAccount.actions} reads none there, while a bit that needs only the
/// readable word answers by it, so with the collateral's word unreadable a repay passes the Router's gate
/// (`MMRouterLib.canAct`). Never reverts (ADMISSION).
/// @param id The venue's id.
/// @param want The `CAN_` bits asked about.
/// @return The bits of `want` the venue allows now.
function actionsOf(bytes32 id, uint8 want) external view returns (uint8);
}
src/interfaces/core/mm/IHeldRepay.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The minimum position of a kind that declares `CAP_HELD_REPAY`, which the pool reads (`IFinancingAccount`
/// ADMISSION): a partial repay that leaves the debt at least `floor`, as the venue values it, is taken whole,
/// and a borrow or a supply that leaves the position under it is refused, so the Router's plan and supply
/// cascade pass over a slice there that would (`MMRouterLib`), with the lenders' rounding past it where the
/// lender's check can read the position low: a supply, whose shares it mints rounded down, and a borrow where
/// the venue owes.
interface IHeldRepay {
/// @notice The minimum debt at venue `id`, in loan-token base units; `ok` false while the venue cannot value it,
/// when a partial repay may take nothing. Never reverts, and answers within `MMRouterLib.MINIMUM_READ_GAS`
/// (1,000,000 gas), an admission rule of every kind that declares `CAP_HELD_REPAY`: the Router's plan and
/// supply cascade pass over a venue whose read reverts, answers short or runs past it.
function minimumDebt(bytes32 id) external view returns (bool ok, uint256 floor);
}
/// @notice The bound a kind's lender takes repays up to, which a debt can pass (a Compound-style market's total
/// borrows, which a sole borrower's debt passes by a remainder no repay takes: `CTokenAccount`), and the market
/// it is the bound of, which no capability bit declares: every venue borrowing from that market repays out of
/// the one bound, so a repay there takes at most what the repays before it, at any of the pool's venues, left
/// of it. The pool reads it of a cover pair's venues whose kind can refuse an action and declares no
/// `CAP_HELD_REPAY` (`FLAMMLawLib`'s cover check), and its exit maximum of every indebted venue whose kind
/// declares no `CAP_HELD_REPAY`, each walking the venues in the order the swap or the exit repays them
/// (`FLAMMExitMaxima`); a venue that does not answer is read as taking a repay of its whole debt whole.
interface IRepayable {
/// @notice The most venue `id`'s lender takes of repays now, in loan-token base units (`type(uint256).max` where it
/// reads none), and the market whose bound it is, one address per bound across every account of the
/// kind. Never reverts.
function repayable(bytes32 id) external view returns (uint256 bound, address market);
}
src/interfaces/core/mm/IMMRouter.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 {IFinancingAccount} from "src/interfaces/core/mm/IFinancingAccount.sol";
import {WAD as ONE_WAD} from "src/libraries/Constants.sol";
/// @dev One in WAD, the 18-decimal fixed point of LTVs, bands, rates and USD prices.
uint256 constant WAD = ONE_WAD;
/// @dev A venue oracle's price scale: debt base units per collateral base unit, times 1e36.
uint256 constant ORACLE_PRICE_SCALE = 1e36;
/// @dev Tokens a pool may list, its pool asset (token 0) included; the owed and backing sets are 16-bit masks over
/// them.
uint256 constant MAX_TOKENS = 16;
/// @dev Credit pairs a pool may hold, retired ones included: a retired pair keeps its index and its accounts'
/// addresses. Every ordered pair of two distinct tokens, each added once, so the limit never binds before the
/// token list does; a pair index is a uint8.
uint256 constant MAX_PAIRS = MAX_TOKENS * (MAX_TOKENS - 1);
/// @dev The Morpho Blue venue kind. A constant, not an enum: governance adds kinds through
/// `FLAMMFactory.setAccountDeployerOf`.
uint8 constant VENUE_KIND_MORPHO_BLUE = 0;
/// @dev Venues the Router holds for one pool at once; a retired venue's slot (and id) is reused by the next admission,
/// and the pool's own records take fewer (`FLAMMStore.MAX_POOL_VENUES`). The Router bounds their number alone,
/// never a pro-rata exit's gas, which grows with the pool's live positions, each repaid and released in the exit,
/// nor a releasing swap's, which grows with the venues it reads, those where its input repays a debt and those it
/// walks to release collateral of the token it pays out (`IMMRouter.reclaimBestEffort`), and can grow faster per
/// venue than an exit's, against the 2^24 gas one transaction may take (EIP-7825). A swap whose release takes it
/// past that gas reverts at every gas limit while the release is due, where no venue's release alone takes three
/// million gas (a release that began with that much and failed starved ends the walk as the lender's burn:
/// `reclaim`). The curator's or keeper's `Release` on the maintenance path (`FLAMM.maintain`) releases with no
/// swap what its caller names, so it clears a release due before a swap, never one the swap's own repay makes due.
/// The curator keeps a pool's positions within what one exit and one releasing swap carry; nothing checks it on
/// chain.
uint256 constant MAX_VENUES = 64;
/// @dev `IMMRouter.minLltv` where no venue of the pair binds the pin: none can borrow and none owes anything. A zero
/// threshold binds.
uint256 constant NO_VENUE_LLTV = type(uint256).max;
/// @dev A status bit of a venue (`IMMRouter.VenueView.status`, one byte of bits; zero is a live venue, in every
/// priority order). Retired: the slot holds no position the Router reads, and the next admission may reuse it. A
/// retired venue is not fenced.
uint8 constant VENUE_RETIRED = 1;
/// @dev A status bit of a venue, as {VENUE_RETIRED}. Fenced: locked by its pool (`IMMRouter.lockVenue`) until the pool
/// lifts the lock or the venue retires.
uint8 constant VENUE_FENCED = 2;
/// @dev The word that opens a frame venue's params (`IMMRouter.addVenue`): `abi.encode(FRAME_VENUE, frame, params)`
/// puts the venue in frame `frame` (a tag the pool picks, read as an address) at its kind: one account, one
/// position at the lender, shared by the venues of every pair the pool puts in that frame, instead of the pair's
/// own account. A pool chooses per venue: plain params (the pair's own account, the default), one frame for every
/// pair at a lender, or several frames; a pair may hold venues at its own account and at several frames of one
/// kind at once.
bytes32 constant FRAME_VENUE = keccak256("FLAMM.frameVenue");
/// @notice A pair's price in its venues' price scale: debt base units per collateral base unit, scaled by 1e36, from
/// the two tokens' USD prices (WAD per whole token) and decimals (each at most 18): `usdColl * 10^(36 +
/// debtDecimals - collDecimals) / usdDebt`, rounded down, in one `mulDiv`. Zero, an unchecked price, when
/// either USD price is zero or the result would not fit a word, so an absurd answer never reverts a read. The
/// Router, the pool and the periphery price every pair with this function alone, so each direction comes from
/// the two USD prices and none is the inverse of another.
function pairPrice36(uint256 usdColl, uint256 usdDebt, uint8 collDecimals, uint8 debtDecimals) pure returns (uint256) {
if (usdColl == 0 || usdDebt == 0) return 0;
uint256 m = 10 ** (36 + uint256(debtDecimals) - uint256(collDecimals));
if (usdColl / usdDebt >= type(uint256).max / m) return 0;
return Math.mulDiv(usdColl, m, usdDebt);
}
/// @notice The shared money-market router. Each pool lists tokens (token 0 is its pool asset) and credit pairs over
/// them: a pair borrows its debt token against its collateral token, at venues held in its (pair, kind)
/// financing accounts, or in a frame's account its pool shares among several pairs at a kind (`FRAME_VENUE`).
/// Pool-scoped calls act on `msg.sender`'s namespace, and refuse a caller no `registerPool` registered
/// (`NotRegistered`), `accrueExcept` aside, which accrues nothing for one; `registerPool` is Factory-only; the
/// protocol owner (`protocolSafe`) pauses and unpauses (`setGlobalPaused`). Amounts are native base units.
/// Inbound legs pull from the pool's allowance what they consume: a post pulls the venue's collateral token, a
/// repay, supply or bridge its debt token, and a repay hands back in the same call what its lender did not
/// take. Every mutating call but `setGlobalPaused` holds the Router's transient lock
/// (`ReentrancyGuardLib.Reentrant`), and the views that read positions through a plan or a walk (`drawn`,
/// `venuePosition`, `book`, `fundingCeiling`, `fundingCollateral`, `borrowRoom`, `supplyRoom`, `reclaimable`)
/// refuse while it is held.
/// @dev The protocol owner. `protocolSafe`, the Factory's `PROTOCOL_SAFE`, is the protocol owner's address on chain:
/// as deployed a `FactoryAdmin` forwarder, whose `SAFE` is the owner's multisig. The rewards every account
/// sends there, and the fees paid to the Factory's `protocolFeeReceiver` while it names that address, sit there
/// until the protocol owner moves them with `execute`.
///
/// Prices. Every priced call takes `usd`, the pool's checked USD price of each of its tokens (WAD per whole
/// token, indexed as the pool's token list, exactly `tokenCount` long, else `BadPriceVector`); zero means
/// that token is unchecked. The Router prices each venue at its own pair ({pairPrice36} of the venue's
/// collateral and debt tokens), so no caller hands it a pair's price. A priced path refuses an unchecked pair;
/// the price gates only risk-increasing legs.
///
/// No circularity. The owed set is the tokens some unfenced venue lends the pool, the backing set the
/// collateral tokens of those venues. A borrow at a venue that owes nothing, on pair (a -> b), is refused
/// (`DrawOutsideDrawnSet`) when a is owed, when b backs a debt, or when b would raise the owed set past
/// `maxDrawnTokens`. Every path that can start a debt checks it (`borrow`, `fund`'s borrow phase, `borrowRoom`
/// and `fundingCeiling`), `refinanceDebt` stays inside one pair onto a venue whose pair already owes, and
/// `lockVenue` lifts no fence where the venue would make the sets circular, so among the unfenced venues no
/// token is ever owed and backing at once: a pool is never long and short one pair, and no chain a -> b -> c is
/// drawn. A fenced venue's debt and collateral sit outside both sets.
///
/// Fences. `lockVenue` fences one live venue, whatever it holds, so a pool can stand clear of one lender that
/// stops answering its legs while that lender's other markets, and other lenders of the same tokens, stay live;
/// a pool fences every venue naming a token to take the token out of its pool book.
/// - A fenced venue's borrow and supply switches go off and cannot turn on while it is fenced
/// (`VenueIsFenced`), and it leaves the four priority orders.
/// - `book`, `accrueExcept`, the cascades (`repayCascade`, `supplyCascade`, `withdrawCascade`, `reclaim`,
/// `reclaimBestEffort`, `reclaimable`), the plans (`fund`, `fundingCeiling`, `fundingCollateral`,
/// `borrowRoom`) and the drawn sets pass a fenced venue; the caps, `minLltv` and the by-id views still count
/// it.
/// - It takes no leg that adds to it or moves it to another venue (a post, a borrow, a supply, a priced release
/// while it owes, a refinance or a migration at either end; `borrow` and `supply` refuse on its switches) and
/// stays open to the by-id legs that unwind it: `repay`, a proportional `withdrawCollateral`,
/// `withdrawSupplied`, `syncManaged`, `recognizeCollateral` and, once it holds nothing, `retireVenue`.
/// - The pool's `lockVenue` lifts the fence: the venue rejoins the priority orders, last.
/// - A frame's account (`FRAME_VENUE`) is one position at its lender for all its venues: the Router refuses a
/// venue joining it while one there is fenced (`VenueIsFenced`), and no more, as each of its other venues
/// takes every leg its own state allows, so the pool fences, lifts and gives up a frame's venues together.
interface IMMRouter {
/// @notice A listed token as the Router records it for a pool ({token}).
struct TokenView {
address token; // the token's address
uint8 decimals; // at most 18
uint256 scale; // 10^(18 - decimals): lifts the token's base units to 18 decimals
uint128 supplyCap; // across every venue lending it, in the token's base units; zero: none
bool retired; // terminal: the token takes no new pair and no supply cap
}
/// @notice A credit pair as the Router records it ({pair}): it borrows token `debt` against token `coll`.
struct PairView {
uint8 coll; // the collateral token's index in the pool's list
uint8 debt; // the debt token's index in the pool's list
uint64 pinLtvWad; // the LTV a borrow is held to, WAD
uint64 safetyGapWad; // the room a borrowing venue's threshold keeps over the pin, WAD; written once
uint64 oracleBandWad; // how far a venue's own oracle may sit from the pair's price, WAD; zero: none is read
uint128 debtCap; // the pair's debt across its venues, in debt-token base units; zero: none
bool borrowEnabled; // the pair's borrow switch, beside each venue's own
bool retired; // terminal: its venues are retired and hold nothing
}
/// @notice A venue as the Router records it ({venue}), with its account's threshold read live.
struct VenueView {
address account; // the financing account that holds the position
bytes32 id; // the venue's id at that account
uint8 kind; // the venue kind, one lender
uint8 pair; // its credit pair's index
uint8 coll; // its pair's collateral token's index
uint8 debt; // its pair's debt token's index
uint64 lltvWad; // live: the account's threshold now
bool borrowEnabled; // the venue's borrow switch, beside its pair's
bool supplyEnabled; // the venue's supply switch
uint8 status; // VENUE_RETIRED and VENUE_FENCED bits; zero: live, in every priority order
uint128 debtCap; // the venue's debt, in debt-token base units; zero: none
uint128 supplyCap; // the venue's supply, in debt-token base units; zero: none
uint64 maxBorrowRateWad; // the highest borrow rate a borrow may leave, per second, WAD; zero: none
}
/// @notice `pool` is registered, with `poolAsset` as its token 0 ({registerPool}).
event PoolRegistered(address indexed pool, address poolAsset);
/// @notice `pool` lists `token` as token `idx`: the pool asset at {registerPool}, any other at {addToken}.
event TokenAdded(address indexed pool, uint8 indexed idx, address token);
/// @notice `pool` sets token `idx`'s supply cap, in the token's base units ({setTokenSupplyCap}).
event TokenSupplyCapSet(address indexed pool, uint8 indexed idx, uint128 supplyCap);
/// @notice `pool` retires token `idx` ({retireToken}).
event TokenRetired(address indexed pool, uint8 indexed idx);
/// @notice A venue enters (`fenced`) or leaves its fence: it enters at its pool's `lockVenue`, out of the priority
/// orders with both switches off (`VenueFlagsSet`, `PrioritiesSet`), and leaves at the pool's lift, back in
/// the orders last with its switches still off (`PrioritiesSet`), or at its own retirement (`retireVenue`).
event VenueFenced(address indexed pool, uint16 indexed id, bool fenced);
/// @notice `pool` lists credit pair `idx`, which borrows `debt` against `coll`, with its pin, gap and oracle band,
/// each WAD ({addPair}).
event PairAdded(address indexed pool, uint8 indexed idx, uint8 coll, uint8 debt, uint64 pin, uint64 gap, uint64 band);
/// @notice `pool` sets pair `idx`'s debt cap, in debt-token base units, and its borrow switch ({setPairCaps}).
event PairCapsSet(address indexed pool, uint8 indexed idx, uint128 debtCap, bool borrowEnabled);
/// @notice `pool` retires pair `idx` ({retirePair}).
event PairRetired(address indexed pool, uint8 indexed idx);
/// @notice `pool` sets how many tokens it may owe at once ({setMaxDrawnTokens}).
event MaxDrawnTokensSet(address indexed pool, uint8 maxDrawnTokens);
/// @notice A venue of `pair` at `kind` deploys `account`, the first there under the kind's deployer of the day: the
/// pair's own, or a frame's (`FRAME_VENUE`), which answers no collateral token and its frame as its loan
/// token. The venues that find the account later announce nothing.
event AccountDeployed(address indexed pool, uint8 indexed pair, uint8 indexed kind, address account);
/// @notice `pool` admits venue `id` of `pair` at `kind`, `venueId` its id at its account ({addVenue}); the venue
/// joins the priority orders, last, with no `PrioritiesSet`.
event VenueAdded(address indexed pool, uint16 indexed id, uint8 kind, uint8 pair, bytes32 venueId);
/// @notice A venue's two switches as they stand after {addVenue}, {setVenueFlags}, or a fence that turned one off.
event VenueFlagsSet(address indexed pool, uint16 indexed id, bool borrowEnabled, bool supplyEnabled);
/// @notice `pool` sets venue `id`'s two caps, in debt-token base units, and its rate ceiling, per second, WAD
/// ({setVenueCaps}).
event VenueCapsSet(address indexed pool, uint16 indexed id, uint128 debtCap, uint128 supplyCap, uint64 maxBorrowRateWad);
/// @notice `pool` retires venue `id`, whose slot the next admission may reuse ({retireVenue}); a live venue leaves
/// the priority orders with no `PrioritiesSet`.
event VenueRetired(address indexed pool, uint16 indexed id);
/// @notice The four priority orders as they stand after {setPriorities}, or a fence's lock or lift ({lockVenue}).
event PrioritiesSet(address indexed pool, uint16[] borrow, uint16[] supply, uint16[] withdraw, uint16[] repay);
/// @notice `pool` sets `pair`'s pin, WAD ({setPin}).
event PinSet(address indexed pool, uint8 indexed pair, uint64 pinLtvWad);
/// @notice `pool` turns `fund`'s per-slice re-check on or off ({setFundRecheck}).
event FundRecheckSet(address indexed pool, bool on);
/// @notice `pool` sets `pair`'s venue-oracle band, WAD ({setOracleBand}).
event OracleBandSet(address indexed pool, uint8 indexed pair, uint64 oracleBandWad);
/// @notice The protocol owner sets or clears the global pause ({setGlobalPaused}).
event GlobalPauseSet(bool paused);
/// @notice Venue `id` lends `assets` of its debt token to `to` ({borrow}, {fund}'s borrow phase).
event Borrowed(address indexed pool, uint16 indexed id, uint256 assets, address to);
/// @notice Venue `id` takes a repay of `assets` of its debt token ({repay}, {repayCascade}).
event Repaid(address indexed pool, uint16 indexed id, uint256 assets);
/// @notice Venue `id` takes a supply of `assets` of its debt token ({supply}, {supplyCascade}).
event Supplied(address indexed pool, uint16 indexed id, uint256 assets);
/// @notice Venue `id` pays `assets` of its supply to `to` ({withdrawSupplied}, {withdrawCascade}, {fund}'s
/// withdrawal phase).
event SuppliedWithdrawn(address indexed pool, uint16 indexed id, uint256 assets, address to);
/// @notice Venue `id` takes a post of `assets` of its collateral token ({postCollateral}, {fund}'s borrow phase).
event CollateralPosted(address indexed pool, uint16 indexed id, uint256 assets);
/// @notice Venue `id` releases `assets` of its collateral token to the pool ({withdrawCollateral}, {reclaim}).
event CollateralWithdrawn(address indexed pool, uint16 indexed id, uint256 assets);
/// @notice `assets` of debt and `collateralMoved` of collateral move from venue `src` to venue `dst`
/// ({refinanceDebt}).
event DebtRefinanced(address indexed pool, uint16 indexed src, uint16 indexed dst, uint256 assets, uint256 collateralMoved);
/// @notice Supply moves from venue `src` to venue `dst`, `assets` what the source paid ({migrateSupply}).
event SupplyMigrated(address indexed pool, uint16 indexed src, uint16 indexed dst, uint256 assets);
/// @notice {registerPool}'s caller is not the Factory that constructed this Router.
error NotFactory();
/// @notice {setGlobalPaused}'s caller is not `protocolSafe`.
error NotProtocolSafe();
/// @notice A pool-scoped call's caller is no registered pool.
error NotRegistered();
/// @notice {registerPool} names a pool registered before.
error AlreadyRegistered();
/// @notice The pool {registerPool} names does not answer the Factory, this Router and the pool asset as its own.
error PoolBindingMismatch();
/// @notice {addVenue}'s account is not at its deployer's CREATE2 address, or its bindings read back otherwise.
error AccountCodeMismatch();
/// @notice {addVenue} names a kind with no account deployer at the Factory.
error KindUnknown();
/// @notice {addVenue}'s kind declares a capability outside `KNOWN_CAPABILITIES`.
error UnknownCapability();
/// @notice A token index past the pool's list.
error BadTokenIndex();
/// @notice A pair index past the pool's list.
error BadPairIndex();
/// @notice The call names a retired token where a live one is needed.
error TokenIsRetired();
/// @notice The call names a retired pair where a live one is needed.
error PairIsRetired();
/// @notice {retireToken} names a token a live pair still names.
error TokenInUse();
/// @notice {retirePair} names a pair a venue of which is not retired or still holds something.
error PairNotEmpty();
/// @notice {addToken} names a token listed before, a retired one included.
error DuplicateToken();
/// @notice {addPair} names a pair added before, a retired one included.
error DuplicatePair();
/// @notice {addToken} past `MAX_TOKENS`.
error TooManyTokens();
/// @notice {addPair} past `MAX_PAIRS`.
error TooManyPairs();
/// @notice A priced call's `usd` is not `tokenCount` long.
error BadPriceVector();
/// @notice A draw at a venue that owes nothing would make a token owed and backing at once, or pass
/// `maxDrawnTokens`; also a fence's lift that would make a token owed and backing at once ({lockVenue}).
error DrawOutsideDrawnSet();
/// @notice A leg the global pause stops ({setGlobalPaused}).
error GlobalPaused();
/// @notice A venue's tokens are not its pair's ({addVenue}), or the two ends of a move are one venue, or do not
/// share the pair ({refinanceDebt}) or the debt token ({migrateSupply}).
error VenueMismatch();
/// @notice {addVenue} names a position a live or fenced slot already names.
error DuplicateVenue();
/// @notice {addVenue} past `MAX_VENUES`, with no retired slot to reuse.
error TooManyVenues();
/// @notice A venue id past the pool's list.
error BadVenueId();
/// @notice The call needs a venue that is not retired.
error VenueIsRetired();
/// @notice The call asks of a fenced venue what it does not take (a leg, a switch on), or {addVenue} joins an
/// account with a fenced venue.
error VenueIsFenced();
/// @notice {retireVenue} names a venue that owes or recognizes something.
error VenueNotEmpty();
/// @notice The venue's switch for the leg, or its pair's, is off.
error VenueDisabled();
/// @notice {setPriorities} is handed an order that does not list every live, unfenced venue exactly once.
error BadPriorities();
/// @notice A setting or an amount outside what the call takes (each call states its bounds).
error InvalidConfig();
/// @notice The pair's price is unchecked, or the venue's oracle sits outside the pair's band or does not read.
error OracleBand();
/// @notice A borrow would pass the venue's or the pair's debt cap.
error DebtCapExceeded();
/// @notice A supply would pass the venue's or the token's supply cap, or what the venue takes now.
error SupplyCapExceeded();
/// @notice A borrow would leave the venue's borrow rate over its ceiling, or the rate does not read.
error RateCeiling();
/// @notice The venue's threshold sits under its pair's pin plus the gap, so it lends nothing.
error VenueOverPinned();
/// @notice A leg would leave the venue past the LTV it is held to: a borrow's or a priced release's bound, or a
/// proportional release past what the repay freed.
error Unhealthy();
/// @notice A fund, a refinance or a supply withdrawal finds too little, `shortfall` base units. The pool raises it
/// too, for an entry's leg under a lender's minimum and a quote's payout past what the Router can fund.
error InsufficientLiquidity(uint256 shortfall);
/// @notice {reclaim} comes short by `shortfall`, or {withdrawCollateral} names zero or more than the Router
/// recognizes (`shortfall` its `assets` then), base units.
error InsufficientCollateral(uint256 shortfall);
/// @notice A refinance's bridge needs an allowance of `needed` of the debt token, base units.
error InsufficientBridge(uint256 needed);
/// @notice A refinance's atomic move, or its bridge's repay, took other than its amount.
error ExactDelta();
/// @notice A move's two ends do not sum to what they held, past the rounding the move allows ({refinanceDebt},
/// {migrateSupply}).
error Conservation();
/// @notice A refinance or a migration with nothing to move.
error NothingToMove();
/// @notice A proportional release at an indebted venue with no repay of the same transaction to read.
error NoRepaySnapshot();
/// @notice A leg's receiver is not the caller.
error BadReceiver();
// ---- factory / protocol
/// @notice Lists the pool asset as token 0, with `maxDrawnTokens` 1. Factory-only (`NotFactory`), once
/// (`AlreadyRegistered`); the pool must answer the Factory, this Router and `poolAsset` as its own
/// (`PoolBindingMismatch` otherwise).
/// @param pool The pool to register.
/// @param poolAsset Its pool asset.
function registerPool(address pool, address poolAsset) external;
/// @notice Sets the global pause, which stops the legs that add credit risk (a borrow, a funding's borrow phase, a
/// supply, the supply cascade, a refinance, a migration) and leaves every leg that unwinds open (a repay,
/// a post, a release, a supply withdrawal). The protocol owner (`protocolSafe`) sets and clears it; where
/// `protocolSafe` is `FactoryAdmin`, the pauser named there may set it through `FactoryAdmin.pauseRouter`;
/// anyone else, `NotProtocolSafe`.
/// @param paused The pause asked for.
function setGlobalPaused(bool paused) external;
/// @notice The protocol owner's address on chain, the Factory's `PROTOCOL_SAFE` at deployment, which no call
/// changes ({IMMRouter}).
function protocolSafe() external view returns (address);
// ---- pool-scoped token and pair set (msg.sender = pool)
/// @notice Appends a token: not zero, at most 18 decimals (`InvalidConfig`), not listed before, retired ones
/// included (`DuplicateToken`), at most `MAX_TOKENS` in all (`TooManyTokens`).
/// @param token The token to list.
/// @return idx Its index in the pool's list.
function addToken(address token) external returns (uint8 idx);
/// @notice The supply of the token the pool's venues may hold at once, across every pair that lends it; refused
/// while the token is retired (`TokenIsRetired`).
/// @param idx The token's index (`BadTokenIndex` past the list).
/// @param supplyCap The cap, in the token's base units; zero: none.
function setTokenSupplyCap(uint8 idx, uint128 supplyCap) external;
/// @notice Terminal: retires a token, never the pool asset (`InvalidConfig`) nor one already retired, and only once
/// every pair naming it is retired (`TokenInUse` otherwise). A retired token takes no pair and no supply
/// cap (`TokenIsRetired`).
/// @param idx The token's index (`BadTokenIndex` past the list).
function retireToken(uint8 idx) external;
/// @notice Appends a credit pair that borrows `debt` against `coll`: two live listed tokens, distinct, a pair not
/// added before (retired ones included, whose accounts keep their addresses), `pinLtvWad` above zero,
/// `pinLtvWad + safetyGapWad` under one, `oracleBandWad` at most 20 % (zero: no venue oracle is read for
/// it). Born with its borrowing off. No venue of the pair lends while its threshold is under the pin plus
/// the gap; the gap is written once. Refused `BadTokenIndex`, `TokenIsRetired`, `DuplicatePair`,
/// `TooManyPairs`, and `InvalidConfig` past the bounds above.
/// @param coll The collateral token's index.
/// @param debt The debt token's index.
/// @param pinLtvWad The pin, WAD ({setPin}).
/// @param safetyGapWad The room a borrowing venue's threshold keeps over the pin, WAD.
/// @param oracleBandWad The venue-oracle band, WAD ({setOracleBand}).
/// @return idx The pair's index.
function addPair(uint8 coll, uint8 debt, uint64 pinLtvWad, uint64 safetyGapWad, uint64 oracleBandWad) external returns (uint8 idx);
/// @notice The pair's debt cap across its venues and its borrow switch; refused once the pair is retired
/// (`PairIsRetired`).
/// @param pair The pair's index (`BadPairIndex` past the list).
/// @param debtCap The cap, in debt-token base units; zero: none.
/// @param borrowEnabled The pair's borrow switch.
function setPairCaps(uint8 pair, uint128 debtCap, bool borrowEnabled) external;
/// @notice A lower pin always passes, so the pool can follow a lender's cut at once; any other pin plus the pair's
/// gap must stay within the pair's `minLltv` (one, where no venue of the pair binds), else `InvalidConfig`.
/// @param pair The pair's index (`BadPairIndex` past the list).
/// @param pinLtvWad The new pin, WAD, above zero (`InvalidConfig`).
function setPin(uint8 pair, uint64 pinLtvWad) external;
/// @notice The pair's venue-oracle band, at most 20 % (`InvalidConfig` past it): how far a venue's own oracle may
/// sit from the pair's price on every band-gated path (admission of a priced or borrowing venue, borrows,
/// a priced release, refinance). Zero turns it off: no venue oracle is read and only an unchecked price is
/// refused.
/// @param pair The pair's index (`BadPairIndex` past the list).
/// @param oracleBandWad The band, WAD.
function setOracleBand(uint8 pair, uint64 oracleBandWad) external;
/// @notice Terminal: every venue of the pair must be retired, owe nothing and recognize no supply or collateral
/// (`PairNotEmpty` otherwise); its borrow switch goes off for good.
/// @param pair The pair's index (`BadPairIndex` past the list, `PairIsRetired` for one retired).
function retirePair(uint8 pair) external;
/// @notice How many tokens may be owed at once, at least one and at most the token count less one
/// (`InvalidConfig`); a borrow that would add an owed token past it is refused. Lowering it unwinds
/// nothing.
/// @param maxDrawnTokens The limit.
function setMaxDrawnTokens(uint8 maxDrawnTokens) external;
// ---- pool-scoped venue configuration
/// @notice Registers a venue of `kind` for `pair` from protocol-specific `venueParams`, in the pair's own (pair,
/// kind) account or, where the params open with `FRAME_VENUE`, in a frame's account at the kind.
/// @dev Which account:
/// - Plain params: the pair's own (pair, kind) account, bound to the pair's (collateral, debt) tokens, under
/// the kind's deployer of the day. The first venue there deploys it and the others find it at its address
/// after its bindings read back, so once the Factory replaces a kind's deployer the pair's next plain venue
/// opens its own account under the new one, and its venues at the old one stay there until they move.
/// - Params that open with `FRAME_VENUE` (`abi.encode(FRAME_VENUE, frame, params)`): the frame's account at
/// the kind, bound to (zero, `frame`) and shared by the venues of every pair the pool puts in the frame,
/// found or deployed the same way. It takes `abi.encode(collateral, debt, params)` with the pair's two
/// tokens and must name them back for the venue's id (`IFrameAccount.tokensOf`; `VenueMismatch` where it
/// names others), which a kind that holds no frame does not answer, so it takes no such venue.
/// - No venue joins a frame's account while a venue there is fenced (`VenueIsFenced`): the Router refuses that
/// join alone, and the pool fences a frame's venues together.
/// - A pair may hold venues at several accounts of one kind (its own, its own under a later deployer,
/// frames'), and moves between them by a new venue and `refinanceDebt` or `migrateSupply` (a debt's move
/// between them needs room under its lender's collateral cap: `refinanceDebt`). It may borrow at several of
/// them at once, as a plan holds what it posts through them within the one room their lender has (`fund`).
///
/// Slots:
/// - A pool holds at most `MAX_VENUES` venues (`TooManyVenues` past it), and the Router bounds nothing else of
/// an exit's gas, nor a releasing swap's: a pro-rata exit repays and releases every live position, and a
/// releasing swap reads the venues, repays the pool's debt in the token it takes in and walks those that
/// hold the token it pays out as collateral, so the gas of each grows with them (`MAX_VENUES`), and the
/// curator keeps a pool's positions within what one exit and one releasing swap carry.
/// - A retired slot is reused before the record grows: the one that already names this position, else the
/// first, so no two slots ever name one position.
///
/// Admission:
/// - A venue whose borrowing is off may come unpriced: it is admitted with no band check and lends nothing
/// until a path that borrows checks its band at a checked price, as each does.
/// - A venue that can borrow needs a threshold of at least the pair's pin plus its gap (`InvalidConfig`); one
/// whose borrowing is off is admitted whatever its threshold, as it lends nothing and binds no pin, and
/// turns its borrowing on only once the pin plus the gap is within it (`setVenueFlags`).
/// - A kind that declares a capability outside `KNOWN_CAPABILITIES` (every bit the Router admits) is refused
/// (`UnknownCapability`), and so is a retired pair (`PairIsRetired`).
/// - One kind number is one lender, whose reserve every account of the kind shares or none does
/// (`IFinancingAccount` ADMISSION): a venue that declares `CAP_SHARED_LIQUIDITY` otherwise than the pool's
/// live venues of its kind, as a later deployer at the number might, is refused (`InvalidConfig`), so a
/// plan's posts there stay netted across the accounts (`fund`).
/// - A venue whose kind can refuse an action (`CAP_ACTION_GATES`) and whose account answers
/// `IActionsOf.actionsOf` as its `actions` here has its gates read through it, one action at a time; any
/// other, through `actions`.
/// - Refused also `BadPriceVector`, `BadPairIndex`, `KindUnknown` (no deployer at `kind`),
/// `AccountCodeMismatch` (an account off its pinned address or bindings), `DuplicateVenue` (a live or fenced
/// slot names the position) and `OracleBand` (a borrowing venue or a priced one outside the pair's band).
/// @param kind The venue kind, which names the deployer at the Factory.
/// @param pair The pair's index.
/// @param venueParams The kind's parameters, or `abi.encode(FRAME_VENUE, frame, params)` for a frame's account.
/// @param borrowEnabled The venue's borrow switch.
/// @param supplyEnabled The venue's supply switch.
/// @param usd The pool's checked USD prices ({IMMRouter}); a zero at either of the pair's tokens leaves the venue
/// unpriced, which only a venue whose borrowing is off may be.
/// @return id The venue's slot, its id in every by-id call.
function addVenue(
uint8 kind,
uint8 pair,
bytes calldata venueParams,
bool borrowEnabled,
bool supplyEnabled,
uint256[] calldata usd
) external returns (uint16 id);
/// @notice Sets a live venue's two switches (`BadVenueId`, `VenueIsRetired` otherwise). Turning a venue's borrowing
/// on is refused (`InvalidConfig`) while its threshold is under its pair's pin plus the gap. A fenced venue
/// turns neither switch on (`VenueIsFenced`).
/// @param id The venue's slot.
/// @param borrowEnabled The venue's borrow switch.
/// @param supplyEnabled The venue's supply switch.
function setVenueFlags(uint16 id, bool borrowEnabled, bool supplyEnabled) external;
/// @notice Fences a live venue (`fenced`): both switches go off and stay off, and it leaves the four priority
/// orders, the others keeping their order; or lifts a fence, the venue back in the orders, last,
/// its switches still off. Refused (`InvalidConfig`) where the venue is fenced already or not fenced to
/// lift, and (`DrawOutsideDrawnSet`) where the lift would leave the unfenced venues holding a token owed
/// and backing at once; the drawn-token limit binds new draws alone, as when it is lowered. Only the pool
/// that holds the venue sets it, as every pool-scoped call.
/// The venues of a frame's account share one position at its lender, so the pool fences, lifts and gives
/// them up together: the Router refuses only a venue joining the account while one there is fenced.
/// @param id The venue's slot.
/// @param fenced True to fence, false to lift.
function lockVenue(uint16 id, bool fenced) external;
/// @notice Sets a venue's caps and rate ceiling, a fenced one's too (`BadVenueId`, `VenueIsRetired` otherwise). A
/// cap under what the venue holds refuses new legs and unwinds nothing.
/// @param id The venue's slot.
/// @param debtCap The venue's debt cap, in debt-token base units; zero: none.
/// @param supplyCap The venue's supply cap, in debt-token base units; zero: none.
/// @param maxBorrowRateWad The highest borrow rate a borrow there may leave, per second, WAD; zero: none.
function setVenueCaps(uint16 id, uint128 debtCap, uint128 supplyCap, uint64 maxBorrowRateWad) external;
/// @notice The four cascade orders, each listing every live, unfenced venue once (`BadPriorities` otherwise).
/// @param borrow_ The order `fund` borrows in; {reclaim} walks it in reverse.
/// @param supply_ The order {supplyCascade} lends in.
/// @param withdraw_ The order `fund` and {withdrawCascade} withdraw supply in.
/// @param repay_ The order {repayCascade} repays in.
function setPriorities(
uint16[] calldata borrow_,
uint16[] calldata supply_,
uint16[] calldata withdraw_,
uint16[] calldata repay_
) external;
/// @notice Terminal. The venue must owe nothing on its raw position and recognize no collateral and no supplied
/// assets (a withdrawal's share dust, worth none, is none); a position donated to the account, and that
/// dust, survive retirement, unrecognized. A live venue leaves the four priority orders, the others keeping
/// their order; a fenced one, in none, retires as any other, and its fence ends with it (`VenueFenced`).
/// Refused `VenueNotEmpty` otherwise, and `BadVenueId` or `VenueIsRetired` for no such venue.
/// @param id The venue's slot, which the next admission may reuse.
function retireVenue(uint16 id) external;
/// @notice On (the default), `fund` re-checks each borrow slice against its venue just before borrowing, as
/// the plan's withdrawals and the slice's collateral post left the venue. Off, the plan's checks of the
/// same bounds stand alone and each slice costs less gas: a venue that moves between plan and borrow
/// against the plan's projection (a threshold or rate that a post or withdrawal changes) is then caught
/// only by the venue's own checks. Cash is never re-checked: the venue's borrow refuses a shortfall itself.
/// @param on Whether `fund` re-checks.
function setFundRecheck(bool on) external;
/// @notice Clamps one live venue's managed trackers down to its actual position, after the pool's emergency path
/// moved it outside the Router; a retired venue's are zero already, and `VenueIsRetired` refuses it.
/// @param id The venue's slot.
function syncManaged(uint16 id) external;
/// @notice Raises one live venue's managed collateral by the `units` the pool's emergency path posted directly,
/// capped at the actual position; `VenueIsRetired` refuses a retired venue, whose slot a later admission
/// may reuse.
/// @param id The venue's slot.
/// @param units The collateral units posted, in the account's own units ({IFinancingAccount.positionOf}).
function recognizeCollateral(uint16 id, uint256 units) external;
// ---- pool-scoped primitives (msg.sender = pool)
/// @notice Pulls `assets` of the venue's collateral token and posts it; refused at a fenced venue
/// (`VenueIsFenced`). The global pause leaves it open, as a post only reduces risk.
/// @param id The venue's slot.
/// @param assets The amount, in the collateral token's base units, above zero (`InvalidConfig`).
function postCollateral(uint16 id, uint256 assets) external;
/// @notice Releases up to `assets` of the venue's collateral token to the pool and returns what it released: what
/// the venue cannot release now (`IFinancingAccount.collateralReleasable`: collateral it lent out, a
/// release it refuses, or under `CAP_PRICED_RELEASE` any release while its oracle cannot be read) stays
/// posted and recognized, and waits. A venue that owes nothing reads no price and no repay.
/// @dev Proportional, it reads no price and releases at most the collateral the same transaction's repay freed, the
/// lender's rounding of that repay aside:
/// - Where the repay lowered the debt, up to four base units of debt over the exact rest are not held against
/// the release (`MMRouterLib.RELEASE_SLACK`).
/// - At a venue whose collateral accrues (`CAP_ACCRUING_COLLATERAL`), neither is the rounding a market whose
/// rate every holder's redemption moves may pass on from the flow's earlier legs: up to one unit's worth and
/// one for each venue of the pool, at most a millionth of one whole collateral token and one, and at most
/// four base units and a millionth of the release.
/// - The allowance answers no particular leg, and each repay that lowers the debt grants it once.
///
/// Priced, an indebted venue releases no further than `reclaim` would take it; an indebted fenced venue
/// releases proportionally alone (`VenueIsFenced`).
/// @param id The venue's slot.
/// @param assets The most to release, in the collateral token's base units: zero, or more than the Router
/// recognizes there, reverts `InsufficientCollateral`.
/// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`); zeros serve a proportional
/// release.
/// @param proportional True for what the same transaction's repay freed (`NoRepaySnapshot` with no repay,
/// `Unhealthy` past it), false for a priced release (`OracleBand` off the band, `Unhealthy` past its bound).
/// @return released What it released, at most `assets`; zero where the venue can release nothing now.
function withdrawCollateral(uint16 id, uint256 assets, uint256[] calldata usd, bool proportional)
external
returns (uint256 released);
/// @notice Borrows `assets` of the venue's debt token at a live venue with its switch and its pair's on. Refused
/// `GlobalPaused`, `VenueDisabled`, `DrawOutsideDrawnSet` (a venue that owes nothing, under the
/// no-circularity rule), `OracleBand`, `VenueOverPinned`, `DebtCapExceeded` (the venue's or the pair's),
/// `Unhealthy` (past the pin on the collateral posted there) and `RateCeiling`.
/// @param id The venue's slot.
/// @param assets The amount, in debt-token base units, above zero (`InvalidConfig`).
/// @param to The receiver, which must be the caller (`BadReceiver`).
/// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
function borrow(uint16 id, uint256 assets, address to, uint256[] calldata usd) external;
/// @notice Pulls up to `assets` of the venue's debt token and repays, at a fenced or retired venue too; what the
/// lender does not take goes straight back to the pool. It records the venue's (debt, collateral) for a
/// proportional release in the same transaction.
/// @param id The venue's slot.
/// @param assets The most to repay, in debt-token base units, capped at the venue's debt.
/// @return repaid What the lender took.
function repay(uint16 id, uint256 assets) external returns (uint256 repaid);
/// @notice Pulls `assets` of the venue's debt token and lends it at the venue. Refused `GlobalPaused`,
/// `VenueDisabled`, and `SupplyCapExceeded` past the venue's cap, what the venue takes now or the token's
/// cap.
/// @param id The venue's slot.
/// @param assets The amount, in debt-token base units, above zero (`InvalidConfig`).
/// @return shares The supply shares the account minted.
function supply(uint16 id, uint256 assets) external returns (uint256 shares);
/// @notice Withdraws `assets` of the venue's lent debt token to the pool (`to` the caller), every managed share for
/// `type(uint256).max`. A leg over what the venue recognizes as the pool's supply is refused
/// (`InsufficientLiquidity`), save at a venue whose units accrue (`CAP_ACCRUING_COLLATERAL`) and that
/// recognizes some: there a leg over it by the rounding a shared market's rate may pass on from the flow's
/// earlier legs still leaves, up to one unit's worth and one for each venue of the pool, at most a
/// millionth of one whole token and one, and at most four base units and a millionth of the leg.
/// @param id The venue's slot.
/// @param assets The amount, in debt-token base units, above zero (`InsufficientLiquidity`).
/// @param to The receiver, which must be the caller (`BadReceiver`).
/// @return withdrawn What the venue paid; zero for `type(uint256).max` with no managed share.
function withdrawSupplied(uint16 id, uint256 assets, address to) external returns (uint256 withdrawn);
/// @notice Accrues interest at each live, unfenced venue of the caller's own pool but those in `skipVenues` (bit i:
/// venue i) that do not lend token `kept`, so the reads that follow in the block take the accrued state: a
/// swap passes its idle venues and the token it pays, whose venues alone it reads a rate at; zero accrues
/// them all. Any caller, its own venues only (none unless a registered pool): accrual is permissionless and
/// idempotent at the venue. Best effort per venue: an account whose accrual reverts is skipped.
/// @param skipVenues The venues to pass over, bit i for venue i.
/// @param kept A token whose venues accrue whatever `skipVenues` says.
function accrueExcept(uint64 skipVenues, uint8 kept) external;
// ---- pool-scoped cascades (each passes fenced venues)
/// @notice Pays `assets` of the pair's debt token to `to`: first by withdrawing that token's supply at any venue
/// lending it (withdraw order), then by borrowing at the pair's venues (borrow order), posting up to
/// `collateralIn` of the pair's collateral token: at each venue what its pin needs, and where its
/// collateral accrues one unit's assets and one more, which the venue's rounding may keep. It never borrows
/// more than `assets`.
/// @dev The borrow phase runs only while the pair can draw (its switch, the global pause, the no-circularity rule)
/// and within the pair's debt cap.
///
/// A venue whose kind holds a minimum position (`CAP_HELD_REPAY`) takes no slice that leaves its debt under
/// that minimum (`IHeldRepay.minimumDebt`), or over it by less than the lenders' rounding
/// (`MMRouterLib.RELEASE_SLACK`) where it owes already: the plan passes it over, as it does one whose minimum
/// cannot be read (a read that reverts, answers short or runs past `MMRouterLib.MINIMUM_READ_GAS`), and `fund`
/// reverts `InsufficientLiquidity` by what no venue takes.
///
/// Each post stays within its venue's post room:
/// - Where the pair's venues at a kind that shares one reserve per token (`CAP_SHARED_LIQUIDITY`) sit at
/// several of its accounts (its own, its own under a later deployer, frames'), each account reports that
/// lender's room for its own venues alone, and a slice whose post passes what the plan's posts through the
/// others left of it is sized again within it, so the plan's posts there fit the lender's room together, as
/// at one account, whose report parts it among the account's venues.
/// - A report nets what its own account holds for the venue's next post, which that post mints with its own,
/// and no other report does, so where collateral accrues the plan counts each post through another account
/// with one unit's assets more, the most that account can hold for it: the posts fit the lender's room at
/// its very edge too.
/// - They can come short of it, never past it: by that unit for each such post, and where an account parts the
/// room among `k` of its venues there, by up to `k - 1` times the plan's posts through the others, as each
/// part is held to its share less those posts whole; a later plan posts what is left.
/// - One kind number is one lender (`IFinancingAccount` ADMISSION): a lender listed under two numbers would
/// have its posts counted apart and its room taken twice.
/// @param pair The pair's index (`BadPairIndex`).
/// @param assets What to pay, in debt-token base units.
/// @param to The receiver, which must be the caller (`BadReceiver`).
/// @param collateralIn The most to post, in collateral-token base units, pulled from the pool's allowance.
/// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`). An unchecked pair runs the
/// withdrawal phase alone.
function fund(uint8 pair, uint256 assets, address to, uint256 collateralIn, uint256[] calldata usd) external;
/// @notice Repays up to `assets` of `token` at every unfenced venue that lends it to the pool, in repay order; each
/// repay records its venue's (debt, collateral) for a proportional release in the same transaction. It
/// pulls at most `assets` in all: what a venue does not take of its pull comes straight back to the pool,
/// and the cascade does not offer it to the next venue. A venue whose gate refuses a repay is passed over.
/// @param token The debt token's index (`BadTokenIndex`).
/// @param assets The most to pull, in the token's base units.
/// @return repaid What the lenders took.
function repayCascade(uint8 token, uint256 assets) external returns (uint256 repaid);
/// @notice Supplies up to `assets` of `token` at venues that lend it with supply on, in supply order. A venue whose
/// kind holds a minimum position takes no supply that leaves its position under that minimum or over it by
/// less than the lenders' rounding (`MMRouterLib.RELEASE_SLACK`: the lender mints a supply's shares
/// rounded down), nor any while its minimum cannot be read: the cascade passes it over, and what no venue
/// takes stays with the pool, all of it while the global pause holds.
/// @param token The token's index (`BadTokenIndex`; the global pause returns zero before it reads the index).
/// @param assets The most to lend, in the token's base units.
/// @return supplied What the venues took.
function supplyCascade(uint8 token, uint256 assets) external returns (uint256 supplied);
/// @notice Withdraws up to `assets` of supplied `token` from the unfenced venues that lend it, in withdraw order,
/// to `to`, which must be the pool, as for `withdrawSupplied` (`BadReceiver` otherwise). A venue whose
/// withdrawal reverts at the lender is passed over.
/// @param token The token's index (`BadTokenIndex`).
/// @param assets The most to withdraw, in the token's base units.
/// @param to The receiver.
/// @return withdrawn What the venues paid, which may fall short of `assets`.
function withdrawCascade(uint8 token, uint256 assets, address to) external returns (uint256 withdrawn);
/// @notice Releases collateral `token` across the unfenced venues whose collateral it is, in reverse borrow order.
/// An indebted venue releases down to its pair's pin, or, once its threshold has fallen under the pin plus
/// the gap, down to that threshold less the gap; one whose pair is unchecked, or whose oracle is off the
/// pair's band, releases nothing. A venue that refuses its release is passed over, so the rest still pay:
/// only a shortfall over all of them reverts (`InsufficientCollateral`, by the shortfall). A release that
/// fails with under an eighth of the gas it began with left may have run out of gas: the walk reverts
/// `VenueReads.ReadStarved` where it began with under three million, and ends where it began with more, as
/// the lender burnt it. A starved read, the venue's oracle read for its band among them, reverts
/// `ReadStarved` as well.
/// @param token The collateral token's index.
/// @param assets What to release, in the token's base units.
/// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
/// @return got What it released: `assets`.
function reclaim(uint8 token, uint256 assets, uint256[] calldata usd) external returns (uint256 got);
/// @notice As {reclaim}, with no revert on a shortfall: a starved read or release still reverts
/// `VenueReads.ReadStarved`.
/// @param token The collateral token's index.
/// @param assets The most to release, in the token's base units.
/// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
/// @return got What it released, which may fall short of `assets`.
function reclaimBestEffort(uint8 token, uint256 assets, uint256[] calldata usd) external returns (uint256 got);
/// @notice Moves debt between two venues of one pair: atomically inside one account that supports it, else bridged
/// through the pool's granted debt token (`InsufficientBridge` when the allowance is short). The collateral
/// moves in proportion to the debt, all that the source recognizes on a full move. Refused at a fenced
/// venue at either end (`VenueIsFenced`).
/// @dev Where either end holds a minimum position (`CAP_HELD_REPAY`), a move that would leave it under that minimum
/// reverts, as no plan passes it over: the destination's lender refuses the borrow, and the source takes a
/// partial repay short of the move (`ExactDelta`). The curator's or keeper's move is refused, and its caller
/// sizes it again.
///
/// Between two accounts of one lender whose collateral market is capped (a pair's own and a frame's, or its
/// own under two deployers), the bridge releases at the source before it posts at the destination, so the
/// lender's market ends holding what it held, but the post needs room under the cap for the moved collateral
/// and, where collateral accrues, for what the destination account holds for its next post: while the lender's
/// cap sits under what its market holds (a cap its governance lowered), such a move reverts at the lender, and
/// the pair stays at its account until the cap leaves room.
///
/// Refused also:
/// - `GlobalPaused`.
/// - `VenueMismatch`: one venue, or two pairs.
/// - `VenueDisabled`: the destination's switch.
/// - `NothingToMove`.
/// - `InsufficientLiquidity`: the source cannot release the collateral, or the destination has not the cash.
/// - `OracleBand`, `VenueOverPinned`, `DebtCapExceeded` (the destination's) and `RateCeiling`.
/// - `Unhealthy`: either end past the pin.
/// - `Conservation`: the two venues' summed debt moved by more than `MMRouterLib.REFINANCE_SLACK`.
/// @param src The source venue's slot.
/// @param dst The destination venue's slot, live.
/// @param assets The debt to move, in debt-token base units; at or past the source's debt it moves all of it.
/// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
function refinanceDebt(uint16 src, uint16 dst, uint256 assets, uint256[] calldata usd) external;
/// @notice Moves supply between two venues that lend the same token; refused at a fenced venue at either end
/// (`VenueIsFenced`).
/// @dev The destination must recognize what the source paid it, less the rounding of its supply (`Conservation`
/// otherwise):
/// - That rounding is up to four base units, or up to one of its shares' worth and one where that is more, but
/// past four never more than a millionth of the amount moved nor a millionth of one whole token.
/// - A refused read of that share refuses the move.
/// - The bound is the destination's rounding alone: what the source charges to pay the move (a redemption fee)
/// is outside it.
///
/// A move that would leave a destination holding a minimum position (`CAP_HELD_REPAY`) under that minimum
/// reverts at its lender, which refuses the supply: the curator's or keeper's move is refused, not passed
/// over, and its caller sizes it again. The source's withdrawal meets no minimum, as such a lender checks none
/// on a withdrawal.
///
/// Refused also `GlobalPaused`, `VenueMismatch` (one venue, or two tokens), `NothingToMove`, `VenueDisabled`
/// and `SupplyCapExceeded` (the destination's switch and room).
/// @param src The source venue's slot.
/// @param dst The destination venue's slot, live.
/// @param assets What to move, in the token's base units, within what the source recognizes.
function migrateSupply(uint16 src, uint16 dst, uint256 assets) external;
// ---- views (any caller; `pool` explicit)
/// @notice The tokens the pool lists, retired ones included; zero for an unregistered pool.
function tokenCount(address pool) external view returns (uint256);
/// @notice The pool's token `idx`, retired or not (`BadTokenIndex` past the list).
/// @return The token's record ({TokenView}), its cap in the token's base units.
function token(address pool, uint8 idx) external view returns (TokenView memory);
/// @notice The pool's pairs, retired ones included; zero for an unregistered pool.
function pairCount(address pool) external view returns (uint256);
/// @notice The pool's pair `idx`, retired or not (`BadPairIndex` past the list).
/// @return The pair's record ({PairView}): its pin, gap and band in WAD, its debt cap in debt-token base units.
function pair(address pool, uint8 idx) external view returns (PairView memory);
/// @notice The pair's first own (pair, kind) account, which its first plain venue of the kind deployed: zero until
/// then, and for a pair not added. Its later plain venues land at its own account under the kind's deployer
/// of the day, another once the Factory replaces that deployer, and a frame venue at its frame's account:
/// each venue's is `venue(pool, id).account`.
/// @return The account's address, or zero.
function accountOf(address pool, uint8 pair, uint8 kind) external view returns (address);
/// @notice The pool the Router deployed or joined `account` for; zero for any other address.
function poolOf(address account) external view returns (address);
/// @notice The slots of the pool's venue record, retired ones included; zero for an unregistered pool.
function venueCount(address pool) external view returns (uint256);
/// @notice The pool's venue `id`, retired or not (`BadVenueId` past the record).
/// @return The venue's record ({VenueView}): its threshold read live, WAD; its caps in debt-token base units.
function venue(address pool, uint16 id) external view returns (VenueView memory);
/// @notice The pool's four cascade orders ({setPriorities}).
/// @param pool The pool.
/// @return borrow_ The borrow order.
/// @return supply_ The supply order.
/// @return withdraw_ The withdraw order.
/// @return repay_ The repay order.
function priorities(address pool)
external
view
returns (uint16[] memory borrow_, uint16[] memory supply_, uint16[] memory withdraw_, uint16[] memory repay_);
/// @notice The most tokens the pool's owed set may hold ({setMaxDrawnTokens}); registration sets one.
function maxDrawnTokens(address pool) external view returns (uint8);
/// @notice The owed set (bit t: some unfenced venue lends token t to the pool) and the backing set (bit t: token t
/// is the collateral of an unfenced venue that lends to the pool).
/// @param pool The pool.
/// @return owed The owed set, a mask over the pool's token indices.
/// @return backing The backing set, a mask over the pool's token indices.
function drawn(address pool) external view returns (uint16 owed, uint16 backing);
/// @notice Venue `id`'s position as its account reports it, and the parts the Router recognizes as the pool's: a
/// gift to the account sits in the raw reads alone. Reads a fenced or retired venue too (`BadVenueId` past
/// the record).
/// @param pool The pool.
/// @param id The venue's slot.
/// @return collateral The collateral the account holds, in collateral-token base units.
/// @return recognizedCollateral The part the Router's tracker recognizes, in the same units.
/// @return supplied The account's supply at its worth, in debt-token base units.
/// @return recognizedSupplied The part the Router's tracker recognizes, in the same units.
/// @return debt The venue's debt at the accrued state, in debt-token base units.
function venuePosition(address pool, uint16 id)
external
view
returns (uint256 collateral, uint256 recognizedCollateral, uint256 supplied, uint256 recognizedSupplied, uint256 debt);
/// @notice The pool's positions per token in one walk of its venues, skipping retired and fenced ones and those in
/// `skipVenues` (bit i: venue i): each venue's recognized collateral credited to its collateral token, its
/// recognized supply and its debt to its debt token, each array `tokenCount` long. A fenced venue is read
/// by id alone (`venuePosition`). `emptyVenues` marks the venues read that owe nothing, carry no managed
/// collateral and hold no recognized supply: only the pool's own calls through the Router move those, so a
/// gift posted or supplied on the account's behalf leaves a venue empty, a withdrawal's share dust (worth
/// nothing) does too, and a venue a lender seized collateral from is not empty until its tracker is synced
/// down or it retires.
/// @param pool The pool.
/// @param skipVenues The venues to pass over, bit i for venue i.
/// @return posted Recognized collateral per token, in its base units.
/// @return supplied Recognized supply per token, in its base units.
/// @return owed Debt per token, in its base units.
/// @return emptyVenues The venues read that hold nothing of the pool's, bit i for venue i.
function book(address pool, uint64 skipVenues)
external
view
returns (uint256[] memory posted, uint256[] memory supplied, uint256[] memory owed, uint64 emptyVenues);
/// @notice The lowest threshold, read live, of the pair's venues that can borrow or still owe: the pair pin's and
/// its LTV's bound. A zero threshold binds like any other; `NO_VENUE_LLTV` where none binds, and for a pair
/// not added.
function minLltv(address pool, uint8 pair) external view returns (uint256);
/// @notice What `fund` would find for `pair`, up to `cap` (`type(uint256).max`: all of it), with `collateralIn`
/// of its collateral token to post. `assumeRepaid` (bit t) reads the drawn-set test alone (which tokens are
/// owed and which back a debt) as if every venue lending token t had been repaid in full, so a plan that
/// repays one side first can pass that test for a draw on the other; the debt caps and each slice's pin
/// read the debt as it stands. The plan stops at `cap`, so a small cap reads less, and as it passes over a
/// slice that leaves a venue holding a minimum position under it (`fund`), a smaller cap can read nothing
/// at such a venue where a larger one reads all of it.
/// @param pool The pool; an unregistered one reads zero.
/// @param pair The pair's index (`BadPairIndex`).
/// @param cap The most to read, in debt-token base units.
/// @param collateralIn The most to post, in collateral-token base units.
/// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
/// @param assumeRepaid The tokens read as repaid in the drawn-set test, bit t for token t.
/// @return What the plan pays, at most `cap`, in debt-token base units.
function fundingCeiling(
address pool,
uint8 pair,
uint256 cap,
uint256 collateralIn,
uint256[] calldata usd,
uint16 assumeRepaid
) external view returns (uint256);
/// @notice The collateral `fund(pair, assets, …, collateralIn, usd)` posts now: the sum of its plan's posts at the
/// pair's venues, at most `collateralIn`, with the Router's own rounding and placement. A borrow that first
/// withdraws its collateral token's supply withdraws what this reads past the custody it holds, then funds
/// at the custody the withdrawal leaves: `fund` plans anew after the withdrawal, which can free room under
/// the posting market's supply cap and lower its collateral reads, and `collateralIn` bounds what it posts.
/// @param pool The pool; an unregistered one reads zero.
/// @param pair The pair's index (`BadPairIndex`).
/// @param assets What `fund` would pay, in debt-token base units.
/// @param collateralIn The most to post, in collateral-token base units.
/// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
/// @return posted The plan's posts, summed, in collateral-token base units.
function fundingCollateral(address pool, uint8 pair, uint256 assets, uint256 collateralIn, uint256[] calldata usd)
external
view
returns (uint256 posted);
/// @notice The most venue `id` would lend now once `collateralIn` is posted, by every gate a borrow passes
/// (switches, the drawn set, band, pin, free cash, both debt caps, rate ceiling); zero when one is shut,
/// and where a venue holding a minimum position would be left under it by all of that room (`fund`). There
/// a positive room does not mean every smaller borrow is taken: one that leaves the position under the
/// minimum is refused.
/// @param pool The pool.
/// @param id The venue's slot (`BadVenueId` past the record).
/// @param collateralIn The collateral to read as posted, in collateral-token base units.
/// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
/// @return The room, in debt-token base units.
function borrowRoom(address pool, uint16 id, uint256 collateralIn, uint256[] calldata usd)
external
view
returns (uint256);
/// @notice The most venue `id` would take as supply now (switches, the venue's and the token's supply caps); zero
/// when one is shut.
/// @param pool The pool.
/// @param id The venue's slot (`BadVenueId` past the record).
/// @return The room, in debt-token base units.
function supplyRoom(address pool, uint16 id) external view returns (uint256);
/// @notice What `reclaim` of `token` would release now. A venue whose release would revert at the lender still
/// counts, so this reads a ceiling on what the walk pays.
/// @param pool The pool.
/// @param token The collateral token's index.
/// @param usd The pool's checked USD prices, `tokenCount` long (`BadPriceVector`).
/// @return The release, in the token's base units.
function reclaimable(address pool, uint8 token, uint256[] calldata usd) external view returns (uint256);
/// @notice Venue `id`'s health against its threshold, at the caller's prices, which are not checked against the
/// venue's oracle: the collateral's worth at the threshold over the debt, carried through the pair's pin
/// and rounded down. No flow reads it; the pool's flows read `venueHealthy`.
/// @param pool The pool.
/// @param id The venue's slot (`BadVenueId` past the record).
/// @param usd USD prices, `tokenCount` long (`BadPriceVector`).
/// @return healthWad The health, WAD, so 1e18 sits at the threshold; `type(uint256).max` with no debt, and zero at
/// an unchecked pair.
function venueHealth(address pool, uint16 id, uint256[] calldata usd) external view returns (uint256 healthWad);
/// @notice The venue's `IFinancingAccount.healthy`, at the market's own price, which the pool's flows read. Not
/// `venueHealth`, which prices the position at the caller's prices.
function venueHealthy(address pool, uint16 id) external view returns (bool);
/// @notice The actions venue `id` allows now, as its account reports them (`IFinancingAccount.actions`):
/// `venueCapacity`'s `actions` alone, with none of the liquidity and caps that view builds.
function venueActions(address pool, uint16 id) external view returns (uint8);
/// @notice What venue `id` can move now, as its account reports it: each leg's liquidity, caps and rate limits,
/// and the actions the venue allows.
function venueCapacity(address pool, uint16 id) external view returns (IFinancingAccount.Capacity memory);
}
src/libraries/Constants.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
// The protocol's shared units and delay values, each written once. A contract that names one of its own (a public
// getter, or a constant other files read through it) declares it as this file's value, at its own type, so a change
// of a value here reaches every rule that shares it, and a rule that must differ changes its own line alone. The
// pool's own delay names keep their literal values, as a constant read through another can compile to other code:
// `DelayLib.GRACE`, `PriceFeed.REPLACE_DELAY`, `FLAMMFactory.MIN_FEE_DELAY_SEC` and the pool store's three
// `MIN_*_DELAY_SEC`. The shared-constants test holds each of them to its value here.
// ---------------------------------------------------------------- units
/// @dev One in 18 decimals: the unit of every `*Wad` ratio, of LTVs, bands, rates and USD prices.
uint256 constant WAD = 1e18;
/// @dev Parts per million: the unit of a rate, a rung's offset and a word's skew.
uint256 constant PPM = 1e6;
/// @dev The first amount past 128 bits: an output cap, and the first amount past a door's grid.
uint256 constant CAP_128 = 1 << 128;
// ---------------------------------------------------------------- delays
/// @dev The least delay a pool may take for its operator's own changes: a pool's `governanceDelaySec` at birth, a
/// launched pool's delay, its authority's delay, and the least a listing's change reads as the pool's own.
uint32 constant POOL_DELAY_FLOOR_SEC = 1 hours;
/// @dev What a protocol-level loosening waits: the front's timelock, a feed's replacement, a protocol fee's rise, a
/// band ceiling's raise, the beacon delay a cheap lane asks for, a credit door's config, and a listing's change
/// where its pool's own delay cannot be read.
uint32 constant PROTOCOL_DELAY_SEC = 10 days;
/// @dev How long a due change stays applicable outside the pool, whose own window is its delay or a day, whichever
/// is longer: past it the change has lapsed.
uint32 constant CHANGE_WINDOW_SEC = 7 days;
src/libraries/ReentrancyGuardLib.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The reentrancy lock: one flag in transient slot 0 of the running contract, which the pool, the libraries it
/// delegatecalls (they share its flag), the Router and the periphery take. A revert restores the flag with the
/// rest of the call's state, and the end of the transaction clears it.
library ReentrancyGuardLib {
/// @notice A guarded entry or a guarded view ran while a flow held the lock.
error Reentrant();
/// @notice Takes the lock; reverts `Reentrant` where a flow holds it.
function _guard() internal {
_readGuard();
assembly ("memory-safe") {
tstore(0, 1)
}
}
/// @notice Reverts `Reentrant` while a flow holds the lock: its accounting is half-applied, so an external view
/// must not answer. Internal reads bypass it.
function _readGuard() internal view {
bytes4 selector = Reentrant.selector;
assembly ("memory-safe") {
if tload(0) {
mstore(0, selector)
revert(0, 0x04)
}
}
}
/// @notice Whether a flow holds the lock, for views that answer zero or false instead of reverting (EIP-4626
/// `max*`, a cheap lane's state).
function _guardHeld() internal view returns (bool held) {
assembly ("memory-safe") {
held := iszero(iszero(tload(0)))
}
}
/// @notice Reverts `Reentrant` where `reason`, the data a failed external call returned, is that error alone: a held
/// lock, whoever's, is never a refusal for a caller that swallows the failures of a call it makes. Passes
/// every other reason.
function _passOnLock(bytes memory reason) internal pure {
if (reason.length == 4 && bytes4(reason) == Reentrant.selector) revert Reentrant();
}
/// @notice Clears the lock, so a guarded call can run again in the same transaction.
function _unlockGuard() internal {
assembly ("memory-safe") {
tstore(0, 0)
}
}
}
/// @notice The lock as a modifier: one transient slot per contract, released when the guarded call returns.
abstract contract NonReentrant {
/// @dev Takes the lock for the call and clears it when the call returns.
modifier nonReentrant() {
ReentrancyGuardLib._guard();
_;
ReentrancyGuardLib._unlockGuard();
}
}
src/libraries/SafeTransferLib.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The token calls of the pool, the Router, the venue kinds, the PropAMM contracts and the periphery:
/// OpenZeppelin 4.8's `SafeERC20.safeTransfer`, `safeTransferFrom` and `safeApprove`, with its calls, verdicts
/// and revert data, built in scratch memory. The pool and the Router both import it, so the Router compiles no
/// pool source and no pool edit reaches its token calls.
/// @dev Scratch memory is the memory at the free-memory pointer, which no function here moves: nothing it writes
/// outlives the call.
library SafeTransferLib {
/// @notice OpenZeppelin 4.8's `SafeERC20.safeTransfer`: the same call, verdict and revert data (see
/// {_callOptionalReturn}), built in scratch memory.
function safeTransfer(address token, address to, uint256 amount) internal {
uint256 m;
assembly ("memory-safe") {
m := mload(0x40)
mstore(m, shl(224, 0xa9059cbb)) // transfer(address,uint256)
mstore(add(m, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(m, 36), amount)
}
_callOptionalReturn(token, m, 68);
}
/// @notice OpenZeppelin 4.8's `SafeERC20.safeTransferFrom`: the same call, verdict and revert data (see
/// {_callOptionalReturn}), built in scratch memory.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
uint256 m;
assembly ("memory-safe") {
m := mload(0x40)
mstore(m, shl(224, 0x23b872dd)) // transferFrom(address,address,uint256)
mstore(add(m, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(m, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(m, 68), amount)
}
_callOptionalReturn(token, m, 100);
}
/// @dev The `len` bytes of call data at `m` sent to `token` as OpenZeppelin 4.8's `SafeERC20._callOptionalReturn`
/// sends them (`Address.functionCall`: all gas, no value), with its verdicts: a failed call bubbles its revert
/// data, or reverts "SafeERC20: low-level call failed" with none; an empty success needs code at `token`
/// ("Address: call to non-contract"); returned data must open with a bool (else an empty revert, as
/// `abi.decode` gives) that is true ("SafeERC20: ERC20 operation did not succeed"). A success copies no return
/// data but that first word.
function _callOptionalReturn(address token, uint256 m, uint256 len) private {
assembly ("memory-safe") {
// `Error(string)` with the `n`-byte message `w0 ++ w1`, at `p`
function fail(p, n, w0, w1) {
mstore(p, shl(224, 0x08c379a0))
mstore(add(p, 4), 0x20)
mstore(add(p, 36), n)
mstore(add(p, 68), w0)
mstore(add(p, 100), w1)
revert(p, add(68, mul(0x20, div(add(n, 31), 32))))
}
let ok := call(gas(), token, 0, m, len, 0, 0)
let rds := returndatasize()
if iszero(ok) {
if rds {
returndatacopy(m, 0, rds)
revert(m, rds)
}
fail(m, 32, "SafeERC20: low-level call failed", 0)
}
switch rds
case 0 {
if iszero(extcodesize(token)) { fail(m, 29, "Address: call to non-contract", 0) }
}
default {
if lt(rds, 32) { revert(0, 0) }
returndatacopy(m, 0, 32)
let v := mload(m)
if gt(v, 1) { revert(0, 0) }
if iszero(v) { fail(m, 42, "SafeERC20: ERC20 operation did n", "ot succeed") }
}
}
}
/// @notice OpenZeppelin 4.8's `SafeERC20.safeApprove` without its read of the standing allowance: the same call,
/// verdict and revert data (see {_callOptionalReturn}), built in scratch memory. Its callers never grant
/// over a standing grant: a leg's grant is pulled in full or cleared within the call, and a door's standing
/// grant to its front is made once, from zero, each renewal clearing it first. (The Aave kind's standing
/// grant takes its own route, `AaveV3ReadsLib`, once per token, from zero.) A token that refuses a grant
/// over a nonzero one (Ethereum's USDT; BNB Chain's does not) needs that: every grant there is made from
/// zero.
function safeApprove(address token, address spender, uint256 amount) internal {
uint256 m;
assembly ("memory-safe") {
m := mload(0x40)
mstore(m, shl(224, 0x095ea7b3)) // approve(address,uint256)
mstore(add(m, 4), and(spender, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(m, 36), amount)
}
_callOptionalReturn(token, m, 68);
}
}
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.