Verified contractExactUNLICENSED
FLAMMBookLens
Address0x97e6784240652f70491912a33d2c531d9daccffd
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.35
- Same code
2 more contracts
Details
- Compiler
- solc 0.8.35+commit.47b9dedd
- Language
- solidity
- Optimization
- Yes, 100 runs
- EVM version
- cancun
- Via IR
- yes
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,396,607
- Creation transaction
- 0xb01be2c018…64d2c0a6ad
- Libraries
- src/core/mm/MMRouterLib.sol:MMRouterLib0xa474…d2b4e5src/core/flamm/FLAMMLane.sol:FLAMMLane0x0988…d22e98src/core/flamm/FLAMMRoute.sol:FLAMMRoute0x312e…0fdaa9src/periphery/FLAMMMaxima.sol:FLAMMMaxima0x4a99…d6259csrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0x5d47…27cc62src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x0bfe…043753src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xd53f…ed5983src/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0x2577…4e3473src/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0xf0be…2b9555src/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x7a11…58517bsrc/core/mm/CTokenMarketLib.sol:CTokenMarketLib0x18c5…b2071csrc/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0xa6db…bdcbcbsrc/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x0b8d…2e7e5csrc/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0x02b4…731ccesrc/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0xa16d…a201e8src/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0x539e…a79737src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0xa4d3…d5ce2esrc/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0x7c55…d233dfsrc/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0xcda6…a4dcf7src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x8423…7adc96src/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0xa6b4…0c67f9src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0xb489…d3c7cbsrc/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xfaae…2511basrc/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x480f…4e0a81src/hooks/everlong/LeverageLib.sol:LeverageLib0x1b1d…40ad11src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0x9499…409cc2src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0x0775…d94cbesrc/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xabe4…7426f7
10 files
- src/periphery/FLAMMBookLens.solmain6.24 KB
- lib/openzeppelin-contracts-compat/contracts/token/ERC20/IERC20.sol2.77 KB
- lib/openzeppelin-contracts-compat/contracts/utils/math/Math.sol12.51 KB
- src/interfaces/core/IPriceFeed.sol3.71 KB
- src/interfaces/core/flamm/IFLAMM.sol52.68 KB
- src/interfaces/core/flamm/IFLAMMHooks.sol8.36 KB
- src/interfaces/core/flamm/IPairHook.sol14.14 KB
- src/interfaces/core/mm/IFinancingAccount.sol46.04 KB
- src/interfaces/core/mm/IMMRouter.sol70.37 KB
- src/libraries/Constants.sol2.11 KB
src/periphery/FLAMMBookLens.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {IFLAMM} from "src/interfaces/core/flamm/IFLAMM.sol";
import {IMMRouter, pairPrice36} from "src/interfaces/core/mm/IMMRouter.sol";
import {IPriceFeed} from "src/interfaces/core/IPriceFeed.sol";
/// @notice The pool view the lens reads beside `IFLAMM`, which `FLAMM` declares alone.
interface IFLAMMBookViews {
/// @notice The spread fee the pool owes the protocol in token `t`, native units.
function spreadFeeOwed(uint8 t) external view returns (uint256);
}
/// @notice Read-only reporting of any pool book, beside `FLAMMLens`: every token it lists and every credit pair.
/// Price-dependent answers carry an `ok` flag (or a zero price) instead of reverting.
contract FLAMMBookLens {
/// @notice One listed token, the pool asset included: its index; the pool's record of it (`IFLAMM.TokenConfig`:
/// binding, swap and lending policy, custody `held`, the credit pair that owes it, its debt-free flag); its
/// venue legs as the pool reads them (the Router's book: `supplied`, `posted`, `owed`); the protocol's
/// spread fee owed in it; the Router's record (`retired`, `supplyCap`); and its checked USD price with its
/// stamp and peg verdict, `ok` false where unchecked. `price36` is its price against the pool asset (its
/// base units per poolAsset base unit, scaled by 1e36; 1e36 for the pool asset itself), zero where either
/// price is unchecked.
struct Token {
uint8 index;
IFLAMM.TokenConfig config;
uint256 supplied;
uint256 posted;
uint256 owed;
uint256 spreadFeeOwed;
bool retired;
uint128 supplyCap;
bool ok;
uint256 usdWad;
uint48 observedAt;
uint256 price36;
bool pegOk;
}
/// @notice One credit pair: its index; the pool's record (`IFLAMM.PairConfig`: its two tokens, dials (the LTV is
/// the Router's pin), envelope, borrow mirror, whether it is live); the Router's safety gap, venue-oracle
/// band and debt cap (`IMMRouter.PairView`); its binding threshold (`IMMRouter.minLltv`, `NO_VENUE_LLTV`
/// where no venue binds); across its venues, the debt and the collateral the Router recognizes; and its
/// price `price36` (debt base units per collateral base unit, scaled by 1e36), zero where either price is
/// unchecked.
struct Pair {
uint8 index;
IFLAMM.PairConfig config;
uint64 safetyGapWad;
uint64 oracleBandWad;
uint128 debtCap;
uint256 minLltv;
uint256 debt;
uint256 collateral;
uint256 price36;
}
/// @notice Every token the pool lists, token 0 first, as `Token` describes it.
function tokens(address pool) external view returns (Token[] memory out) {
IFLAMM p = IFLAMM(pool);
IMMRouter r = IMMRouter(p.router());
IPriceFeed feed = IPriceFeed(p.priceFeed());
uint256 n = p.tokenCount();
out = new Token[](n);
(uint256[] memory pst, uint256[] memory sup, uint256[] memory owed,) = r.book(pool, 0);
for (uint8 t; t < n; ++t) {
Token memory k = out[t];
k.index = t;
k.config = p.tokenConfig(t);
(k.supplied, k.posted, k.owed) = (sup[t], pst[t], owed[t]);
try IFLAMMBookViews(pool).spreadFeeOwed(t) returns (uint256 f) {
k.spreadFeeOwed = f;
} catch {}
try r.token(pool, t) returns (IMMRouter.TokenView memory tv) {
(k.retired, k.supplyCap) = (tv.retired, tv.supplyCap);
} catch {}
try feed.peekUsd(k.config.token) returns (bool ok, uint256 usd, uint48 ts) {
(k.ok, k.usdWad, k.observedAt) = (ok && usd != 0, usd, ts);
} catch {}
try feed.pegOk(k.config.token) returns (bool peg) {
k.pegOk = peg;
} catch {}
Token memory k0 = out[0];
if (k.ok && k0.ok) k.price36 = pairPrice36(k0.usdWad, k.usdWad, k0.config.decimals, k.config.decimals);
}
}
/// @notice Every credit pair the pool holds, retired ones included, as `Pair` describes it. A venue slot the pool's
/// walks skip (`IFLAMM.retiredVenues`: a retired or a fenced one) counts in none.
function pairs(address pool) external view returns (Pair[] memory out) {
IFLAMM p = IFLAMM(pool);
IMMRouter r = IMMRouter(p.router());
IPriceFeed feed = IPriceFeed(p.priceFeed());
uint256 m = p.pairCount();
out = new Pair[](m);
for (uint8 i; i < m; ++i) {
Pair memory q = out[i];
q.index = i;
q.config = p.pairConfig(i);
IMMRouter.PairView memory pv = r.pair(pool, i);
(q.safetyGapWad, q.oracleBandWad, q.debtCap) = (pv.safetyGapWad, pv.oracleBandWad, pv.debtCap);
try r.minLltv(pool, i) returns (uint256 l) {
q.minLltv = l;
} catch {}
q.price36 = _frame(feed, r.token(pool, q.config.coll), r.token(pool, q.config.debt));
}
uint256 retired;
try p.retiredVenues() returns (uint256 mask) {
retired = mask;
} catch {}
uint256 n = r.venueCount(pool);
for (uint16 v; v < n; ++v) {
if ((retired >> v) & 1 != 0) continue;
uint8 i = r.venue(pool, v).pair;
(, uint256 coll,,, uint256 debt) = r.venuePosition(pool, v);
if (i < m) (out[i].debt, out[i].collateral) = (out[i].debt + debt, out[i].collateral + coll);
}
}
/// @dev Pair (`a` -> `b`)'s `price36` from one read of its two tokens (`pairPrice36`); zero where unchecked.
function _frame(IPriceFeed feed, IMMRouter.TokenView memory a, IMMRouter.TokenView memory b)
private
view
returns (uint256)
{
try feed.peekPair(a.token, b.token) returns (bool ok, uint256 ua, uint256 ub, uint48) {
if (ok) return pairPrice36(ua, ub, a.decimals, b.decimals);
} catch {}
return 0;
}
}
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/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);
}
}
}
src/interfaces/core/IPriceFeed.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice Checked USD quotes per token (`usdWad`: USD per whole token, 18 decimals), alone or for a pair. A consumer
/// derives any price scale from a pair's two prices with one rounding of its own; the feed answers no cross, so
/// it rounds nothing. `observedAt` is the older source timestamp. `usd` / `pair` revert when a check fails; the
/// `peek` variants never revert.
interface IPriceFeed {
/// @notice The token's checked USD price. Reverts `SequencerDown` or `SequencerGrace` at the L2 sequencer gate,
/// `UnknownToken` for a token not listed, `InvalidPrice` for a round with id 0, an answer not positive or a
/// time 0 or in the future, and `StalePrice` past the token's heartbeat bound.
/// @param token The token.
/// @return usdWad USD per whole token, WAD.
/// @return observedAt The round's source timestamp, unix seconds.
function usd(address token) external view returns (uint256 usdWad, uint48 observedAt);
/// @notice `usd` that answers instead of reverting.
/// @param token The token.
/// @return ok Whether every check of `usd` passed; a token not listed reads false.
/// @return usdWad As `usd`; zero where `ok` is false.
/// @return observedAt As `usd`; zero where `ok` is false.
function peekUsd(address token) external view returns (bool ok, uint256 usdWad, uint48 observedAt);
/// @notice True when the token has no peg band, else when its checked USD price is within the band of 1e18;
/// false while the check fails. `UnknownToken` for a token not listed. A pool's swap and flows do not call
/// it: each applies `pegBandWad == 0 || |usdWad - 1e18| <= pegBandWad` to a checked price it already read
/// (a swap's `pair` quote answer, a pro-rata entry's pool book prices), which equals `pegOk` here, so a
/// feed's own `pegOk` rule is not consulted there.
/// @param token The token.
/// @return Whether the token is within its peg band.
function pegOk(address token) external view returns (bool);
/// @notice The token's configured peg band, WAD (0 = no peg check); `UnknownToken` for a token not listed.
function pegBandWad(address token) external view returns (uint256);
/// @notice Both tokens' checked USD prices in one sequencer check, unrounded, and the older stamp: a consumer
/// derives its own price scale from the two. Reverts as `usd` does, on either token.
/// @param base The first token.
/// @param quote The second token.
/// @return baseUsdWad `base`'s USD per whole token, WAD.
/// @return quoteUsdWad `quote`'s USD per whole token, WAD.
/// @return observedAt The older round's source timestamp, unix seconds.
function pair(address base, address quote) external view returns (uint256 baseUsdWad, uint256 quoteUsdWad, uint48 observedAt);
/// @notice `pair` that answers instead of reverting.
/// @param base The first token.
/// @param quote The second token.
/// @return ok Whether every check of `pair` passed; a token not listed reads false.
/// @return baseUsdWad As `pair`; zero where `ok` is false.
/// @return quoteUsdWad As `pair`; zero where `ok` is false.
/// @return observedAt As `pair`; zero where `ok` is false.
function peekPair(address base, address quote)
external
view
returns (bool ok, uint256 baseUsdWad, uint256 quoteUsdWad, uint48 observedAt);
/// @notice Whether `token` is listed.
function hasToken(address token) external view returns (bool);
}
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/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 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/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;
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"src/core/mm/MMRouterLib.sol": {
"MMRouterLib": "0xA4749766934833DfBeaF4Fc0d79c150A1Dd2B4E5"
},
"src/core/flamm/FLAMMLane.sol": {
"FLAMMLane": "0x0988077AB06F1efd8cFa3f08FC60CAf3e6d22e98"
},
"src/core/flamm/FLAMMRoute.sol": {
"FLAMMRoute": "0x312ee92ecd113F925dD513d450b062C8740fDaA9"
},
"src/periphery/FLAMMMaxima.sol": {
"FLAMMMaxima": "0x4A997343D91c981BF63274fc222AA96D32d6259c"
},
"src/core/flamm/FLAMMLawLib.sol": {
"FLAMMLawLib": "0x5D473B15E032756Cd81fc66B8F1e9BE2f427cc62"
},
"src/core/flamm/FLAMMOpsLib.sol": {
"FLAMMOpsLib": "0x0BFe60fB1f5223F1A2b7B02Ef18f5C33fb043753"
},
"src/core/mm/AaveV3ReadsLib.sol": {
"AaveV3ReadsLib": "0xD53F6170226A74D453e84414Ffc2FFcE5ded5983"
},
"src/core/flamm/FLAMMFlowLib.sol": {
"FLAMMFlowLib": "0x2577D707D41209489b2EF53101a4f6baDd4E3473"
},
"src/core/flamm/FLAMMGateLib.sol": {
"FLAMMGateLib": "0xF0BE115A2D6F27274F2e9EE50B89Ed42db2B9555"
},
"src/core/flamm/FLAMMKeptLib.sol": {
"FLAMMKeptLib": "0x7a11899232dd9F17c28bF062Ec2ee2267158517b"
},
"src/core/mm/CTokenMarketLib.sol": {
"CTokenMarketLib": "0x18c53F2aCAbcDEEdb575A136f49fa4C43EB2071c"
},
"src/core/flamm/FLAMMAdmitLib.sol": {
"FLAMMAdmitLib": "0xA6dBD8cD5Cd10F8a5857cbeD54a28405ffbDcBCb"
},
"src/core/flamm/FLAMMBlindLib.sol": {
"FLAMMBlindLib": "0x0b8d436F1a7AE25C5d16955ed4CDa781E42e7E5C"
},
"src/core/flamm/FLAMMClaimLib.sol": {
"FLAMMClaimLib": "0x02b4354a56630ab165A880B1198a603E62731cCE"
},
"src/core/flamm/FLAMMFenceLib.sol": {
"FLAMMFenceLib": "0xA16ddA83f47a42F875f141b6954595D584a201e8"
},
"src/core/flamm/FLAMMFloatLib.sol": {
"FLAMMFloatLib": "0x539EfC2b17cF0fdF254AAaB925b3A7c360A79737"
},
"src/core/flamm/FLAMMQuoteLib.sol": {
"FLAMMQuoteLib": "0xa4D34f4882a529574840881e755BCFae2bd5ce2e"
},
"src/core/flamm/FLAMMTopUpLib.sol": {
"FLAMMTopUpLib": "0x7C55a535Ce298b1e5e6d00F645088F777ad233DF"
},
"src/core/mm/CTokenRewardsLib.sol": {
"CTokenRewardsLib": "0xcda63d7eCCF838F2732Bff676706BDE5abA4DcF7"
},
"src/core/mm/MMRouterAdminLib.sol": {
"MMRouterAdminLib": "0x8423744b3F304ED0B43043d7ad4E7d8A247aDc96"
},
"src/core/flamm/FLAMMPolicyLib.sol": {
"FLAMMPolicyLib": "0xa6B495B2BdcDcf4F327844d9aaA0eD4C550c67F9"
},
"src/core/flamm/FLAMMSettleLib.sol": {
"FLAMMSettleLib": "0xB4890a27205505BDAA05717B6c3aB38b2dd3C7Cb"
},
"src/core/flamm/FLAMMSharedLib.sol": {
"FLAMMSharedLib": "0xFaAEd38962aEb6c282Ac36E0cdE9313AbA2511ba"
},
"src/periphery/FLAMMExitMaxima.sol": {
"FLAMMExitMaxima": "0x480f51866554e92649c9d3502bA31AA4234e0a81"
},
"src/hooks/everlong/LeverageLib.sol": {
"LeverageLib": "0x1B1D1C42d26c169dB59D8681d0FD4C9a2840Ad11"
},
"src/core/flamm/FLAMMMaintainLib.sol": {
"FLAMMMaintainLib": "0x94998f13fc5d5D2271c90b835c6a805dad409cC2"
},
"src/core/flamm/FLAMMPairQuoteLib.sol": {
"FLAMMPairQuoteLib": "0x077523D1427aE408105fe8592F907ECDa0D94cbE"
},
"src/hooks/everlong/EverlongOpsLib.sol": {
"EverlongOpsLib": "0xAbe4447C954E3C7a405f8E75116BF9f5787426F7"
}
},
"optimizer": {
"runs": 100,
"enabled": true
},
"viaSSACFG": false,
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
"solady/=lib/solady/src/",
"forge-std/=lib/forge-std/src/"
],
"experimental": false
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.