Verified contractExactUNLICENSED
FLAMMFloatLib
Address0x539efc2b17cf0fdf254aaab925b3a7c360a79737
- 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,396,528
- Creation transaction
- 0x2c5f313e9e…175293cd5f
- Libraries
- src/core/mm/MMRouterLib.sol:MMRouterLib0xa474…d2b4e5src/core/flamm/FLAMMLane.sol:FLAMMLane0x0988…d22e98src/core/flamm/FLAMMRoute.sol:FLAMMRoute0x312e…0fdaa9src/periphery/FLAMMMaxima.sol:FLAMMMaxima0x4a99…d6259csrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0x5d47…27cc62src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x0bfe…043753src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xd53f…ed5983src/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0x2577…4e3473src/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0xf0be…2b9555src/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x7a11…58517bsrc/core/mm/CTokenMarketLib.sol:CTokenMarketLib0x18c5…b2071csrc/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0xa6db…bdcbcbsrc/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x0b8d…2e7e5csrc/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0x02b4…731ccesrc/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0xa16d…a201e8src/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0x539e…a79737src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0xa4d3…d5ce2esrc/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0x7c55…d233dfsrc/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0xcda6…a4dcf7src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x8423…7adc96src/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0xa6b4…0c67f9src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0xb489…d3c7cbsrc/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xfaae…2511basrc/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x480f…4e0a81src/hooks/everlong/LeverageLib.sol:LeverageLib0x1b1d…40ad11src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0x9499…409cc2src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0x0775…d94cbesrc/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xabe4…7426f7
52 files
The source code is large: one file is shown at a time. Choose a file in the list.
- src/core/flamm/FLAMMFloatLib.solmain57.91 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.sol54.32 KB
- src/core/flamm/FLAMMAdmitLib.sol37.26 KB
- src/core/flamm/FLAMMBlindLib.sol41.3 KB
- src/core/flamm/FLAMMClaimLib.sol49.42 KB
- src/core/flamm/FLAMMClaimVault.sol1.65 KB
- src/core/flamm/FLAMMFenceLib.sol72.83 KB
- src/core/flamm/FLAMMFlowLib.sol55.24 KB
- src/core/flamm/FLAMMGateLib.sol87.39 KB
- src/core/flamm/FLAMMKeptLib.sol45.59 KB
- src/core/flamm/FLAMMLane.sol70.27 KB
- src/core/flamm/FLAMMLawLib.sol60.67 KB
- src/core/flamm/FLAMMMaintainLib.sol41.67 KB
- src/core/flamm/FLAMMOpsLib.sol32.2 KB
- src/core/flamm/FLAMMPolicyLib.sol39.49 KB
- src/core/flamm/FLAMMQuoteLib.sol16.89 KB
- src/core/flamm/FLAMMRoute.sol16.45 KB
- src/core/flamm/FLAMMSettleLib.sol42.92 KB
- src/core/flamm/FLAMMSharedLib.sol13.11 KB
- src/core/flamm/FLAMMStore.sol135.42 KB
- src/core/flamm/FLAMMSwapLib.sol55.65 KB
- src/core/flamm/FLAMMTopUpLib.sol48.97 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.sol2.99 KB
- src/interfaces/core/mm/IFinancingAccount.sol46.04 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 for good: the pool then starts a debt only through {refill}, the keeper's or the
/// curator's, and 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 stays off
/// (`InvalidConfig`): its law is not the one the swap's plan sizes.
function setCreditPath(bool on) public {
FLAMMStore.S storage $ = _s();
_gate($, !on);
if (on && $.features & FLAMMStore.CUSTODY_BLIND != 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 _s().idleFloor;
}
/// @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 does not, 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 (`FLAMMBlindLib.repayable`).
/// 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.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);
pay = _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 alone sets what it repays (`FLAMMBlindLib.repayable`), as at {flush}, but for a token with
/// two or more live pairs the room is read first (`FLAMMLane.flushPairRoom`), and a refusal of its priced
/// read refuses the flush.
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.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
// alone sets `left`, the room read above can only refuse, 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;
left -= r.repay(id, left < debt ? left : debt);
}
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).
function _repayable(
FLAMMStore.S storage $,
FLAMMGateLib.Book memory b,
uint256 a,
uint256 own,
uint256 pay,
uint8 p
) private returns (uint256) {
if (!FLAMMBlindLib.blind($, b)) return pay;
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.
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 does not lapse: it stays scheduled until executed, cut, cancelled or replaced. 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.
function executeOperatorShare() public {
FLAMMStore.S storage $ = FLAMMStore.s();
ReentrancyGuardLib._guard();
uint48 due = $.operatorShareExecutableAt;
if (due == 0) 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).
function operatorShare() public view returns (uint16 shareBp, uint16 pendingBp, uint48 executableAt) {
FLAMMStore.S storage $ = FLAMMStore.s();
return (uint16($.operatorShare), $.pendingOperatorShareBp, $.operatorShareExecutableAt);
}
/// @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": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"src/core/mm/MMRouterLib.sol": {
"MMRouterLib": "0xA4749766934833DfBeaF4Fc0d79c150A1Dd2B4E5"
},
"src/core/flamm/FLAMMLane.sol": {
"FLAMMLane": "0x0988077AB06F1efd8cFa3f08FC60CAf3e6d22e98"
},
"src/core/flamm/FLAMMRoute.sol": {
"FLAMMRoute": "0x312ee92ecd113F925dD513d450b062C8740fDaA9"
},
"src/periphery/FLAMMMaxima.sol": {
"FLAMMMaxima": "0x4A997343D91c981BF63274fc222AA96D32d6259c"
},
"src/core/flamm/FLAMMLawLib.sol": {
"FLAMMLawLib": "0x5D473B15E032756Cd81fc66B8F1e9BE2f427cc62"
},
"src/core/flamm/FLAMMOpsLib.sol": {
"FLAMMOpsLib": "0x0BFe60fB1f5223F1A2b7B02Ef18f5C33fb043753"
},
"src/core/mm/AaveV3ReadsLib.sol": {
"AaveV3ReadsLib": "0xD53F6170226A74D453e84414Ffc2FFcE5ded5983"
},
"src/core/flamm/FLAMMFlowLib.sol": {
"FLAMMFlowLib": "0x2577D707D41209489b2EF53101a4f6baDd4E3473"
},
"src/core/flamm/FLAMMGateLib.sol": {
"FLAMMGateLib": "0xF0BE115A2D6F27274F2e9EE50B89Ed42db2B9555"
},
"src/core/flamm/FLAMMKeptLib.sol": {
"FLAMMKeptLib": "0x7a11899232dd9F17c28bF062Ec2ee2267158517b"
},
"src/core/mm/CTokenMarketLib.sol": {
"CTokenMarketLib": "0x18c53F2aCAbcDEEdb575A136f49fa4C43EB2071c"
},
"src/core/flamm/FLAMMAdmitLib.sol": {
"FLAMMAdmitLib": "0xA6dBD8cD5Cd10F8a5857cbeD54a28405ffbDcBCb"
},
"src/core/flamm/FLAMMBlindLib.sol": {
"FLAMMBlindLib": "0x0b8d436F1a7AE25C5d16955ed4CDa781E42e7E5C"
},
"src/core/flamm/FLAMMClaimLib.sol": {
"FLAMMClaimLib": "0x02b4354a56630ab165A880B1198a603E62731cCE"
},
"src/core/flamm/FLAMMFenceLib.sol": {
"FLAMMFenceLib": "0xA16ddA83f47a42F875f141b6954595D584a201e8"
},
"src/core/flamm/FLAMMFloatLib.sol": {
"FLAMMFloatLib": "0x539EfC2b17cF0fdF254AAaB925b3A7c360A79737"
},
"src/core/flamm/FLAMMQuoteLib.sol": {
"FLAMMQuoteLib": "0xa4D34f4882a529574840881e755BCFae2bd5ce2e"
},
"src/core/flamm/FLAMMTopUpLib.sol": {
"FLAMMTopUpLib": "0x7C55a535Ce298b1e5e6d00F645088F777ad233DF"
},
"src/core/mm/CTokenRewardsLib.sol": {
"CTokenRewardsLib": "0xcda63d7eCCF838F2732Bff676706BDE5abA4DcF7"
},
"src/core/mm/MMRouterAdminLib.sol": {
"MMRouterAdminLib": "0x8423744b3F304ED0B43043d7ad4E7d8A247aDc96"
},
"src/core/flamm/FLAMMPolicyLib.sol": {
"FLAMMPolicyLib": "0xa6B495B2BdcDcf4F327844d9aaA0eD4C550c67F9"
},
"src/core/flamm/FLAMMSettleLib.sol": {
"FLAMMSettleLib": "0xB4890a27205505BDAA05717B6c3aB38b2dd3C7Cb"
},
"src/core/flamm/FLAMMSharedLib.sol": {
"FLAMMSharedLib": "0xFaAEd38962aEb6c282Ac36E0cdE9313AbA2511ba"
},
"src/periphery/FLAMMExitMaxima.sol": {
"FLAMMExitMaxima": "0x480f51866554e92649c9d3502bA31AA4234e0a81"
},
"src/hooks/everlong/LeverageLib.sol": {
"LeverageLib": "0x1B1D1C42d26c169dB59D8681d0FD4C9a2840Ad11"
},
"src/core/flamm/FLAMMMaintainLib.sol": {
"FLAMMMaintainLib": "0x94998f13fc5d5D2271c90b835c6a805dad409cC2"
},
"src/core/flamm/FLAMMPairQuoteLib.sol": {
"FLAMMPairQuoteLib": "0x077523D1427aE408105fe8592F907ECDa0D94cbE"
},
"src/hooks/everlong/EverlongOpsLib.sol": {
"EverlongOpsLib": "0xAbe4447C954E3C7a405f8E75116BF9f5787426F7"
}
},
"optimizer": {
"runs": 100,
"enabled": true
},
"viaSSACFG": false,
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
"solady/=lib/solady/src/",
"forge-std/=lib/forge-std/src/"
],
"experimental": false
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.