Verified contractExactUNLICENSED
FLAMMKeeperGate
Address0xc7130dd0c986f24cdf59c8d7eeed0b88a137f4dd
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.35
- Same code
Only this contract
Details
- Compiler
- solc 0.8.35+commit.47b9dedd
- Language
- solidity
- Optimization
- Yes, 100 runs
- EVM version
- cancun
- Via IR
- yes
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,500,080
- Creation transaction
- 0x74c8348003…956272f634
7 files
- src/periphery/keeper/FLAMMKeeperGate.solmain5.47 KB
- lib/openzeppelin-contracts-compat/contracts/token/ERC20/IERC20.sol2.77 KB
- src/interfaces/core/IEverlongCore.sol889 B
- 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/periphery/keeper/IFLAMMKeeperGate.sol14.11 KB
src/periphery/keeper/FLAMMKeeperGate.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {IEverlongCore} from "src/interfaces/core/IEverlongCore.sol";
import {IFLAMM} from "src/interfaces/core/flamm/IFLAMM.sol";
import {IFLAMMKeeperGate} from "src/periphery/keeper/IFLAMMKeeperGate.sol";
/// @notice One pool's two-tier keeper (`IFLAMMKeeperGate`): the operator's keeper passes any call to the pool, the
/// refill keys its refill and its two flushes alone. Its bindings are immutable: deploy one per pool and refill
/// tier, then point the keeper slot of a pool on a record of its own at it (`EverlongCore`, or a launcher's
/// `DelayedAuthority`); a record several pools bind (`EverlongSharedCore`) refuses a gate, which would be the
/// keeper of them all and reach this pool alone.
/// @dev The refill tier sits in four immutables, each slot past the tier's size holding its first key, so no slot reads
/// zero and no zero sender passes. `refill`, `flush` and `flushPair` send their own calldata on unchanged, as
/// their selectors are the pool's.
contract FLAMMKeeperGate is IFLAMMKeeperGate {
/// @inheritdoc IFLAMMKeeperGate
uint256 public constant MAX_REFILLERS = 4;
/// @inheritdoc IFLAMMKeeperGate
address public immutable POOL;
/// @inheritdoc IFLAMMKeeperGate
address public immutable OPERATOR_KEEPER;
/// @dev The refill tier's first key.
address internal immutable REFILL_0;
/// @dev Its second key, or its first.
address internal immutable REFILL_1;
/// @dev Its third key, or its first.
address internal immutable REFILL_2;
/// @dev Its fourth key, or its first.
address internal immutable REFILL_3;
/// @dev How many keys the refill tier names, one to `MAX_REFILLERS`.
uint256 internal immutable REFILL_COUNT;
/// @param pool The pool every entry calls; it must have code (`BadPool`).
/// @param operatorKeeper The operator's keeper key, the full tier, never zero (`ZeroKeeper`).
/// @param refillKeys The refill tier: one to `MAX_REFILLERS` keys (`BadRefillTier`), none zero (`ZeroKeeper`), and
/// no key named twice in it or as the operator's keeper (`DuplicateKey`).
constructor(address pool, address operatorKeeper, address[] memory refillKeys) {
if (pool.code.length == 0) revert BadPool();
if (operatorKeeper == address(0)) revert ZeroKeeper();
uint256 n = refillKeys.length;
if (n == 0 || n > MAX_REFILLERS) revert BadRefillTier();
for (uint256 i; i < n; ++i) {
address k = refillKeys[i];
if (k == address(0)) revert ZeroKeeper();
if (k == operatorKeeper) revert DuplicateKey();
for (uint256 j; j < i; ++j) {
if (refillKeys[j] == k) revert DuplicateKey();
}
}
POOL = pool;
OPERATOR_KEEPER = operatorKeeper;
address first = refillKeys[0];
REFILL_0 = first;
REFILL_1 = n > 1 ? refillKeys[1] : first;
REFILL_2 = n > 2 ? refillKeys[2] : first;
REFILL_3 = n > 3 ? refillKeys[3] : first;
REFILL_COUNT = n;
}
/// @inheritdoc IFLAMMKeeperGate
function refillers() external view returns (address[] memory keys) {
address[4] memory all = [REFILL_0, REFILL_1, REFILL_2, REFILL_3];
keys = new address[](REFILL_COUNT);
for (uint256 i; i < keys.length; ++i) {
keys[i] = all[i];
}
}
/// @inheritdoc IFLAMMKeeperGate
function inSlot() external view returns (bool) {
return IEverlongCore(IFLAMM(POOL).core()).keeper() == address(this);
}
/// @notice `IFLAMMKeeperGate.refill`, the pool's own `refill` call, passed on ({_pass}).
function refill(uint16[] calldata, uint256[] calldata, uint256) external returns (uint256) {
_pass();
}
/// @notice `IFLAMMKeeperGate.flush`, the pool's own `flush` call, passed on ({_pass}).
function flush(uint8, bool) external returns (uint256, uint256) {
_pass();
}
/// @notice `IFLAMMKeeperGate.flushPair`, the pool's own `flushPair` call, passed on ({_pass}).
function flushPair(uint8, uint8, bool) external returns (uint256, uint256) {
_pass();
}
/// @dev For either tier (`NotKeeper` otherwise): this call's calldata goes to the pool with no value and the gas
/// left, and the pool's return data or revert data ends this call unchanged.
function _pass() private {
address s = msg.sender;
if (s != REFILL_0 && s != REFILL_1 && s != REFILL_2 && s != REFILL_3 && s != OPERATOR_KEEPER) {
revert NotKeeper();
}
address pool = POOL;
assembly ("memory-safe") {
let m := mload(0x40)
calldatacopy(m, 0, calldatasize())
let ok := call(gas(), pool, 0, m, calldatasize(), 0, 0)
returndatacopy(m, 0, returndatasize())
if iszero(ok) { revert(m, returndatasize()) }
return(m, returndatasize())
}
}
/// @inheritdoc IFLAMMKeeperGate
function forward(bytes calldata data) external returns (bytes memory ret) {
if (msg.sender != OPERATOR_KEEPER) revert NotOperatorKeeper();
bool ok;
(ok, ret) = POOL.call(data);
if (!ok) {
assembly ("memory-safe") {
revert(add(ret, 0x20), mload(ret))
}
}
}
}
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);
}
src/interfaces/core/IEverlongCore.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice A pool's authority record as the pool and its periphery read it: `EverlongCore`, or `DelayedAuthority`,
/// which answers the same getters with delays on the owner and the guardian. The pool reads the roles from it
/// on each call, so a change there applies to the pool at once.
interface IEverlongCore {
/// @notice The pool's curator.
function owner() external view returns (address);
/// @notice The pool's guardian; zero for none.
function guardian() external view returns (address);
/// @notice The pool's keeper; zero for none.
function keeper() external view returns (address);
/// @notice The receiver of the curator's performance fee, never zero.
function feeReceiver() external view returns (address);
}
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/periphery/keeper/IFLAMMKeeperGate.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice One pool's keeper in two tiers. The pool's operator opts in by naming the gate the keeper in the pool's
/// authority (its owner's `setKeeper` on `DelayedAuthority` or `EverlongCore`, at once) and opts out the same
/// way. The operator's own keeper key, the full tier, passes any call to the pool (`forward`), every keeper
/// entry included; the refill keys, the refill tier, may only refill a custody-blind pool's buffer (`refill`)
/// and flush as the pool's keeper (`flush`, `flushPair`), three entries either tier sends. Ownerless,
/// immutable, no storage and no funds: the pool and both tiers are fixed at creation, so a rotation is a new
/// gate and the operator's repoint of the slot to it.
/// @dev The rules:
/// - The opt-in: anyone may create a gate, and a contract built to pass for one answers every view here alike, so
/// the views prove nothing: named in the slot, a lookalike hands its creator every keeper entry. The operator
/// names only a gate it created itself, or the address it recomputes under a CREATE2 deployer from the published
/// creation code, the salt, the pool and both tiers, an address that commits to all of them.
/// - The slot: the pool reads its keeper from its authority on each call, so while the slot names this gate every
/// keeper entry admits the gate and no other key as keeper. The operator's keeper key then reaches them only
/// through the gate, its direct `flush` and `flushPair` passing as anyone's with no role refusal, and the
/// operator's own key, the authority's owner, keeps every entry it had. Once the operator names another keeper,
/// or none, the pool refuses what the gate sends to a keeper entry (`NotKeeperOrCurator`) from that call on and
/// reads the flushes it sends, either tier's, as anyone's, with no role refusal; `inSlot` reads which. An
/// operator change leaves the slot as it stands, both tiers with it, for the new operator to repoint.
/// - One pool: the slot is the authority's, the gate one pool's. Any other pool of the authority, which the
/// launcher does not refuse, is left with no keeper but the operator, `inSlot` reading true all the same, so the
/// operator opts in on an authority that backs this pool alone.
/// - The refill tier reaches `refill`, `flush` and `flushPair` and nothing else: no setter, no `maintain`, no
/// `recenter`, no fence unwind and no `forward`. It reaches them by selector, so what they do is what the pool's
/// implementation does at the time of the call, which the Factory's delayed implementation change moves for
/// every pool, gate or not. Each refill is the pool's own, under all of its rules: the pause, the pegs, prices
/// that read (`PriceUnchecked`), the idle floor and the law per token (`LedgerBoundBreached`), each drawn
/// token's reserve target (`InvalidConfig`) and the Router's own at each draw: its pause, the venue's switch,
/// the drawn set, the venue oracle's band, the pin, the pair's and the venue's debt caps (`DebtCapExceeded`) and
/// the rate ceiling (`RateCeiling`).
/// - A flush through the gate is the keeper's, as the pool reads the gate as its keeper. `flush` repays a token
/// with two or more live pairs for no one; at such a token `flushPair` takes the keeper's room
/// (`FLAMMLane.flushPairRoom`): up to all of the token's custody where it is owed at one of them, where its
/// custody covers its whole debt or where none of its pairs is past its cap, and anyone's room otherwise. The
/// keeper's room takes a priced read where the token is owed at two or more pairs and its custody falls short of
/// its debt, and anyone's wherever it is owed at two or more: that read refuses (`PriceUnchecked`) while a price
/// it needs does not read. On a custody-blind pool the buffer's guard, not the room, sizes a repay where one
/// runs, the room's read still running first at `flushPair`: the keeper's repays up to all the custody the pool
/// owns of the token, the whole buffer included, at `flushPair` as far as that pair's venues owe. A refill
/// key's own `flush` and `flushPair`, sent to the pool, stay anyone's: on a custody-blind pool they repay the
/// custody past the token's reserve target, and where the target holds custody back and what is past it falls
/// short of the debt, first each venue past its trigger whose pair's price reads (at `flushPair`, of that pair
/// alone), as far as its debt over what its collateral carries at its target, a venue that refuses a repay now
/// passed over.
/// - The residual: on a custody-blind pool the keeper's repay runs in the keeper's order, the Router's repay order
/// at `flush` and the pair's venues in slot order at `flushPair`, with no cure first of a venue past its
/// trigger. Where two or more venues owe the token and custody is short of their debt, a refill key's flush
/// through the gate can spend the custody at venues within their trigger and leave one past its trigger there,
/// which anyone's flush would have repaid first where the reserve target holds custody back and that venue's
/// pair price reads. At a token with two or more live pairs, which `flush` repays for no one, only anyone's
/// `flushPair` at that venue's own pair cures it first, so the gate's `flushPair` at another pair can spend the
/// custody there and leave that venue past its trigger. A loss then needs an outside price fall past that
/// venue's threshold, beyond what anyone's top-up out of idle collateral (`maintainCollateral`) covers, before
/// the operator acts; with one indebted venue the keeper's flush repays it at least as far as anyone's cure
/// would. The operator's own keeper has the same reach.
/// - The bounds are the operator's: the gate checks none. A debt cap of zero is no cap, so a refill key re-arms
/// each drained buffer until the idle floor stops it; the rate ceiling refuses a draw, not the interest after
/// it. A stolen refill key can also unwind each refill at once, its flush through the gate repaying the buffer,
/// and put a token's custody into one pair's debt with `flushPair`. A repay moves only the pool's own custody
/// into its own debt and never raises a venue's ratio, so that costs availability and the operator's gas, and
/// principal only through the residual above (a venue its flush leaves past its trigger, then an outside price
/// fall past that venue's threshold, beyond what a top-up covers, before the operator acts) or at a lender that
/// fails yet still takes repays before the guardian fences it. The full tier cannot stop a refill key: the
/// operator's or the guardian's brakes stop its refills (the pause, a venue's or a pair's borrow switch) but not
/// its flushes, which the repoint ends; and a gate removed over a stolen key is never named again, as its keys
/// stay in it.
/// - One target: every entry calls the pool alone. The other contracts that read a pool's keeper each admit its
/// operator too (a curve hook's tuning, a tranche controller's rate, an Aave frame account's collateral flag),
/// so moving the slot here leaves the operator every power there, and a custody-blind pool, the one kind
/// `refill` serves, admits no frame venue. A target the caller named would make the gate a keeper on every
/// contract that trusts the pool's keeper; the pool alone keeps its reach to the pool.
/// - No funds: the gate's own code moves and approves no token, takes no ether (no receive, no fallback, no
/// payable entry) and forwards no value. What the pool itself keys to the gate, its shares, a fence claim or
/// parked proceeds, the full tier reaches through `forward`, as any holder's call; any other token sent to it
/// stays there. An entry that pulls from its caller refuses through it (a `FundedRefinance` whose move the
/// pool's custody cannot bridge): the operator sends that one from its own key.
interface IFLAMMKeeperGate {
/// @notice At creation, a pool with no code, zero among them.
error BadPool();
/// @notice At creation, a zero operator's keeper or refill key.
error ZeroKeeper();
/// @notice At creation, a refill tier of no key or of more than `MAX_REFILLERS`.
error BadRefillTier();
/// @notice At creation, a key named twice, in one tier or across both.
error DuplicateKey();
/// @notice `refill`, `flush` or `flushPair` from a caller in neither tier, with arguments the gate's decoder takes:
/// one it refuses (a cut encoding, an offset or a length past the end, a dirty index or flag) ends first,
/// with no data, whoever sends it.
error NotKeeper();
/// @notice `forward` from anyone but the operator's keeper, a refill key included.
error NotOperatorKeeper();
/// @notice The most keys the refill tier may name: 4.
function MAX_REFILLERS() external view returns (uint256);
/// @notice The pool every entry calls.
function POOL() external view returns (address);
/// @notice The operator's keeper key, the full tier: `forward`, `refill`, `flush` and `flushPair`. The operator's
/// own, or its owner key where it runs no keeper: a check of who holds a pool's keeper powers reads this
/// and `refillers`, as the slot shows only the gate.
function OPERATOR_KEEPER() external view returns (address);
/// @notice The refill tier's keys, in the order named at creation: `refill`, `flush` and `flushPair` alone.
function refillers() external view returns (address[] memory keys);
/// @notice Whether the pool's authority names this gate its keeper now; while it does not, the pool refuses every
/// keeper entry the gate sends it (`NotKeeperOrCurator`) and reads the gate's flushes as anyone's.
function inSlot() external view returns (bool);
/// @notice The pool's `refill`, for either tier: this call's calldata goes to the pool unchanged, its selector the
/// pool's own, and the pool's answer comes back unchanged, its revert data included. `NotKeeper` for anyone
/// in neither tier. A call the gate's own decoder refuses (a cut head, an offset or a length past the end)
/// ends at the gate first, with no data, whoever sends it; the arrays' entries it passes on unread, the
/// pool's to check.
/// @param venueIds The venues to borrow at, as the pool's `refill` takes them.
/// @param amounts What to borrow at each.
/// @param maxPost The most of the collateral token's custody the refill may post.
/// @return posted What the pool posted.
function refill(uint16[] calldata venueIds, uint256[] calldata amounts, uint256 maxPost)
external
returns (uint256 posted);
/// @notice The pool's `flush`, for either tier, as `refill` is: this call's calldata goes to the pool unchanged and
/// the pool's answer comes back unchanged, its revert data included; `NotKeeper` for anyone in neither
/// tier, and a cut encoding or a dirty index or flag ends at the gate with no data. While the slot names
/// the gate the pool reads the flush as its keeper's: on a custody-blind pool it repays `a`'s debt up to
/// all the custody the pool owns of it, the buffer included, in the Router's repay order and with no cure
/// first of a venue past its trigger; a token with two or more live pairs it repays for no one. Out of the
/// slot it is anyone's.
/// @param a The token to repay, as the pool's `flush` takes it.
/// @param prove Whether the flush also sets the debt-free flags and pair proofs a fresh position read shows.
/// @return repaid What the pool repaid.
/// @return lent What the pool lent of the custody past the reserve target.
function flush(uint8 a, bool prove) external returns (uint256 repaid, uint256 lent);
/// @notice The pool's `flushPair`, for either tier, as `flush` is. While the slot names the gate the pool reads it
/// as its keeper's: at a token with two or more live pairs the repay of `a` at pair `p` takes the keeper's
/// room (`FLAMMLane.flushPairRoom`), whose priced read, where `a` is owed at two or more pairs and its
/// custody falls short of its debt, refuses (`PriceUnchecked`) while a price it needs does not read. On a
/// custody-blind pool the buffer's guard then sizes the repay in the room's place: up to all the custody
/// the pool owns of `a`, at `p`'s venues in slot order as far as they owe, with no cure first of a venue
/// past its trigger, at `p` or at another pair. Out of the slot it is anyone's.
/// @param a The token to repay, as the pool's `flushPair` takes it.
/// @param p The pair it repays at, one that owes `a`.
/// @param prove As at `flush`.
/// @return repaid What the pool repaid.
/// @return lent What the pool lent of the custody past the reserve target, once `a` owes nothing.
function flushPair(uint8 a, uint8 p, bool prove) external returns (uint256 repaid, uint256 lent);
/// @notice The operator's keeper's call of `data` at the pool, with no value and the gas left: returns the pool's
/// return data and reverts with its revert data, unchanged. `NotOperatorKeeper` for anyone else, the refill
/// tier included.
/// @param data The pool call, its selector and arguments.
/// @return ret The pool's return data.
function forward(bytes calldata data) external returns (bytes memory ret);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 100,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.