Verified contractExactUNLICENSED
FLAMMFloatLib
Address0x6b2b25ebba12e78afea697b9ac6d2167a6518935
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.35
- Same code
Only this contract
Details
- Compiler
- solc 0.8.35+commit.47b9dedd
- Language
- solidity
- Optimization
- Yes, 100 runs
- EVM version
- cancun
- Via IR
- yes
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,480,475
- Creation transaction
- 0x3e6e90b808…0613b4bb42
- Libraries
- src/core/mm/MMRouterLib.sol:MMRouterLib0x95b3…48ef2csrc/core/flamm/FLAMMLane.sol:FLAMMLane0x5d81…90de37src/core/flamm/FLAMMRoute.sol:FLAMMRoute0xb1ff…7fb0fesrc/periphery/FLAMMMaxima.sol:FLAMMMaxima0x6854…90a91bsrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0xf55c…49cf45src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x0be7…5ecc47src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xa5db…72803esrc/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0x2795…4cfb77src/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0x3a05…434368src/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x70ca…60bee4src/core/mm/CTokenMarketLib.sol:CTokenMarketLib0x60e4…314010src/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0x0b10…1ce950src/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x634d…298fcdsrc/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0x5dc3…aa7e91src/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0x9dbb…798f1asrc/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0x6b2b…518935src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0x99de…929869src/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0xe4be…cfac2esrc/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0x93ab…262861src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x6abb…60ea7esrc/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0x3858…f91f06src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0x4551…33b301src/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xb852…b71005src/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x6a6a…798659src/hooks/everlong/LeverageLib.sol:LeverageLib0x8039…16d055src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0xaa54…b56417src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0x3bc5…2055ddsrc/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xf6d5…9dfeef
52 files
The source code is large: one file is shown at a time. Choose a file in the list.
- src/core/flamm/FLAMMFloatLib.solmain62.2 KB
- lib/openzeppelin-contracts-compat/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/openzeppelin-contracts-compat/contracts/token/ERC20/IERC20.sol2.77 KB
- lib/openzeppelin-contracts-compat/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- lib/openzeppelin-contracts-compat/contracts/utils/math/Math.sol12.51 KB
- lib/openzeppelin-contracts-compat/contracts/utils/math/SafeCast.sol35.08 KB
- lib/openzeppelin-contracts-upgradeable-compat/contracts/proxy/utils/Initializable.sol8.91 KB
- lib/openzeppelin-contracts-upgradeable-compat/contracts/token/ERC20/ERC20Upgradeable.sol12.23 KB
- lib/openzeppelin-contracts-upgradeable-compat/contracts/utils/ContextUpgradeable.sol1.19 KB
- src/core/PriceFeed.sol19.12 KB
- src/core/flamm/FLAMM.sol55.93 KB
- src/core/flamm/FLAMMAdmitLib.sol38.79 KB
- src/core/flamm/FLAMMBlindLib.sol60.72 KB
- src/core/flamm/FLAMMClaimLib.sol49.63 KB
- src/core/flamm/FLAMMClaimVault.sol1.65 KB
- src/core/flamm/FLAMMFenceLib.sol72.81 KB
- src/core/flamm/FLAMMFlowLib.sol54.32 KB
- src/core/flamm/FLAMMGateLib.sol93.55 KB
- src/core/flamm/FLAMMKeptLib.sol45.86 KB
- src/core/flamm/FLAMMLane.sol70.59 KB
- src/core/flamm/FLAMMLawLib.sol61.53 KB
- src/core/flamm/FLAMMMaintainLib.sol42.7 KB
- src/core/flamm/FLAMMOpsLib.sol32.2 KB
- src/core/flamm/FLAMMPolicyLib.sol39.79 KB
- src/core/flamm/FLAMMQuoteLib.sol17 KB
- src/core/flamm/FLAMMRoute.sol16.45 KB
- src/core/flamm/FLAMMSettleLib.sol43.2 KB
- src/core/flamm/FLAMMSharedLib.sol13.11 KB
- src/core/flamm/FLAMMStore.sol137.17 KB
- src/core/flamm/FLAMMSwapLib.sol55.86 KB
- src/core/flamm/FLAMMTopUpLib.sol52.56 KB
- src/core/mm/MMRouterAdminLib.sol24.07 KB
- src/core/mm/MMRouterLib.sol72.71 KB
- src/core/mm/VenueAccountBase.sol15.61 KB
- src/core/mm/VenueReads.sol2.05 KB
- src/interfaces/core/IDepositAllowlist.sol1.06 KB
- src/interfaces/core/IEverlongCore.sol889 B
- src/interfaces/core/IPriceFeed.sol3.71 KB
- src/interfaces/core/flamm/IFLAMM.sol52.68 KB
- src/interfaces/core/flamm/IFLAMMHooks.sol8.36 KB
- src/interfaces/core/flamm/IHookCapabilities.sol2.63 KB
- src/interfaces/core/flamm/IPairHook.sol14.14 KB
- src/interfaces/core/mm/IAccountDeployer.sol3.04 KB
- src/interfaces/core/mm/IFinancingAccount.sol47.32 KB
- src/interfaces/core/mm/IHeldRepay.sol2.61 KB
- src/interfaces/core/mm/IMMRouter.sol70.37 KB
- src/interfaces/utils/integrations/IAggregatorV3Interface.sol818 B
- src/libraries/Constants.sol2.11 KB
- src/libraries/DelayLib.sol11.22 KB
- src/libraries/ReentrancyGuardLib.sol2.52 KB
- src/libraries/SafeTransferLib.sol5.11 KB
- src/propamm/libraries/PropAMMLaneLib.sol2.31 KB
src/core/flamm/FLAMMFloatLib.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {
FLAMMStore, InvalidConfig, GuardianMayOnlyTighten, NoPerformanceFeeScheduled, NoOperatorShareScheduled,
HookSetNotReady, CustodyMismatch, NotFront, LaneInitialised, StrictModeSet, CreditPathSet, OutflowCapsSet,
SpreadFeeRateSet, SpreadFeeCollected, PerformanceFeeCancelled, FloatRefilled, Flushed, LanePairsSet,
TokenOutflowCapsSet, FlushedPair, OperatorShareSet, OperatorShareScheduled, OperatorShareCancelled,
OperatorFeeCollected
} from "src/core/flamm/FLAMMStore.sol";
import {FLAMMOpsLib} from "src/core/flamm/FLAMMOpsLib.sol";
import {FLAMMGateLib} from "src/core/flamm/FLAMMGateLib.sol";
import {FLAMMBlindLib} from "src/core/flamm/FLAMMBlindLib.sol";
import {FLAMMLane} from "src/core/flamm/FLAMMLane.sol";
import {FLAMMKeptLib} from "src/core/flamm/FLAMMKeptLib.sol";
import {IFLAMMProtocolFee} from "src/interfaces/core/flamm/IFLAMM.sol";
import {IMMRouter} from "src/interfaces/core/mm/IMMRouter.sol";
import {ReentrancyGuardLib} from "src/libraries/ReentrancyGuardLib.sol";
import {PropAMMLaneLib} from "src/propamm/libraries/PropAMMLaneLib.sol";
/// @notice What a pool reads of its Factory: at the cheap lane's birth, the delay of the pools' beacon upgrades and
/// whether the caller is a front the protocol owner lets initialise a cheap lane; where a token is listed and
/// at a resync, the token's peg group (zero: none), which makes a pair of two tokens of one group correlated
/// (`FLAMMOpsLib.syncKinds`).
interface IFLAMMLaneFactory {
/// @notice The delay of the pools' beacon upgrades, seconds.
function UPGRADE_DELAY() external view returns (uint32);
/// @notice Whether the protocol owner lets `front` initialise a pool's cheap lane (`FLAMMFactory.listLaneFront`).
function isListedFront(address front) external view returns (bool);
/// @notice `token`'s peg group; zero for none.
function pegGroupOf(address token) external view returns (uint16);
}
/// @notice The cheap lane's settings, the float actions, the protocol's spread fee, the view of the deposit basket of
/// the curator's fee mark, the curator's or guardian's cancel of a fee rise, the operator's share of each fill
/// with its delayed rise ({setOperatorShareBp}) and its collection ({collectOperatorFee},
/// {operatorFeeOwed}). `FLAMM`'s fallback reaches each entry with the pool's own selector and
/// calldata, so a pool decodes none of it and its other entries pay nothing for these; each entry checks its
/// own caller and holds the pool's lock. Every public entry here takes the pool's storage from its own
/// namespace, never as an argument: the fallback hands any caller any selector of this library. The helpers the
/// pool's other code calls with its storage (the credit path's fold and settlement, the cap gate, the basket's
/// record) are `FLAMMLane`'s.
/// @dev The float is a token's custody the pool owns (`FLAMMStore.ownHeld`): what it holds unlent and unposted, less
/// the spread fee owed in the token. A cheap fill pays from nothing else, never touching a lender. A float action
/// moves it to or from the lenders: {refillFloat} withdraws supply into it, {flush} and {flushPair} repay debt
/// from it and lend its surplus, and a custody-blind pool's {refill} borrows into it and posts out of it.
/// The pool's delay D is `S.governanceDelaySec`, written once at birth: on a pool whose cheap lane is on, every
/// loosening of the curator's waits D (strict mode off, the credit path on, an outflow cap's raise, a token's caps
/// raised, a pair opened on the cheap lane, a cap's raise), every tightening applies at once, and the curator or
/// the guardian cancels a scheduled loosening. A pair hook's installation waits D on every pool.
library FLAMMFloatLib {
/// @notice The protocol's spread rate at most, bp, on every pool: of each fill's edge against its fee price where
/// the front prices it (a pool whose cheap lane is on), and of the pricing hook's fee where another hook
/// does, which the hook reports as the protocol's part (`EverlongHook`: `feeOut * bp / 1e4`, so above
/// 10,000 it would pass the fee and core would refuse every fill). One ceiling for both.
uint16 internal constant MAX_SPREAD_FEE_BP = 3_000;
/// @notice Each notional rate at most, in `FLAMMStore.NOTIONAL_SCALE` parts of a fill's notional leg: 10 bp.
uint16 internal constant MAX_NOTIONAL_RATE = 10_000;
/// @dev The transient word `initLane` sets for its transaction, which `initLaneTokens` reads: the cheap lane's
/// birth.
uint256 private constant LANE_BIRTH = uint256(keccak256("everlong.flamm.lane.birth")) - 1;
/// @dev The pending table's keys of the cheap lane's loosenings (`FLAMMLane.capDue`).
bytes4 private constant SET_STRICT_MODE = bytes4(keccak256("setStrictMode(bool)"));
bytes4 private constant SET_CREDIT_PATH = bytes4(keccak256("setCreditPath(bool)"));
bytes4 private constant SET_OUTFLOW_CAPS = bytes4(keccak256("setOutflowCaps(uint96)"));
bytes4 private constant SET_LANE_PAIRS = bytes4(keccak256("setLanePairs(uint256)"));
bytes4 private constant SET_TOKEN_CAPS = bytes4(keccak256("setTokenOutflowCaps(uint8,uint48)"));
// ------------------------------------------------------------------ access and the lock
function _s() private pure returns (FLAMMStore.S storage) {
return FLAMMStore.s();
}
/// @dev The cheap lane's settings exist only on a pool whose front initialised it.
function _laneOn(FLAMMStore.S storage $) private view {
if ($.swapBits & FLAMMStore.SWAP_LANE == 0) revert InvalidConfig();
}
// ------------------------------------------------------------------ the cheap lane's birth
/// @notice `IFLAMMLane.initLane`: the front's first birth call, from its `confirmPool` in the pool's
/// one-transaction launch. The caller must be the pool's swap hook and a front the protocol owner lets
/// initialise a cheap lane at the Factory (`NotFront` otherwise). A pool that pays pairs past the hook pair
/// takes their settings in the same transaction ({initLaneTokens}).
/// @dev The call:
/// - gives `laneWord` and `laneConfig` their nonzero version;
/// - sets strict mode, the credit path (`creditPath`, the choice made at the pool's launch through
/// `PropAMMLauncher` for the pool's own swap of every pair its front prices: off is {setCreditPath}'s off,
/// whose turn-on waits the pool's delay) and the outflow caps (the buckets start empty and fill at their
/// rates);
/// - mirrors token 1's bucket unit and notional cap into `laneConfig` (`FLAMMStore.LANE_UNIT_SHIFT`,
/// `LANE_NOTIONAL_SHIFT`);
/// - records a birth pause as the curator's (`LANE_CURATOR_PAUSE`);
/// - fixes the pool's hook set for life (`HookSetLocked`);
/// - from here holds the protocol's high-water rate at zero, as the protocol's part is the spread fee
/// (`setSpreadFeeRates`).
/// It is refused (`InvalidConfig`) where:
/// - the cheap lane is on already;
/// - the protocol's high-water rate is set (the Factory skips its default for a pool born under a cheap-lane
/// front);
/// - a pool-asset notional cap is set (the hook pair's cheap fill honours token 1's alone);
/// - a spread fee is recorded (none at birth: from here a cheap-lane pool owes token 1's fee in `laneWord` and
/// any other token's in its record);
/// - the Factory's beacon upgrades wait less than `FLAMMStore.MIN_LANE_UPGRADE_DELAY_SEC`;
/// - the pool owes anything: a pair's proof (`FLAMMStore.S.pairsFree`), set at its admission, is cleared at a
/// draw only while the cheap lane is on, so one born after a draw would read a drawn pair as proven.
function initLane(bool strict, bool creditPath, uint96 outflowCaps) public {
FLAMMStore.S storage $ = _s();
IFLAMMLaneFactory f = IFLAMMLaneFactory($.factory);
if (msg.sender != $.invariantHook || !f.isListedFront(msg.sender)) revert NotFront();
ReentrancyGuardLib._guard();
if (
$.swapBits & FLAMMStore.SWAP_LANE != 0 || $.protocolFeeBp != 0
|| $.poolBits & (FLAMMStore.POOL_ASSET_CAPPED | FLAMMStore.POOL_SPREAD_OWED) != 0
|| f.UPGRADE_DELAY() < FLAMMStore.MIN_LANE_UPGRADE_DELAY_SEC
|| FLAMMGateLib.owes(FLAMMGateLib.bookOf($))
) revert InvalidConfig();
uint256 version = FLAMMStore.LANE_VERSION << FLAMMStore.LANE_VERSION_SHIFT;
$.laneWord = version | (strict ? FLAMMStore.LANE_STRICT : 0) | (block.timestamp << FLAMMStore.LANE_TIME_SHIFT);
// a pool born paused: the curator's pause from birth, so the pause bits match `paused`; token 1's unit and cap
FLAMMStore.TokenCfg storage c1 = $.tokens[1];
uint256 dec = c1.decimals;
$.laneConfig = version | outflowCaps | (creditPath ? 0 : FLAMMStore.LANE_CREDIT_OFF)
| ($.paused ? FLAMMStore.LANE_CURATOR_PAUSE : 0) | ((dec > 6 ? dec - 6 : 0) << FLAMMStore.LANE_UNIT_SHIFT)
| (uint256(c1.maxSwapNotional) << FLAMMStore.LANE_NOTIONAL_SHIFT);
$.swapBits |= FLAMMStore.SWAP_LANE;
uint256 birth = LANE_BIRTH;
assembly ("memory-safe") {
tstore(birth, 1)
}
emit LaneInitialised(strict, creditPath, outflowCaps);
ReentrancyGuardLib._unlockGuard();
}
/// @notice `IFLAMMLane.initLaneTokens`: the front's second birth call, in `initLane`'s transaction alone (a
/// transient word), once: the ordered pairs past the hook pair the cheap lane may settle (`lanePairs`,
/// pairs of listed tokens, never the hook pair's nor a pair hook's, {_lanePairsAllowed}; a pair whose
/// listing goes live later among them, which {syncListings} opens to the pool's own swap once the front
/// prices it), the outflow caps of each token from 2 on (`tokenCaps[t - 2]`, rate in bits 0-23 and burst in
/// 24-47, their buckets starting empty), and the Router's drawn-token limit, raised where `maxDrawnTokens`
/// is above it (a pool that may owe several tokens), each of which would otherwise wait the pool's delay;
/// and, with `blind`, the custody-blind law for the pool's life (`FLAMMStore.CUSTODY_BLIND`), which turns
/// the credit path off: the pool then starts a debt through {refill}, the keeper's or the curator's, and,
/// once {setCreditPath} turns the path on (three tokens or more, token 1 keeping no buffer), through its
/// own swap on the hook pair alone; each borrowed token's reserve target is its buffer's guard, which the
/// curator sets to the buffer, counting the custody the pool already owns of the token, a curator's seed
/// included.
/// `InvalidConfig` for a mask past those pairs or a caps array that is not one entry per token from 2 on.
function initLaneTokens(uint256 lanePairs, uint48[] calldata tokenCaps, uint8 maxDrawnTokens, bool blind)
public
{
FLAMMStore.S storage $ = _s();
if (msg.sender != $.invariantHook) revert NotFront();
uint256 birth = LANE_BIRTH;
uint256 mark;
assembly ("memory-safe") {
mark := tload(birth)
tstore(birth, 0)
}
if (mark == 0) revert NotFront();
ReentrancyGuardLib._guard();
uint256 n = $.tokenCount;
if (lanePairs & ~_lanePairsAllowed($) != 0 || tokenCaps.length + 2 != n) revert InvalidConfig();
$.lanePairs = lanePairs;
$.routePairs = lanePairs & $.hookPairs;
emit LanePairsSet(lanePairs);
for (uint256 t = 2; t < n; ++t) {
uint48 caps = tokenCaps[t - 2];
$.laneTok[t] =
(uint256(caps) << FLAMMStore.TOK_CAPS_SHIFT) | (block.timestamp << FLAMMStore.TOK_TIME_SHIFT);
emit TokenOutflowCapsSet(uint8(t), caps);
}
if (maxDrawnTokens > $.maxDrawnTokens) {
$.router.setMaxDrawnTokens(maxDrawnTokens);
$.maxDrawnTokens = maxDrawnTokens;
}
if (blind) FLAMMBlindLib.birth($);
ReentrancyGuardLib._unlockGuard();
}
// ------------------------------------------------------------------ the cheap lane past the hook pair
/// @notice The ordered pairs past the hook pair the cheap lane settles (`S.lanePairs`, `hookPairs`' layout), pairs
/// of listed tokens, never a pair hook's ({_lanePairsAllowed}): a closing applies at once (the curator's
/// or the guardian's) and drops a scheduled opening; an opening is the curator's and waits the pool's
/// delay in the pending table (`FLAMMLane.capDue`), the identical call applying it once due, which the
/// curator or the guardian cancels (`FLAMMAdmitLib.cancel`), and which asks the front again of the pairs it opens
/// (`FLAMMLane.syncListings`), so a listing live before its pair joined the cheap lane trades from then on.
/// The closings a mask makes apply at once even where it also opens.
function setLanePairs(uint256 mask) public {
FLAMMStore.S storage $ = _s();
bool guardian = FLAMMStore.curatorOrGuardian($);
ReentrancyGuardLib._guard();
_laneOn($);
if (mask & ~_lanePairsAllowed($) != 0) revert InvalidConfig();
uint256 cur = $.lanePairs;
bool opens = mask & ~cur != 0;
if (guardian && opens) revert GuardianMayOnlyTighten();
uint256 next = cur;
if (cur & ~mask != 0) {
next = cur & mask;
$.lanePairs = next;
emit LanePairsSet(next);
}
if (FLAMMLane.capDue($, !opens, abi.encode(SET_LANE_PAIRS, mask)) == 0 && opens) {
next = mask;
$.lanePairs = mask;
emit LanePairsSet(mask);
// a listing that went live before its pair joined the cheap lane trades now: the pairs this opens are
// asked again
FLAMMLane.syncListings($, mask & ~cur);
}
// the route's one mask beside the trade mask (`S.routePairs`)
if (next != cur) $.routePairs = next & $.hookPairs;
ReentrancyGuardLib._unlockGuard();
}
/// @notice The outflow caps of token `t`, a token from 2 on (rate in bits 0-23, burst in 24-47, 24-bit amounts in
/// its 1e-6 units; tokens 0 and 1 take {setOutflowCaps}): caps neither of whose amounts is higher apply at
/// once, the curator's or the guardian's, after a refill under the old ones; a raise is the curator's and
/// waits the pool's delay in the pending table (`FLAMMLane.capDue`), the identical call applying it once
/// due. Its bucket bounds every payout of the token, the cheap lane's and the pool's own swap's alike.
function setTokenOutflowCaps(uint8 t, uint48 caps) public {
FLAMMStore.S storage $ = _s();
bool guardian = FLAMMStore.curatorOrGuardian($);
ReentrancyGuardLib._guard();
_laneOn($);
FLAMMStore.checkToken($, t);
if (t < 2) revert InvalidConfig();
uint256 w = FLAMMLane.refillTok($.laneTok[t]);
uint256 cur = (w >> FLAMMStore.TOK_CAPS_SHIFT) & FLAMMStore.TOK_CAPS_MASK;
bool tight = _noHigher(caps, cur);
if (guardian && !tight) revert GuardianMayOnlyTighten();
if (FLAMMLane.capDue($, tight, abi.encode(SET_TOKEN_CAPS, t, caps)) == 0) {
$.laneTok[t] = (w & ~(FLAMMStore.TOK_CAPS_MASK << FLAMMStore.TOK_CAPS_SHIFT))
| (uint256(caps) << FLAMMStore.TOK_CAPS_SHIFT);
emit TokenOutflowCapsSet(t, caps);
}
ReentrancyGuardLib._unlockGuard();
}
/// @notice The cheap lane past the hook pair as it stands: the ordered pairs it settles, the live pairs proven to
/// owe nothing (`S.pairsFree`, which its debt rule reads) and token `t`'s bucket word (`S.laneTok`; zero
/// for tokens 0 and 1, whose buckets are in the cheap lane's words, `IFLAMMLane.lane`).
function laneTokens(uint8 t) public view returns (uint256 lanePairs, uint32 pairsFree, uint256 laneToken) {
FLAMMStore.S storage $ = _s();
return ($.lanePairs, $.pairsFree, t > 1 ? $.laneTok[t] : 0);
}
/// @notice `IFLAMMLane.syncListings`: asks the front again which pairs past the hook pair it prices
/// (`IPairHook.pricesPair`, `FLAMMLane.syncListings`) and records each answer in `S.hookPairs`, the mask by
/// which the pool's own swap opens a pair and, with `S.lanePairs`, the cheap lane settles one
/// (`S.routePairs`): a listing the front adds after the pool's birth opens, and one it retires closes.
/// Permissionless and idempotent, under the lock. Returns the mask it leaves, as `FLAMM.tradablePairs`
/// shows it.
/// @dev - It asks of the pairs in `S.lanePairs`, and of every other pair it holds open for the front (one the
/// guardian cut from `S.lanePairs`, or never on it), which may only close; never of the hook pair's or a
/// pair hook's. So it opens only what `S.lanePairs` opened, claims no pair hook's pair, and closes a pair
/// only where the front answers that it does not price it; the curator's trade mask still gates every pair.
/// - A pair the front gives no answer for, a revert (a call short of gas included) or a word that is not a
/// bool, stands as it was: no caller's gas makes an answer read as no, and no pair's failure stops another's
/// resync.
/// - Beside this resync and an opening of `S.lanePairs` ({setLanePairs}), the pool records the front's answers
/// only at a hook's installation, a pair hook's removal and a token's listing (`FLAMMLane.syncPairs`, under
/// the same close-only rule off `S.lanePairs`); a pair hook's checks ({setPairHook}) ask it too and record
/// nothing.
function syncListings() public returns (uint256 next) {
FLAMMStore.S storage $ = _s();
ReentrancyGuardLib._guard();
_laneOn($);
next = FLAMMLane.syncListings($, type(uint256).max);
ReentrancyGuardLib._unlockGuard();
}
/// @dev The ordered pairs the cheap lane may settle past the hook pair: every pair of two listed tokens not both of
/// the hook pair, less the pair hook's pairs. The front need not price one yet: a listing may go live after
/// the pool's birth ({syncListings}).
function _lanePairsAllowed(FLAMMStore.S storage $) private view returns (uint256 m) {
uint256 n = $.tokenCount;
for (uint256 i; i < n; ++i) {
for (uint256 j; j < n; ++j) {
if (i != j && (i | j) > 1) m |= uint256(1) << (16 * i + j);
}
}
if ($.swapBits & FLAMMStore.SWAP_PAIR_HOOK != 0) m &= ~FLAMMLane.orderedPairs($, $.pairHookWord);
}
// ------------------------------------------------------------------ the pair hook
/// @notice A second swap hook for the unordered pairs past the hook pair that `mask` names
/// (`FLAMMStore.pairHookBit`: pairs of listed tokens under `FLAMMStore.PAIR_HOOK_TOKENS`, never tokens 0
/// and 1 together), or none (`hook` zero). Each pair then has one pricer: the pair hook for its pairs, the
/// swap hook (a cheap-lane pool's front) for every other; the cheap lane never settles a pair hook's pair
/// (`S.lanePairs` leaves them). The body runs in `FLAMMLane.updatePairHook`.
/// @dev - An installation or a replacement is the curator's and waits D, the pool's own delay, and nothing longer,
/// on the pending table: the first call schedules it (`AdmissionScheduled`), dropping one scheduled before
/// it, so one stands at a time; the identical call once due and within its window applies it, and the
/// curator or the guardian cancels it (`FLAMMAdmitLib.cancel`). It applies whole: the hook prices the mask's pairs
/// from then on, and opens none of them in the trade mask: a pair open there keeps trading under the new
/// pricer, and a closed one, a closing made after the schedule included, waits the trade mask's own delayed
/// opening; a replacement closes the old mask's pairs the new one leaves, as a removal does.
/// - A removal, the curator's or the guardian's, applies at once, closes the mask's pairs in the trade mask
/// (and in a scheduled opening), so no pair passes back to the swap hook without the trade mask's delayed
/// opening, and drops a scheduled installation, as every tightening drops its setting's scheduled loosening.
/// - The hook must price every pair the mask names both ways and, on a pool whose cheap lane is on, the front
/// none of them either way, at the schedule and again at the installation: each pair has one pricer. It must
/// hold code, name this pool, answer the interface version, declare `HOOK_CAP_PAIR_HOOK`, and meet the
/// pool's band mode and pair shape (`FLAMMGateLib.checkHook`).
/// - Nothing else vets it, a cheap-lane pool's front included: which hook prices the mask's pairs, and how, is
/// the curator's choice and the curator's risk, which depositors see scheduled for D before it applies.
/// Core's fee bounds, band, notional caps and, on a cheap-lane pool, the paid token's outflow bucket bound
/// every fill it prices, and the protocol's part is what the hook reports, within core's bound, and at least
/// the pair's notional floor, owed in the token paid.
/// - While it is set, the swap's rotation and custody-only bits hold only where both hooks declare them.
function setPairHook(address hook, uint256 mask) public {
FLAMMLane.updatePairHook(_s(), hook, mask);
}
/// @notice The pair hook and the unordered pairs it prices (`FLAMMStore.pairHookBit`); zero when none.
function pairHook() public view returns (address hook, uint256 mask) {
uint256 w = _s().pairHookWord;
return (address(uint160(w)), w & ~uint256(type(uint160).max));
}
// ------------------------------------------------------------------ the cheap lane's switches and caps
/// @notice Strict mode (asks also need token 1 proven debt-free): the curator or the guardian turns it on at once,
/// which drops a scheduled turn-off; only the curator turns it off, through the pending table: the first
/// call schedules it for the pool's delay, the identical call within one more delay applies it (past that
/// it lapses), and the curator or the guardian cancels it (`FLAMMAdmitLib.cancel`; `FLAMMLane.capDue`).
function setStrictMode(bool on) public {
FLAMMStore.S storage $ = _s();
_gate($, on);
if (FLAMMLane.capDue($, on, abi.encode(SET_STRICT_MODE, on)) == 0) {
$.laneWord = on ? $.laneWord | FLAMMStore.LANE_STRICT : $.laneWord & ~FLAMMStore.LANE_STRICT;
emit StrictModeSet(on);
}
ReentrancyGuardLib._unlockGuard();
}
/// @notice The credit path, the pool's own swap of every pair its front prices (the hook pair and the listings past
/// it; a pair hook's pairs are not on it): as the pool's launch through `PropAMMLauncher` set it
/// ({initLane}). The curator or the guardian turns it off at once, which drops a scheduled turn-on; only
/// the curator turns it on, through the pending table, as {setStrictMode}. A custody-blind pool's turns on
/// only on three tokens or more with token 1 keeping no buffer (no reserve target), else `InvalidConfig`:
/// there its swap runs on the hook pair alone and posts nothing of the idle floor (`FLAMMLawLib.lawBound`,
/// which a two-token pool's swap does not run), each slice at its venue's pin, so its posted collateral
/// alone carries every pair within its pin, the blind law.
function setCreditPath(bool on) public {
FLAMMStore.S storage $ = _s();
_gate($, !on);
if (
on && $.features & FLAMMStore.CUSTODY_BLIND != 0 && ($.tokenCount < 3 || $.tokens[1].reserveTarget != 0)
) revert InvalidConfig();
if (FLAMMLane.capDue($, !on, abi.encode(SET_CREDIT_PATH, on)) == 0) {
$.laneConfig = on ? $.laneConfig & ~FLAMMStore.LANE_CREDIT_OFF : $.laneConfig | FLAMMStore.LANE_CREDIT_OFF;
emit CreditPathSet(on);
}
ReentrancyGuardLib._unlockGuard();
}
/// @notice The outflow caps (`FLAMMStore.LANE_CAPS_MASK`'s layout): caps none of whose four amounts is higher apply
/// at once, the curator's or the guardian's, and drop a scheduled raise; any other is the curator's,
/// through the pending table, as {setStrictMode}. New caps apply from their change: the buckets refill to
/// it under the caps they had.
function setOutflowCaps(uint96 caps) public {
FLAMMStore.S storage $ = _s();
uint256 cfg = $.laneConfig;
bool tight = _noHigher(caps, cfg & FLAMMStore.LANE_CAPS_MASK);
_gate($, tight);
if (FLAMMLane.capDue($, tight, abi.encode(SET_OUTFLOW_CAPS, caps)) == 0) {
$.laneWord = FLAMMLane.refill($.laneWord, cfg);
$.laneConfig = (cfg & ~FLAMMStore.LANE_CAPS_MASK) | caps;
emit OutflowCapsSet(caps);
}
ReentrancyGuardLib._unlockGuard();
}
/// @notice On a custody-blind pool (`FLAMMStore.CUSTODY_BLIND`), the pool asset's custody the pool owns that a
/// refill leaves idle at least ({refill}), base units, in its own word (`FLAMMStore.S.idleFloor`, read by
/// {idleFloor}): the asks' inventory, which a refill through a drain would otherwise post away, so that no
/// ask brings in what repays the debt. A refill refuses while that custody sits under the floor after its
/// own post, a state check, so a top-up made ahead does not step around it; a top-up, an entry and the
/// permissionless maintainer stay unbounded by it, as a rescue and the LPs' flows come first, and the
/// refills after one that leaves custody under the floor refuse until custody is back over it. A raise
/// applies at once, the curator's or the guardian's, and drops a scheduled cut; a cut is the curator's,
/// through the pending table, as {setStrictMode}. Zero at birth, and no refill runs while it is: the
/// curator sets it after the pool's launch through `PropAMMLauncher`, beside each borrowed token's reserve
/// target. The body runs in `FLAMMBlindLib.setIdleFloor`.
function setIdleFloor(uint128 floor) public {
FLAMMBlindLib.setIdleFloor(_s(), floor);
}
/// @notice A custody-blind pool's idle floor ({setIdleFloor}), base units: zero on any other pool, and on one whose
/// curator has not set it, so no refill runs.
function idleFloor() public view returns (uint256) {
return uint128(_s().idleFloor);
}
/// @notice On a custody-blind pool, the local refill's window, seconds, at most an hour
/// (`FLAMMBlindLib.MAX_LOCAL_WINDOW`); zero, as at birth, is off. While it is on, a refill with `maxPost`
/// zero within the window of the last whole refill is held to the venues it draws at alone
/// ({refill}). A cut, the turn-off among them, applies at once, the curator's or the guardian's, and
/// drops a scheduled raise; a raise, the turn-on among them, is the curator's, through the pending table,
/// as {setStrictMode}. The keeper cannot call it. The body runs in `FLAMMBlindLib.setLocalRefill`.
function setLocalRefill(uint32 window) public {
FLAMMBlindLib.setLocalRefill(_s(), window);
}
/// @notice A custody-blind pool's local refill ({setLocalRefill}): its window, seconds, zero while it is off, and
/// the time of the last whole refill made under it (a refill with `maxPost` over zero that passed; a
/// release writes none), unix seconds, zero where none was since the window was last turned on, raised
/// or turned off. A refill with `maxPost` zero is local until `wholeAt` plus `window`, that second
/// included.
function localRefill() public view returns (uint32 window, uint48 wholeAt) {
uint256 w = _s().idleFloor;
return (uint32(w >> 128), uint48(w >> 160));
}
/// @notice Whether the pool's credit law is custody-blind (`FLAMMStore.CUSTODY_BLIND`), set at the cheap lane's
/// birth for good: its refill ({refill}) and idle floor ({setIdleFloor}) exist, its own swap runs on its
/// hook pair alone and only once {setCreditPath} turns the credit path on, and its front binds its
/// listings to a desk as PRINT or WORD, never NONE, on a pair with or without a price source. A PRINT fill is held to its price fence; a WORD fill pays out of the borrowed buffer at the
/// desk's signed word, with no price fence, within custody, the outflow buckets and the debt caps. On an
/// asset pair a PRINT listing's price fence is built on the source's print scaled by the pair's module,
/// whose multiplier the token's issuer, a shares oracle or a vendor registry sets: the pool trusts them as
/// it trusts the source.
function custodyBlind() public view returns (bool) {
return _s().features & FLAMMStore.CUSTODY_BLIND != 0;
}
/// @notice On a pool whose cheap lane is on, the guardian that set the guardian's pause, or the guardian in office
/// that took it over (`FLAMMLane.setLanePause`); zero while none stands. The guardian in office lifts that
/// pause, and the curator once this address is not the pool's guardian any more. The lift ends the
/// guardian's pause; the pool stays paused while the curator's stands.
function lanePauser() public view returns (address) {
return _s().lanePauser;
}
/// @dev The gate of the cheap lane's setters: the curator, or the guardian for a tightening (`tight`); the lock;
/// the cheap lane on.
function _gate(FLAMMStore.S storage $, bool tight) private {
if (FLAMMStore.curatorOrGuardian($) && !tight) revert GuardianMayOnlyTighten();
ReentrancyGuardLib._guard();
_laneOn($);
}
/// @dev Whether none of `next`'s 24-bit amounts (four on the hook pair's caps, two on a token's) is above `cur`'s.
function _noHigher(uint256 next, uint256 cur) private pure returns (bool) {
for (uint256 i; i < 4; ++i) {
uint256 k = 24 * i;
if (PropAMMLaneLib.amount24((next >> k) & 0xffffff) > PropAMMLaneLib.amount24((cur >> k) & 0xffffff)) {
return false;
}
}
return true;
}
// ------------------------------------------------------------------ the protocol's spread fee
/// @notice The protocol's rates, the Factory's alone, which applies a cut at once and a rise after its delay, each
/// field apart, and relays the whole word (`rates`): the spread rate in bits 0-15
/// (`FLAMMStore.S.spreadFeeBp`), at most {MAX_SPREAD_FEE_BP}; the notional rate of the pool's other pairs
/// in bits 16-31 and of its correlated pairs in bits 32-47 (`FLAMMStore.S.feeRates`), each at most
/// {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 on the pair. A pool with neither notional
/// rate reads neither (`FLAMMStore.SWAP_NOTIONAL`). They apply to later fills only: nothing is minted, so
/// nothing settles at a change.
function setSpreadFeeRates(uint48 rates) public {
FLAMMStore.S storage $ = _s();
FLAMMStore.requireFactory($);
ReentrancyGuardLib._guard();
(uint16 feeBp, uint16 other, uint16 correlated) = (uint16(rates), uint16(rates >> 16), uint16(rates >> 32));
if (feeBp > MAX_SPREAD_FEE_BP || other > MAX_NOTIONAL_RATE || correlated > MAX_NOTIONAL_RATE) {
revert InvalidConfig();
}
$.spreadFeeBp = feeBp;
$.feeRates = ($.feeRates & ~FLAMMStore.RATES_MASK) | other | (uint256(correlated) << 16);
uint8 sb = $.swapBits;
$.swapBits = (other | correlated) != 0 ? sb | FLAMMStore.SWAP_NOTIONAL : sb & ~FLAMMStore.SWAP_NOTIONAL;
emit SpreadFeeRateSet(feeBp, other, correlated);
ReentrancyGuardLib._unlockGuard();
}
/// @notice Re-reads the Factory's peg group of each of the pool's tokens and rewrites which of its pairs are
/// correlated (`FLAMMOpsLib.syncKinds`). Anyone may call it: the tags are the Factory's alone, and a
/// pair keeps the rate its tags gave it until this runs.
function syncFeeKinds() public {
ReentrancyGuardLib._guard();
FLAMMOpsLib.syncKinds(_s());
ReentrancyGuardLib._unlockGuard();
}
/// @notice The protocol's notional rates and the pool's correlated pairs (`FLAMMStore.S.feeRates`).
function feeRates() public view returns (uint256) {
return _s().feeRates;
}
/// @notice Pays the Factory's protocol fee receiver the spread fee owed in token `t`, in kind, as far as the
/// token's custody holds it (`FLAMMStore.feeOwed`: `laneWord`'s accrual first, then the hook fills'
/// record, less the operator's share the record holds, `FLAMMStore.shareOwed`); the pool owns none of
/// that custody, so the payment moves no value of the LPs' and nothing the credit law reads. A part owed
/// past custody stays owed until custody holds it, and is paid before the operator's share
/// ({collectOperatorFee}). One token per call, so a token whose transfer fails (a paused or
/// blocked one) stops no other token's collection. Permissionless and never paused; reads no price.
function collectSpreadFee(uint8 t) public {
FLAMMStore.S storage $ = _s();
ReentrancyGuardLib._guard();
FLAMMStore.checkToken($, t);
_payFee($, t, FLAMMStore.heldOf($, t));
ReentrancyGuardLib._unlockGuard();
}
/// @dev {collectSpreadFee}'s payment of the spread fee owed in token `t` as far as custody `h` holds it,
/// `laneWord`'s accrual first, then the hook fills' record (`FLAMMLane.drainOwed`).
function _payFee(FLAMMStore.S storage $, uint8 t, uint256 h) private {
(uint256 recorded, uint256 accrued) = FLAMMLane.owedParts($, t);
uint256 total = recorded + accrued;
uint256 op = FLAMMStore.shareOwed($, t);
uint256 pay = Math.min(total > op ? total - op : 0, h);
if (pay != 0) {
FLAMMLane.drainOwed($, t, pay, recorded, accrued);
FLAMMStore.setHeld($, t, h - pay);
address token = FLAMMStore.tokenOf($, t);
address to = IFLAMMProtocolFee($.factory).protocolFeeReceiver();
FLAMMStore.safeTransfer(token, to, pay);
if (FLAMMStore.balanceOfThis(token) < h - pay) revert CustodyMismatch();
emit SpreadFeeCollected(t, to, pay);
}
}
/// @notice Pays the core's fee receiver (`IEverlongCore.feeReceiver`, read now) the operator's share owed in token
/// `t` (`FLAMMStore.shareOwed`), in kind, as far as the token's custody holds it past the protocol's part
/// owed beside it, which is paid first (`collectSpreadFee`); the rest stays owed until
/// custody holds it. The pool owns none of that custody, so the payment moves no value of the LPs' and
/// nothing the credit law reads. One token per call; permissionless and never paused; reads no price.
function collectOperatorFee(uint8 t) public {
FLAMMStore.S storage $ = FLAMMStore.s();
ReentrancyGuardLib._guard();
FLAMMStore.checkToken($, t);
uint256 op = FLAMMStore.shareOwed($, t);
if (op != 0) {
(uint256 recorded, uint256 accrued) = FLAMMLane.owedParts($, t);
uint256 total = recorded + accrued;
uint256 h = FLAMMStore.heldOf($, t);
// the protocol's part first: the share is paid out of what custody holds past it
uint256 prot = total > op ? total - op : 0;
uint256 pay = h > prot ? h - prot : 0;
if (pay > op) pay = op;
if (pay > total) pay = total;
if (pay != 0) {
FLAMMLane.drainOwed($, t, pay, recorded, accrued);
FLAMMStore.cutShare($, t, pay);
FLAMMStore.setHeld($, t, h - pay);
address token = FLAMMStore.tokenOf($, t);
address to = $.core.feeReceiver();
FLAMMStore.safeTransfer(token, to, pay);
if (FLAMMStore.balanceOfThis(token) < h - pay) revert CustodyMismatch();
emit OperatorFeeCollected(t, to, pay);
}
}
ReentrancyGuardLib._unlockGuard();
}
/// @notice What the pool owes the operator in token `t`, native units (`FLAMMStore.shareOwed`): a part of what
/// `spreadFeeOwed(t)` reads, which holds it with the protocol's.
function operatorFeeOwed(uint8 t) public view returns (uint256) {
return FLAMMStore.shareOwed(FLAMMStore.s(), t);
}
// ------------------------------------------------------------------ the float actions
/// @notice Withdraws token `a`'s supply into custody, up to `amount` and to its reserve target (the custody the
/// pool owns), where that is at least the token's minimum supply batch (and a unit); else returns without
/// calling the Router. A batch at its maximum refills nothing, as a swap's refill. Permissionless: it only
/// moves the pool's own value from a lender to custody, within the target. The venues' gates apply (a
/// lender that refuses is passed over).
function refillFloat(uint8 a, uint256 amount) public returns (uint256 got) {
FLAMMStore.S storage $ = _s();
ReentrancyGuardLib._guard();
FLAMMStore.checkToken($, a);
FLAMMStore.TokenCfg storage c = $.tokens[a];
uint256 batch = c.minSupplyBatch;
if (!$.noLiveVenue && c.partner != FLAMMStore.NO_PARTNER && batch != type(uint128).max) {
FLAMMGateLib.Leg memory L = FLAMMGateLib.bookOf($).legs[a];
uint256 target = c.reserveTarget;
uint256 want = L.held < target ? Math.min(Math.min(target - L.held, amount), L.supplied) : 0;
if (want != 0 && want >= batch) {
address token = FLAMMStore.tokenOf($, a);
uint256 before = FLAMMStore.balanceOfThis(token);
$.router.withdrawCascade(a, want, address(this));
got = FLAMMStore.balanceOfThis(token) - before;
FLAMMStore.setHeld($, a, FLAMMStore.heldOf($, a) + got);
emit FloatRefilled(a, got);
}
}
ReentrancyGuardLib._unlockGuard();
}
/// @notice Repays token `a`'s debt with the custody the pool owns of it, through the Router's repay cascade, which
/// changes no net debt; with `prove`, sets every token's debt-free flag a fresh position read shows owing
/// nothing, and on a cheap-lane pool every pair proof ({_prove}); then lends the custody over the reserve
/// target where it is at least a batch, as a swap lends its input's surplus: unpaused,
/// `FEATURE_SUPPLY_LENDING` set, never a token that backs a debt (its custody is backing), the pool asset
/// only where its batch allows it, and nothing while a venue that would take it reports a loss on its
/// supply of `FLAMMStore.LOSS_MOVE_FLOOR` or more. A token owed at two or more pairs, or owed at all with two or more live
/// pairs, is neither repaid nor lent here: which of its debts a repay may take is the swap's rule
/// (`FLAMMSettleLib`), a cascade could repay one whose backing the law does not need, and its custody may
/// be what another live pair pays its sellers from, which {flushPair} leaves to the keeper or the curator.
/// On a custody-blind pool anyone but the keeper or the curator repays only the custody past the reserve
/// target, the buffer's guard, but while a venue owing `a` is past its trigger, and nothing at a venue
/// its cure passed over as past saving (`FLAMMBlindLib.repayable`, which then makes those repays itself
/// and leaves the cascade none); such a flush lends nothing of `a` either.
/// Permissionless.
function flush(uint8 a, bool prove) public returns (uint256 repaid, uint256 lent) {
FLAMMStore.S storage $ = _s();
ReentrancyGuardLib._guard();
FLAMMStore.checkToken($, a);
if (!$.noLiveVenue) {
FLAMMGateLib.accrueRead($, 0);
FLAMMGateLib.Book memory b = FLAMMGateLib.bookOf($);
FLAMMGateLib.Leg memory L = b.legs[a];
address token = FLAMMStore.tokenOf($, a);
IMMRouter r = $.router;
uint256 own = L.held;
bool many = L.partner == FLAMMStore.MANY || (L.owed != 0 && FLAMMGateLib.split(b, a));
uint256 pay = many ? 0 : Math.min(L.owed, own);
if (pay != 0) {
uint256 before = FLAMMStore.balanceOfThis(token);
// `many`, from here: nothing is lent either where the cure passed a venue over
(pay, many) = _repayable($, b, a, own, pay, FLAMMStore.NO_PAIR);
if (pay != 0) {
FLAMMStore.approveRouter($, token, pay);
if (r.repayCascade(a, pay) != pay) FLAMMStore.revoke($, token);
}
repaid = before - FLAMMStore.balanceOfThis(token);
own -= repaid;
}
if (prove) _prove($);
if (!many) lent = _lendSurplus($, b, a, token, own);
FLAMMStore.setHeld($, a, FLAMMStore.heldOf($, a) - repaid - lent);
if (FLAMMStore.balanceOfThis(token) < FLAMMStore.heldOf($, a)) revert CustodyMismatch();
emit Flushed(a, repaid, lent);
}
ReentrancyGuardLib._unlockGuard();
}
/// @notice {flush} at one pair: repays token `a`'s debt at pair `p` (which owes `a`) with the custody the pool owns
/// of it, venue by venue in the pair's slot order through the Router's single-venue repay (a venue that
/// owes nothing or refuses a repay now passed over), which changes no net debt; with `prove`, a fresh
/// position read sets the flags and the pair proofs it shows ({_prove}); then, once `a` owes nothing at
/// all, lends the custody over its reserve target as {flush} does. Permissionless.
/// @dev The one repay of a token with two or more live pairs, which {flush} leaves, within
/// `FLAMMLane.flushPairRoom`:
/// - owed at one of them: only the keeper or the curator places the custody, at no price read, as it may be
/// what another live pair pays its sellers from;
/// - owed at two or more, with custody that covers its whole debt: the keeper or the curator places it at no
/// price read, and anyone else by the next rule;
/// - owed at two or more otherwise, at a fresh priced read: while some pair of the token is past its cap the
/// repay goes only to such a pair, only as far as its own excess, and never spends the cash that nets
/// another pair's excess; with none past only the keeper or the curator places the custody.
/// So the credit law holds after it where it held, and anyone else spends only custody that nets the excess it
/// repays.
/// - That repay keeps the law and the payouts where they stand when it is made, and where it clears the
/// token's last excess it reopens the other pairs' draws at once.
/// - But it turns the custody that netted the excess into that pair's own borrowing room: once the crashed
/// collateral recovers, a pair at its cap that paid its sellers from that custody pays them again only after
/// an inflow as large, and a later fall of another pair's collateral finds no custody to net it. The
/// keeper's or the curator's repay does the same.
/// - Where each pair's excess is no more than the token's shortfall none is repayable, theirs included, and
/// where a pair past its cap sits at a lender that refuses repays no caller places the free custody: the
/// curator's emergency repay (`FLAMM.emergency`) is the way out of both.
/// - On a custody-blind pool, whose gate reads no custody, a repay at any pair only lowers what it reads: the
/// buffer's guard sets what it repays (`FLAMMBlindLib.repayable`), as at {flush}, but for a token with two
/// or more live pairs the room's priced read runs first (`FLAMMLane.flushPairRoom`): its refusal refuses the
/// flush, and its figure does not bound the repay.
function flushPair(uint8 a, uint8 p, bool prove) public returns (uint256 repaid, uint256 lent) {
FLAMMStore.S storage $ = _s();
ReentrancyGuardLib._guard();
FLAMMStore.checkToken($, a);
FLAMMStore.checkPair($, p);
FLAMMStore.PairCfg storage pc = $.pairs[p];
if (pc.debt != a) revert InvalidConfig();
if (!$.noLiveVenue) {
FLAMMGateLib.accrueRead($, 0);
FLAMMGateLib.Book memory b = FLAMMGateLib.bookOf($);
FLAMMGateLib.Leg memory L = b.legs[a];
address token = FLAMMStore.tokenOf($, a);
uint256 own = L.held;
if (own != 0 && L.owed != 0) {
IMMRouter r = $.router;
bool many = L.partner == FLAMMStore.MANY;
uint256 before = FLAMMStore.balanceOfThis(token);
uint256 left = many || FLAMMGateLib.split(b, a)
? Math.min(own, FLAMMLane.flushPairRoom($, a, p, own < L.owed, many))
: own;
// on a custody-blind pool a repay only lowers what the gate reads, at any pair: the buffer's guard
// sets `left` once the room read above has not refused, and a stranger's repay at a venue past its
// trigger runs there
(left,) = _repayable($, b, a, own, left, p);
FLAMMStore.approveRouter($, token, left);
for (uint256 m = pc.venues & ~uint256($.retiredVenues); m != 0 && left != 0; m &= m - 1) {
uint16 id;
for (uint256 k = m; k & 1 == 0; k >>= 1) ++id;
// a venue that owes nothing, or refuses a repay now, is passed over, as the cascade does
(,,,, uint256 debt) = r.venuePosition(address(this), id);
if (debt == 0 || FLAMMGateLib.repayRefused($, id)) continue;
// the grant left, as `FLAMMSettleLib._repayInput` counts it: a venue that takes less than the
// Router pulled returns the rest to custody, where it stays
r.repay(id, left < debt ? left : debt);
left = FLAMMStore.granted($, token);
}
FLAMMStore.revoke($, token);
repaid = before - FLAMMStore.balanceOfThis(token);
own -= repaid;
}
if (prove) _prove($);
if (L.owed == repaid) lent = _lendSurplus($, b, a, token, own);
FLAMMStore.setHeld($, a, FLAMMStore.heldOf($, a) - repaid - lent);
if (FLAMMStore.balanceOfThis(token) < FLAMMStore.heldOf($, a)) revert CustodyMismatch();
emit FlushedPair(a, p, repaid, lent);
}
ReentrancyGuardLib._unlockGuard();
}
/// @dev What a flush repays of token `a` at pair `p`: `pay`, its own rule's, but on a custody-blind pool the
/// buffer's guard (`FLAMMBlindLib.repayable`, whose repays at the venues past their trigger the caller counts
/// by the token's balance), and whether the flush lends nothing of the token: where that guard passed a venue
/// over on anyone else's flush.
function _repayable(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
uint256 a,
uint256 own,
uint256 pay,
uint8 p
) private returns (uint256, bool) {
if (!FLAMMBlindLib.blind($, b)) return (pay, false);
return FLAMMBlindLib.repayable($, a, own, b.legs[a].owed, p);
}
/// @dev A flush's `prove`: the flags a fresh position read shows (`FLAMMGateLib.proveDebtFree`, core's read),
/// and on a pool whose cheap lane is on the pairs' proofs too (`FLAMMLane.proveDebtFree`).
function _prove(FLAMMStore.S storage $) private {
if ($.swapBits & FLAMMStore.SWAP_LANE != 0) FLAMMLane.proveDebtFree($);
else FLAMMGateLib.proveDebtFree($);
}
/// @dev {flush}'s lending of `own`, token `a`'s custody the pool owns after the repay: what it lent.
function _lendSurplus(FLAMMStore.S storage $, FLAMMGateLib.Book memory b, uint8 a, address token, uint256 own)
private
returns (uint256 lent)
{
FLAMMStore.TokenCfg storage c = $.tokens[a];
if (
$.paused || $.features & FLAMMStore.FEATURE_SUPPLY_LENDING == 0 || c.partner == FLAMMStore.NO_PARTNER
|| (a == 0 && $.poolBits & FLAMMStore.POOL_ASSET_LENDS == 0) || FLAMMGateLib.backsDebt(b, a)
) return 0;
// the fee owed past custody stays in custody beside the target: custody covers it before anything is lent
uint256 target = c.reserveTarget + FLAMMGateLib.feeOf(b.legs[a]);
uint256 excess = own > target ? own - target : 0;
if (excess == 0 || excess < c.minSupplyBatch) return 0;
// as a swap's lend, nothing while a venue that would take it reports a loss on its supply
// (`FLAMMKeptLib.lendReportsLoss`): the lend would lower NAV by the loss's share of it, in a call anyone makes
if ($.features & FLAMMStore.LOSS_MARKS != 0 && FLAMMKeptLib.lendReportsLoss(a)) return 0;
// `supplyCascade` is keyed by token: every pair that owes `a` may take it, so each one's venues wake
(uint256 pairs,) = FLAMMStore.lanes($, a);
for (uint256 p; pairs >> p != 0; ++p) {
if ((pairs >> p) & 1 != 0) FLAMMGateLib.wake($, $.pairs[p].venues);
}
uint256 before = FLAMMStore.balanceOfThis(token);
FLAMMStore.approveRouter($, token, excess);
if ($.router.supplyCascade(a, excess) != excess) FLAMMStore.revoke($, token);
lent = before - FLAMMStore.balanceOfThis(token);
}
/// @notice On a custody-blind pool (`FLAMMStore.CUSTODY_BLIND`), the keeper's or the curator's refill of the buffer
/// of the cheap lane, under the lock (its body `FLAMMBlindLib.refillBuffer`): borrows `amounts[i]` at venue
/// `venueIds[i]` into custody, each venue's debt token, in one call that reads the venues and the prices
/// once for all of its draws, posting at most `maxPost` of their one collateral token out of the custody
/// the pool owns, as each pin needs and as each indebted venue past its trigger, and the law per token,
/// need after them; refused where the pool asset's custody the pool owns sits under its idle floor after
/// the post ({setIdleFloor}), and where the custody it leaves of a drawn token passes the token's reserve
/// target, the buffer's guard. A venue whose collateral already covers its draw at its pin takes no post: a
/// keeper may post ahead with `maintain`'s top-up so its refills only borrow, as far as the idle custody
/// stays at or over the floor. Not permissionless: a borrow adds debt and its interest, and posts what the
/// cheap lane's other side pays from, the desk's inventory choice. The flows after it move custody alone: a
/// bid pays out the stable already borrowed, an ask pays out idle collateral, never what is posted, and no
/// cheap fill changes a loan. Returns what it posted.
/// @dev What `maxPost` zero means. With the local refill off ({setLocalRefill}), as at birth: a whole refill
/// that may post nothing, so it refuses wherever any venue or the law needs a post. With it on: a local
/// refill, held to the venues it draws at alone. It keeps every check on them and posts nothing; it reads no
/// other venue, so it neither refuses nor posts for one past its trigger and does not prove the law per
/// token over them; it runs only within the window of the last whole refill, one with `maxPost` over zero,
/// the one call that renews it, and refuses past it (`Expired`, which a refill raises nowhere else). A
/// caller that wants every venue read sends `maxPost` of one or more, which may post up to that much. The
/// rules in full are `FLAMMBlindLib.refillBuffer`'s.
function refill(uint16[] calldata venueIds, uint256[] calldata amounts, uint256 maxPost)
public
returns (uint256 posted)
{
FLAMMStore.S storage $ = _s();
FLAMMStore.requireKeeperOrCurator($, false);
ReentrancyGuardLib._guard();
posted = FLAMMBlindLib.refillBuffer($, venueIds, amounts, maxPost);
ReentrancyGuardLib._unlockGuard();
}
// ------------------------------------------------------------------ the curator's fee
/// @notice The curator or the guardian drops the curator's scheduled rise of its performance fee.
function cancelPerformanceFee() public {
FLAMMStore.S storage $ = _s();
FLAMMStore.curatorOrGuardian($);
ReentrancyGuardLib._guard();
if ($.performanceFeeExecutableAt == 0) revert NoPerformanceFeeScheduled();
($.pendingPerformanceFeeBp, $.performanceFeeExecutableAt) = (0, 0);
emit PerformanceFeeCancelled(msg.sender);
ReentrancyGuardLib._unlockGuard();
}
// ------------------------------------------------------------------ the operator's share
/// @notice The curator's share for the pool's operator (the role `src/propamm` calls the operator) of each fill, bp
/// of what the fill's fee (a hook-priced fill's) or edge (a cheap fill's) leaves past the protocol's part,
/// at most `FLAMMStore.MAX_OPERATOR_SHARE_BP`; zero, the default, turns it off. A cover, a hook-priced fill
/// whose input the pool owes, pays no share: its fee past the part stays with the LPs. A cut, or the
/// current rate, applies at once and clears a scheduled rise, which the curator or the guardian may also
/// drop on its own ({cancelOperatorShare}); a rise is scheduled for the pool's delay (`governanceDelaySec`)
/// from now, replacing one already scheduled, and anyone applies it then ({executeOperatorShare}). A due
/// rise lapses past its window, as other due changes do. A change applies to
/// later fills only and moves no value.
/// @dev - Each hook-priced fill but a cover books the share beside the protocol's part (`FLAMMSwapLib.validate`,
/// `FLAMMLane.post`), in kind in the token paid, out of the pool's own custody into the owed record, which
/// every reader keeps out of the pool's own: NAV, the curator's fee mark and the performance fee with it,
/// the credit law, and a token's fence, which holds it with the protocol's fee. The taker's price is the
/// hook's: the share comes out of the fee it charged. {collectOperatorFee} pays it to the
/// core's fee receiver, after the protocol's part.
/// - On a pool whose cheap lane is on, each cheap fill books it too, on every pair, in the pair's quote, the
/// desk's edge its base (`FLAMMLane.cheapShare`). The credit path's swaps, the swap hook's own pricing
/// there, book it as hook-priced fills, in the token paid (a bid's in the quote, an ask's in the base), none
/// on a cover: the front reports the same base, the desk's edge capped at the band of the quote leg, as the
/// fill's fee, and its rate of the gross, within the curator's cap, as the fill's rate (`PropAMMFront`). A
/// pair hook's swaps take it as on any pool.
/// - A swap hook that keeps its own legs (`EverlongHook`) takes the share out of them at the rate the request
/// carries (`FLAMMSwapLib.requestAt`), at least what core books, as it sees none of core's cuts past the
/// room.
function setOperatorShareBp(uint16 shareBp) public {
FLAMMStore.S storage $ = FLAMMStore.s();
FLAMMStore.requireCurator($);
ReentrancyGuardLib._guard();
if (shareBp > FLAMMStore.MAX_OPERATOR_SHARE_BP) revert InvalidConfig();
if (shareBp <= uint16($.operatorShare)) {
_setShare($, shareBp);
} else {
uint48 due = uint48(block.timestamp + $.governanceDelaySec);
($.pendingOperatorShareBp, $.operatorShareExecutableAt) = (shareBp, due);
emit OperatorShareScheduled(shareBp, due);
}
ReentrancyGuardLib._unlockGuard();
}
/// @notice Applies the curator's scheduled rise of the operator's share once the pool's delay has passed;
/// permissionless. Reverts `HookSetNotReady` before then, as an early admission does, and
/// `NoOperatorShareScheduled` past its window (`FLAMMStore.executionWindow`), where it lapses as other due
/// changes do and the curator schedules it again.
function executeOperatorShare() public {
FLAMMStore.S storage $ = FLAMMStore.s();
ReentrancyGuardLib._guard();
uint48 due = $.operatorShareExecutableAt;
if (due == 0 || block.timestamp > due + FLAMMStore.executionWindow($.governanceDelaySec)) {
revert NoOperatorShareScheduled();
}
if (block.timestamp < due) revert HookSetNotReady();
_setShare($, $.pendingOperatorShareBp);
ReentrancyGuardLib._unlockGuard();
}
/// @notice The curator or the guardian drops the scheduled rise of the operator's share.
function cancelOperatorShare() public {
FLAMMStore.S storage $ = FLAMMStore.s();
FLAMMStore.curatorOrGuardian($);
ReentrancyGuardLib._guard();
if ($.operatorShareExecutableAt == 0) revert NoOperatorShareScheduled();
($.pendingOperatorShareBp, $.operatorShareExecutableAt) = (0, 0);
emit OperatorShareCancelled(msg.sender);
ReentrancyGuardLib._unlockGuard();
}
/// @dev Writes the operator's share `shareBp` into its word, clears any scheduled rise, and sets
/// `FLAMMStore.OPERATOR_SHARE` exactly where it is nonzero.
function _setShare(FLAMMStore.S storage $, uint16 shareBp) private {
$.operatorShare = ($.operatorShare & ~uint256(0xffff)) | shareBp;
($.pendingOperatorShareBp, $.operatorShareExecutableAt) = (0, 0);
uint16 f = $.features;
uint16 bit = uint16(FLAMMStore.OPERATOR_SHARE);
$.features = shareBp != 0 ? f | bit : f & ~bit;
emit OperatorShareSet(shareBp);
}
/// @notice The operator's share of each fill, bp ({setOperatorShareBp}), and its scheduled rise and when anyone
/// may apply it (zero when none, or past its window, where it has lapsed: {executeOperatorShare}).
function operatorShare() public view returns (uint16 shareBp, uint16 pendingBp, uint48 executableAt) {
FLAMMStore.S storage $ = FLAMMStore.s();
(shareBp, pendingBp, executableAt) =
(uint16($.operatorShare), $.pendingOperatorShareBp, $.operatorShareExecutableAt);
if (block.timestamp > executableAt + FLAMMStore.executionWindow($.governanceDelaySec)) {
(pendingBp, executableAt) = (0, 0);
}
}
/// @notice The basket's first two entries: zero while the curator's fee mark is the pool asset's ({basketTokens}
/// gives every token's).
function basket() public view returns (uint128 basketPool, uint128 basketLoan) {
FLAMMStore.S storage $ = _s();
return ($.basketPool, $.basketLoan);
}
/// @notice The deposit basket per 1e18 shares, one entry per listed token in its base units: the pool asset's
/// (`basketPool`), token 1's (`basketLoan`) and each later token's (`S.basketTok`); all zero while the
/// curator's fee mark is the pool asset's. The fee mark is NAV per share against the value of every entry.
function basketTokens() public view returns (uint256[] memory e) {
FLAMMStore.S storage $ = _s();
uint256 n = $.tokenCount;
e = new uint256[](n);
if ($.basketPool == 0) return e;
(e[0], e[1]) = ($.basketPool, $.basketLoan);
for (uint256 t = 2; t < n; ++t) {
e[t] = $.basketTok[t];
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {
"src/core/mm/MMRouterLib.sol": {
"MMRouterLib": "0x95b386d242c061ab2551a0d294c94dfe3948ef2c"
},
"src/core/flamm/FLAMMLane.sol": {
"FLAMMLane": "0x5d81d4a7cfd40c3dfe9e009212545608be90de37"
},
"src/core/flamm/FLAMMRoute.sol": {
"FLAMMRoute": "0xb1ffeae12c53f876aa0e495e9c00c829f47fb0fe"
},
"src/periphery/FLAMMMaxima.sol": {
"FLAMMMaxima": "0x68546ce65986354c5394e4bc2f28027ef490a91b"
},
"src/core/flamm/FLAMMLawLib.sol": {
"FLAMMLawLib": "0xf55c5807b6fbe5555443fd6ddbbd52079849cf45"
},
"src/core/flamm/FLAMMOpsLib.sol": {
"FLAMMOpsLib": "0x0be7fdb3d611b05df90a61778a644654735ecc47"
},
"src/core/mm/AaveV3ReadsLib.sol": {
"AaveV3ReadsLib": "0xa5db415d1af2158dd0a4a3c9c1eada277472803e"
},
"src/core/flamm/FLAMMFlowLib.sol": {
"FLAMMFlowLib": "0x27957f4ddf818de39a1c9dba0bf273a5994cfb77"
},
"src/core/flamm/FLAMMGateLib.sol": {
"FLAMMGateLib": "0x3a05779218510235badcbddcdd78732a16434368"
},
"src/core/flamm/FLAMMKeptLib.sol": {
"FLAMMKeptLib": "0x70cace9076ac8dd6a691ced2f9aa62a5c360bee4"
},
"src/core/mm/CTokenMarketLib.sol": {
"CTokenMarketLib": "0x60e4ab6b6ba72325c58924ee7753b14b37314010"
},
"src/core/flamm/FLAMMAdmitLib.sol": {
"FLAMMAdmitLib": "0x0b107b1f0c64f3716554ccc83b53e492e51ce950"
},
"src/core/flamm/FLAMMBlindLib.sol": {
"FLAMMBlindLib": "0x634d5a14c42fb5bec82a7aea32bf636a8d298fcd"
},
"src/core/flamm/FLAMMClaimLib.sol": {
"FLAMMClaimLib": "0x5dc3bb30c60390ce9522b7e3ca315dd334aa7e91"
},
"src/core/flamm/FLAMMFenceLib.sol": {
"FLAMMFenceLib": "0x9dbba0cbd9d7883f4eedd1c8e08780fac4798f1a"
},
"src/core/flamm/FLAMMFloatLib.sol": {
"FLAMMFloatLib": "0x6b2b25ebba12e78afea697b9ac6d2167a6518935"
},
"src/core/flamm/FLAMMQuoteLib.sol": {
"FLAMMQuoteLib": "0x99de54a108c64ebe23ac7766901c199a91929869"
},
"src/core/flamm/FLAMMTopUpLib.sol": {
"FLAMMTopUpLib": "0xe4be161081d1c9aa91951ca347cc99da35cfac2e"
},
"src/core/mm/CTokenRewardsLib.sol": {
"CTokenRewardsLib": "0x93ab647215a9f9f1050302a76506afcbc0262861"
},
"src/core/mm/MMRouterAdminLib.sol": {
"MMRouterAdminLib": "0x6abb06b1e9cba80888992d366913bb9b7760ea7e"
},
"src/core/flamm/FLAMMPolicyLib.sol": {
"FLAMMPolicyLib": "0x3858e2202cebcb6f12f36a596260dd2ed8f91f06"
},
"src/core/flamm/FLAMMSettleLib.sol": {
"FLAMMSettleLib": "0x4551cddb1de95f5452f6a0f836e047e01833b301"
},
"src/core/flamm/FLAMMSharedLib.sol": {
"FLAMMSharedLib": "0xb852d9cbdda85cbed7da0885bca2714ba1b71005"
},
"src/periphery/FLAMMExitMaxima.sol": {
"FLAMMExitMaxima": "0x6a6a3ff1e834dbbf07dee472e07d1ca977798659"
},
"src/hooks/everlong/LeverageLib.sol": {
"LeverageLib": "0x80396f9f894cc3060dfaa7468c4f576e8b16d055"
},
"src/core/flamm/FLAMMMaintainLib.sol": {
"FLAMMMaintainLib": "0xaa5434e13eb54f37c577229efc981cceceb56417"
},
"src/core/flamm/FLAMMPairQuoteLib.sol": {
"FLAMMPairQuoteLib": "0x3bc57bc05cc9dd1fe18106add8ffc060882055dd"
},
"src/hooks/everlong/EverlongOpsLib.sol": {
"EverlongOpsLib": "0xf6d56f4ed6a7c441fd96c53a327026bac19dfeef"
}
},
"optimizer": {
"runs": 100,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.