Verified contractExactUNLICENSED
FLAMMLane
Address0x0988077ab06f1efd8cfa3f08fc60caf3e6d22e98
- 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,543
- Creation transaction
- 0x5ac27032f5…625acc017f
- 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/FLAMMLane.solmain70.27 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/FLAMMFloatLib.sol57.91 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/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/FLAMMLane.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {
FLAMMStore, Paused, FeatureDisabled, OutputAboveCeiling, CustodyMismatch, PairNotTradable, NotFront, OutflowCap,
NotDebtFree, NotionalCap, CreditPathOff, HookSetNotReady, AdmissionScheduled, AdmissionCancelled, NotCurator,
NotGuardianOrCurator, GuardianPauseStands, HookPairsSynced, LanePairsSet, InvalidConfig, GuardianMayOnlyTighten,
PairHookSet, TradePairsSet, InvalidAmount
} from "src/core/flamm/FLAMMStore.sol";
import {FLAMMAdmitLib} from "src/core/flamm/FLAMMAdmitLib.sol";
import {FLAMMGateLib} from "src/core/flamm/FLAMMGateLib.sol";
import {FLAMMLawLib} from "src/core/flamm/FLAMMLawLib.sol";
import {FLAMMRoute} from "src/core/flamm/FLAMMRoute.sol";
import {FLAMMOpsLib} from "src/core/flamm/FLAMMOpsLib.sol";
import {HOOK_CAP_PAIR_HOOK} from "src/interfaces/core/flamm/IHookCapabilities.sol";
import {IPairHook, PAIR_MODE_COVER, PAIR_MODE_ROTATE} from "src/interfaces/core/flamm/IPairHook.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ReentrancyGuardLib} from "src/libraries/ReentrancyGuardLib.sol";
import {PropAMMLaneLib} from "src/propamm/libraries/PropAMMLaneLib.sol";
/// @dev Error words, as the front encodes them: a selector, an argument (bits 32-39), bit 40 where it takes one. The
/// cheap lane's predicates on every pair (`FLAMMLane`, `FLAMMRoute`) build and raise them.
uint256 constant HAS_ARG = 1 << 40;
/// @dev The error word of `sel`, which takes no argument.
function _e(bytes4 sel) pure returns (uint256) {
return uint256(uint32(sel));
}
/// @dev The error word of `sel` with its argument `arg`.
function _eArg(bytes4 sel, uint256 arg) pure returns (uint256) {
return uint256(uint32(sel)) | (arg << 32) | HAS_ARG;
}
/// @dev Reverts with the error word's typed error.
function _fail(uint256 e) pure {
assembly ("memory-safe") {
mstore(0, shl(224, and(e, 0xffffffff)))
if iszero(shr(40, e)) { revert(0, 4) }
mstore(4, and(shr(32, e), 0xff))
revert(0, 36)
}
}
/// @notice The cheap lane: a fill its front prices (a maker-signed ladder, held by the listing's price fence where it
/// has one) settled from tracked custody, never touching the lender, on a pool whose front initialised the
/// cheap lane at birth (`FLAMMFloatLib.initLane`) and whose curator set `FEATURE_CHEAP_FILL`. A bid pays token
/// 1 for the pool asset, an ask the pool asset for token 1.
/// @dev One predicate serves the fill and the view the front plans with (`IFLAMMLane.laneStateOf`), so a quote never
/// promises what the pool would refuse:
/// - the cheap-fill bit, the cheap lane's birth bit (`FLAMMStore.SWAP_LANE`), the side's feature bit and the hook
/// pair in both trade masks (any closing of the pair, a token's delisting included, closes the cheap lane);
/// - a bid: the pool unpaused and token 1 proven debt-free (a pool with no band holds no debt); an ask: every
/// other token that some live pair owes proven debt-free, token 1 too in strict mode; a token no live pair owes
/// is passed over, which skips a delisted one;
/// - on a pool whose pairs make it two-sided, the rule of every fill past the hook pair in place of that one
/// ({pays}, with no exception for the input): the cheap lane reads no price, so it pays nothing that backs or
/// nets a debt;
/// - on a custody-blind pool (`FLAMMStore.CUSTODY_BLIND`) outside strict mode no debt rule at all ({_side} skips
/// it), as its gate reads no custody and a fill moves nothing else; strict mode keeps the two-sided rule there;
/// and, strict mode or not, the pool unpaused on both sides;
/// - the payout within the out token's custody less the spread fee owed in it, which stays reserved there
/// (`FLAMMStore.feeOwed`: in token 1 the accrual in `laneWord` alone, as a cheap-lane pool owes token 1's fee
/// nowhere else; in the pool asset the hook fills' record, read only while some fee is recorded);
/// - token 1's notional cap on the quote leg, net of the room the pair's notional floor needs beside a payout
/// under it (`FLAMMStore.reservedCap`; zero: none), read from its mirror in `laneConfig`
/// (`FLAMMStore.LANE_NOTIONAL_SHIFT`), as token 1's bucket unit is (`LANE_UNIT_SHIFT`);
/// - the side's outflow bucket: per side, a level in the out token's 1e-6 units (10^max(0, decimals - 6) base
/// units) that refills at its rate up to its burst (`laneConfig`, `FLAMMFloatLib.setOutflowCaps`), debited by
/// each payout rounded up, on both paths: the pool's own swap of the hook pair (the credit path, priced through
/// the same front) debits the same bucket ({book}), and its plan folds the side's room into the hook's ceiling
/// ({ceilingOf}), so no front, however it prices, pays faster than the caps.
///
/// A fill writes two pool words, the custody word and `laneWord`: the bucket's debit and the spread fee it accrues
/// (the pool's spread rate of the fill's edge against its fee price, `pullPrice36`, bounded by the fill itself, at
/// least the pair's notional rate of its token-1 leg (`FLAMMStore.notional`), and within the custody it leaves
/// ({boundFee}), in token 1, owed to the protocol and paid in kind by `FLAMMFloatLib.collectSpreadFee`). Where
/// the pool sets an operator's share (`FLAMMStore.OPERATOR_SHARE`), the fill accrues the share beside the part
/// ({cheapShare}, the desk's edge its base) and writes the operator's counter, a third word.
///
/// A pair past the hook pair settles on the cheap lane through `FLAMMRoute`, under the same rules per token: each
/// token from 2 on has its own outflow bucket (`S.laneTok`), and the pool's own swap of any pair the front prices
/// folds and debits the bucket of the token it pays.
///
/// `FLAMMFront` compiles the hook pair's fill and its view in. The rest is public, a linked library the pool's own
/// code delegates to with its storage as an argument, so no other caller reaches it (no fallback routes here): the
/// credit path's half, whose ceiling the swap's plan asks on a cheap-lane pool alone and whose fee booking its
/// settlement calls ({post}), a cheap-lane pool's rules on the curator's caps, its fee mark and its two pauses,
/// and any other pool's rule on a cut of its fee floors ({scheduledCut}), out of the hot libraries, whose entries
/// a new one would make dearer to reach.
library FLAMMLane {
/// @dev The pair hook's key in the pending table and `capRaises`: `FLAMMFloatLib.setPairHook`'s selector, the
/// entry's own, so a scheduled call reads as the curator made it.
bytes4 private constant SET_PAIR_HOOK = bytes4(keccak256("setPairHook(address,uint256)"));
// ------------------------------------------------------------------ the fill
/// @notice `IFLAMMLane.fillFromFront`: checks the caller (the pool's front, its swap hook), the lock, the side's
/// predicate, the input received (`balanceOf` at least tracked custody plus `amountIn`, exactly `amountIn`
/// credited), the notional cap net of the floor's room as {stateOf} reads it, and the bucket; then writes
/// `laneWord` and the custody word (and, where the pool sets an operator's share, books it beside the part,
/// {cheapShare}), pays `recipient`, neither zero nor the pool ({payOut}), and reconciles the out token. It
/// logs nothing itself: the front's `PoolFill` records the fill, with the part it booked and its recipient;
/// the share is in no log.
function fill(
FLAMMStore.S storage $,
bool bid,
uint256 amountIn,
uint256 amountOut,
address recipient,
uint256 pullPrice36
) internal returns (uint256 spreadFee) {
if (msg.sender != $.invariantHook) revert NotFront();
ReentrancyGuardLib._guard();
FLAMMStore.TokenCfg storage c1 = $.tokens[1];
(uint256 h0, uint256 h1, uint256 lane) = ($.held0, $.held1, $.laneWord);
uint256 rate;
{
uint256 err;
uint256 cash;
(err, cash, rate) = _side(c1, bid, lane, h0, h1);
if (err != 0) _fail(err);
if (amountOut > cash) revert OutputAboveCeiling();
// the protocol's part ({boundFee}) at token 1's band of the fill's token-1 leg (a bid's payout, an ask's
// input), within the custody of token 1 the fill leaves beside the fee already owed in it, the accrual in
// `laneWord`, which the bucket's refill and debit below leave as it is
uint256 bp = $.spreadFeeBp;
spreadFee = boundFee(
PropAMMLaneLib.spreadFee(bid, amountIn, amountOut, pullPrice36, bp * 100),
bid ? amountOut : amountIn,
c1.swapPriceBandWad,
bp,
bid,
rate,
_less(bid ? h1 - amountOut : h1 + amountIn, lane & FLAMMStore.LANE_ACCRUED_MASK)
);
}
// the features beside the pool asset, one word
(address t0, address t1, uint256 f) = ($.poolAsset, c1.token, $.features);
if (FLAMMStore.balanceOfThis(bid ? t0 : t1) < (bid ? h0 : h1) + amountIn) revert CustodyMismatch();
{
// token 1's cap and unit from their mirror in `laneConfig`, which the refill reads anyway
uint256 cfg = $.laneConfig;
uint256 cap = FLAMMStore.reservedCap(cfg >> FLAMMStore.LANE_NOTIONAL_SHIFT, rate);
if (cap != 0 && (bid ? amountOut : amountIn) > cap) revert NotionalCap();
lane = refill(lane, cfg);
lane = _debit(lane, bid, amountOut, bid ? _unit1(cfg) : unitOf($.shareScale));
}
// the operator's share past the part, where the pool sets one, accrued with it in token 1
if (f & FLAMMStore.OPERATOR_SHARE != 0) {
lane = _accrue(
lane,
FLAMMRoute.laneShare(
bid,
amountIn,
amountOut,
pullPrice36,
spreadFee,
_less(bid ? h1 - amountOut : h1 + amountIn, lane & FLAMMStore.LANE_ACCRUED_MASK)
)
);
}
if (spreadFee != 0) lane = _accrue(lane, spreadFee);
$.laneWord = lane;
// the payout is at most `cash` (`OutputAboveCeiling`), itself at most the out token's custody, so neither
// difference wraps, and the input's sum already ran checked in the custody check (`CustodyMismatch`)
unchecked {
(h0, h1) = bid ? (h0 + amountIn, h1 - amountOut) : (h0 - amountOut, h1 + amountIn);
}
FLAMMStore.setCustody($, h0, h1);
payOut(bid ? t1 : t0, recipient, amountOut, bid ? h1 : h0);
}
/// @notice The protocol's part `fee` of a fill whose leg in the token the part is owed in is `leg`, a fill's edge
/// or what its hook reported, bounded by the fill itself, so no price a front passes and no hook's report
/// books more than the fill could owe; the three fills share it (the cheap lane's on the hook pair, {fill},
/// and past it, `FLAMMRoute.fillFromFront`, and the hook-priced swap's, `FLAMMSwapLib.validate`):
/// - at most the spread rate `bp` of the pair's band `band` of the leg, never under the least fee band
/// (`FLAMMStore.feeBound`): a band a pool role narrows, or a pool with none, leaves the protocol at least
/// that;
/// - on a cheap bid, at most `leg * bp / (1e4 - bp)`, the bound the hook-priced swap refuses past
/// (`FeeOutOfBounds`, which passes `bid` false); an ask's is at most `bp` of its input, as its edge is at
/// most the input;
/// - at least the notional part of the leg at the pair's notional rate `rate` (`FLAMMStore.notional`),
/// which reads no price, so no edge, pull price or report writes it away;
/// - at most `room`, what holds it beside the payout, so every fee booked is held: the protocol forgoes the
/// rest.
/// None of these moves a payout or a room, so each fill and its view still agree. No product overflows: a
/// leg is within custody's 128 bits or a ceiling, the band within 64 and the rates within 16.
function boundFee(uint256 fee, uint256 leg, uint256 band, uint256 bp, bool bid, uint256 rate, uint256 room)
internal
pure
returns (uint256)
{
if (fee != 0) {
uint256 most = FLAMMStore.feeBound(leg, band, bp);
if (fee > most) fee = most;
if (bid) {
most = leg * bp / (1e4 - bp);
if (fee > most) fee = most;
}
}
uint256 n = FLAMMStore.notional(leg, rate);
if (n > fee) fee = n;
return fee > room ? room : fee;
}
/// @notice The operator's share of a hook-priced fill (`FLAMMSwapLib.validate`) on a pool that sets one
/// (`FLAMMStore.OPERATOR_SHARE`), native units of the token paid: the share's rate
/// (`FLAMMStore.S.operatorShare`, bp) of what the fill's fee `feeOut` leaves past the protocol's part, read
/// after {boundFee}, cut to what the part leaves of its room, to the room left in the operator's counter of
/// the token paid (`FLAMMStore.shareRoom`), so {post} counts all it books, and to what fits beside the part
/// under 2^128; zero on a cover (`PAIR_MODE_COVER` in `mode`), which pays none, and where the fee does not
/// pass the part. `kept` is the custody the plan keeps (`FLAMMSwapLib.Plan.keep`): a rotation's in its low
/// 128 bits, the part above them. `mode` holds the fill's pair mode in bits 0-15, the token paid's index in
/// bits 16-23, the pair's notional rate in bits 24-39 and the fill's rate (`PairFill.feeWad`) from bit 40.
/// @dev - The fee counts at most the fill's own rate, `net * feeWad / (1e18 - feeWad)`: the fee at that rate of
/// a gross of the net `net` plus it. No fee a hook reports past the rate it filled at lifts the share, at
/// any cap of the curator's, and a rate of the whole gross, which leaves no net, counts none.
/// - The part's room is what the net leaves under the ceiling `ceiling` with its notional floor at the pair's
/// notional rate, as `FLAMMSwapLib.validate` reads the part's. Where a live pair owes the token paid, at
/// most `1 - ltv * phiWad` of that room, at the highest `ltv * phiWad` of the pairs that owe it ({_credit}):
/// a payout room that credits the input (`FLAMMGateLib.roomOf`: a unit of the net backed by `phi` of a unit
/// of input at the pair's LTV, `phi` at most the pair's `phiWad`) leaves the law that share of what the net
/// leaves of it as slack, which the share, bringing no input, takes alone. The cut reads neither the input
/// nor whether the payout raises a debt, so it may take less than the law leaves, never more.
/// - On a rotation (`PAIR_MODE_ROTATE`), at most what the output's custody leaves past the custody the
/// rotation keeps, the net and the part: none where the fill rotates without the share, which never adds
/// to a rotation, as its budget credits the input.
/// The share is never more than its rate of what the fee leaves the LPs past the part, so the LPs keep the
/// rest of it, and the settlement funds the two together with the payout: a fill the room, the law and a
/// rotation pass without the share pass with it.
function shareOf(uint256 feeOut, uint256 net, uint256 kept, uint256 ceiling, uint256 mode)
public
view
returns (uint256 op)
{
if (mode & PAIR_MODE_COVER != 0) return 0;
uint256 rate = uint64(mode >> 40);
if (rate >= 1e18) return 0;
uint256 most = Math.mulDiv(net, rate, 1e18 - rate);
if (feeOut > most) feeOut = most;
uint256 pf = kept >> 128;
if (feeOut <= pf) return 0;
FLAMMStore.S storage $ = FLAMMStore.s();
uint256 w = $.operatorShare;
op = Math.mulDiv(feeOut - pf, uint16(w), 1e4);
uint256 room = FLAMMStore.notional(ceiling, uint16(mode >> 24));
// no overflow, as the part's room in `FLAMMSwapLib.validate`: the hook's maximum and its floor are within
// the payout's ceiling, and the net within that maximum
unchecked {
room += ceiling - net;
}
uint256 y = uint8(mode >> 16);
// the law's slack where the room may credit the input: the room less the input's credit at the pairs' LTV
uint256 lp = _credit($, y);
if (lp != 0) room = lp < 1e18 ? Math.mulDiv(room, 1e18 - lp, 1e18) : 0;
if (mode & PAIR_MODE_ROTATE != 0) {
// the custody the rotation leaves the payout, which it rotates past
(uint256 h, uint256 k) = (FLAMMStore.ownHeld($, y), uint128(kept));
uint256 top = h > k ? h - k : 0;
top = top > net ? top - net : 0;
if (top < room) room = top;
}
room = room > pf ? room - pf : 0;
if (op > room) op = room;
uint256 left = FLAMMStore.shareRoom(w, y);
if (op > left) op = left;
left = type(uint128).max - pf;
if (op > left) op = left;
}
/// @dev The highest `ltvWad * phiWad` (WAD) of the live pairs that owe token `t`, which a payout of `t` that draws
/// or raises its debt has its room read at ({shareOf}): the one in its partner cache
/// (`FLAMMStore.TokenCfg.pairId`), every one in its pair mask where two or more owe it (`FLAMMStore.lanes`);
/// zero where none does.
function _credit(FLAMMStore.S storage $, uint256 t) private view returns (uint256 lp) {
FLAMMStore.TokenCfg storage c = $.tokens[t];
uint256 partner = c.partner;
if (partner == FLAMMStore.NO_PARTNER) return 0;
uint256 m;
if (partner == FLAMMStore.MANY) (m,) = FLAMMStore.lanes($, t);
else m = uint256(1) << c.pairId;
while (m != 0) {
FLAMMStore.PairCfg storage pc = $.pairs[Math.log2(m & (~m + 1))];
uint256 v = Math.mulDiv(pc.ltvWad, pc.phiWad, 1e18);
if (v > lp) lp = v;
m &= m - 1;
}
}
/// @notice The operator's share of a cheap fill on a pool that sets one (`FLAMMStore.OPERATOR_SHARE`), on any pair
/// ({fill}, through `FLAMMRoute.laneShare`, and `FLAMMRoute.fillFromFront`): booked in the operator's
/// counter of the quote `q`, the token the fill's part `pf` is owed in (`FLAMMStore.addShare`), and
/// returned, for the caller to owe with the part. The base is the desk's edge, the fill's edge against its
/// fee price `p36` at the whole rate (`PropAMMLaneLib.spreadFee`), read at most the pair's band `band` of
/// the quote leg (a bid's payout, an ask's input), never under `FLAMMStore.MIN_FEE_BAND_WAD`
/// (`FLAMMStore.feeBound` at the whole rate), and at most the curator's cap's rate of the fill's gross
/// (`payout * feeCapWad / (1e18 - feeCapWad)` on a bid, `input * feeCapWad / 1e18` on an ask, below a cap
/// of 1e18), the most a hook fill's own rate reads its fee at ({shareOf}): the share's rate of what the
/// base leaves past the part, none where it does not pass it, so it never takes more than its rate of what
/// the fill earned the LPs past the part. Then at most what the part leaves of `room`, the custody of `q`
/// the fill leaves beside the fee already owed in it, so the pool holds it, and in token 1 of the accrual's
/// field in `laneWord`, which the part's booking refuses past (`OutflowCap`), so the share refuses no fill;
/// then what the counter still holds. What either cut leaves stays with the LPs. It moves no payout and no
/// room: each fill and its view still agree, and the taker's price is the front's.
function cheapShare(
FLAMMStore.S storage $,
bool bid,
uint256 q,
uint256 amountIn,
uint256 amountOut,
uint256 p36,
uint256 band,
uint256 pf,
uint256 room
) internal returns (uint256 op) {
uint256 base = PropAMMLaneLib.spreadFee(bid, amountIn, amountOut, p36, PropAMMLaneLib.PPM);
uint256 most = FLAMMStore.feeBound(bid ? amountOut : amountIn, band, 1e4);
if (base > most) base = most;
uint256 cap = $.feeCapWad;
if (cap < 1e18) {
// no overflow: a leg within custody's 128 bits, the cap within 64
most = bid ? amountOut * cap / (1e18 - cap) : amountIn * cap / 1e18;
if (base > most) base = most;
}
if (base <= pf) return 0;
op = (base - pf) * uint16($.operatorShare) / 1e4;
// the part is within `room` already ({boundFee})
if (op > room - pf) op = room - pf;
if (q == 1) {
uint256 acc = ($.laneWord & FLAMMStore.LANE_ACCRUED_MASK) + pf;
uint256 left = acc < FLAMMStore.LANE_ACCRUED_MASK ? FLAMMStore.LANE_ACCRUED_MASK - acc : 0;
if (op > left) op = left;
}
if (op != 0) op = FLAMMStore.addShare($, q, op);
}
/// @notice A cheap fill's tail, on any pair ({fill}, `FLAMMRoute.fillFromFront`): refuses a `recipient` that is
/// zero or the pool itself (`InvalidAmount`), as the pool's own swap refuses its `to`, so no front's fill
/// pays its output back past custody for the next caller; then pays `amountOut` of `tOut` to `recipient`,
/// reconciles `tOut` against `held`, its custody after the fill (`CustodyMismatch`), and lifts the lock. It
/// logs nothing: the front's `PoolFill` is the fill's record.
function payOut(address tOut, address recipient, uint256 amountOut, uint256 held) internal {
if (recipient == address(0) || recipient == address(this)) revert InvalidAmount();
FLAMMStore.safeTransfer(tOut, recipient, amountOut);
if (FLAMMStore.balanceOfThis(tOut) < held) revert CustodyMismatch();
ReentrancyGuardLib._unlockGuard();
}
/// @notice `IFLAMMLane.laneStateOf` on the hook pair, one side: its room under the fill's predicate and its
/// `maxIn`. All zero while a flow of the pool holds its lock, its custody half-applied.
/// @dev - `room`, zero where the side refuses: the lower of the out token's custody less the fee owed in it and the
/// side's bucket refilled to now, net of the part the pair's notional floor needs beside the payout at the
/// pair's rate (`FLAMMStore.reserved`), as the pool's own swap pays both from the bucket and custody of the
/// token it pays (a bid's custody holds that part already, the cheap fill owing it in token 1), so the room
/// lands on every route of the pair; the cheap fill ({fill}) takes up to the raw room, and one unit past it
/// refuses.
/// - Token 1's notional cap on the side's quote leg, folded into a bid's room (its output) and an ask's
/// `maxIn` (its input), always net of the room the pair's notional floor needs beside a payout under it at
/// the pair's rate (`FLAMMStore.reservedCap`), the side refused or not, as the pool's own swap reads a cap
/// on its payout, so the other side's route may take `maxIn` as its out cap; the fill takes up to the cap
/// net of the floor's room, as `laneStateOf` reports.
/// - Both read token 1's cap and bucket unit from their mirror in `laneConfig`
/// (`FLAMMStore.LANE_NOTIONAL_SHIFT`, `LANE_UNIT_SHIFT`), so on a pool with no cheap lane an ask's `maxIn`
/// reads zero, beside its zero room.
function stateOf(FLAMMStore.S storage $, bool bid) internal view returns (uint256 room, uint256 maxIn) {
if (ReentrancyGuardLib._guardHeld()) return (0, 0);
(uint256 lane, uint256 cfg) = ($.laneWord, $.laneConfig);
(uint256 err, uint256 cash, uint256 rate) = _side($.tokens[1], bid, lane, $.held0, $.held1);
uint256 cap = FLAMMStore.reservedCap(cfg >> FLAMMStore.LANE_NOTIONAL_SHIFT, rate);
if (!bid) maxIn = cap;
if (err != 0) return (0, maxIn);
lane = refill(lane, cfg);
room = bid
? ((lane >> FLAMMStore.LANE_BID_SHIFT) & FLAMMStore.LANE_LEVEL_MASK) * _unit1(cfg)
: _min(cash, ((lane >> FLAMMStore.LANE_ASK_SHIFT) & FLAMMStore.LANE_LEVEL_MASK) * unitOf($.shareScale));
// net of the part beside the payout, as the pool's own swap pays both from its bucket and custody (a bid's
// custody is net already)
room = FLAMMStore.reserved(room, rate);
if (bid) room = _min(cash, room);
if (bid && cap != 0 && cap < room) room = cap;
}
/// @dev The side's predicate: zero and the out token's custody less the spread fee owed in it where the side is
/// open (a bid's within what holds its notional part in token 1 beside it, `FLAMMStore.reserved`), else the
/// error word of its first refusal; and the hook pair's notional rate (`FLAMMStore.notionalRate`), read before
/// any refusal, which the fill floors its part with and the view nets the cap of. It reads the pool's storage
/// itself, so the fill and the view share one copy of it.
function _side(FLAMMStore.TokenCfg storage c1, bool bid, uint256 lane, uint256 h0, uint256 h1)
private
view
returns (uint256 err, uint256 cash, uint256 rate)
{
FLAMMStore.S storage $ = FLAMMStore.s();
(uint256 f, uint256 sb, uint256 pb) = ($.features, $.swapBits, $.poolBits);
if (sb & FLAMMStore.SWAP_NOTIONAL != 0) rate = FLAMMStore.rateOf($.feeRates, 0, 1);
if (sb & FLAMMStore.SWAP_LANE == 0 || f & FLAMMStore.FEATURE_CHEAP_FILL == 0) {
return (_eArg(FeatureDisabled.selector, 6), 0, rate);
}
// a two-sided pool's rule, and a custody-blind pool's in strict mode, is the route's (`FLAMMRoute.pays`); a
// custody-blind pool outside strict mode takes none (`loose`), and its pause closes both sides
bool twoSided = (pb & FLAMMStore.POOL_TWO_SIDED) | (f & FLAMMStore.CUSTODY_BLIND) != 0;
bool loose = f & FLAMMStore.CUSTODY_BLIND != 0 && lane & FLAMMStore.LANE_STRICT == 0;
if (bid) {
if (f & FLAMMStore.FEATURE_SWAP_SELL == 0) return (_eArg(FeatureDisabled.selector, 1), 0, rate);
if (sb & FLAMMStore.SWAP_SELL_OPEN == 0) return (_e(PairNotTradable.selector), 0, rate);
if ($.paused) return (_e(Paused.selector), 0, rate);
if (!loose && !$.noBand && (twoSided ? !_twoSidedPays(true) : !_debtFree(c1))) {
return (_e(NotDebtFree.selector), 0, rate);
}
return (0, FLAMMStore.reserved(_less(h1, lane & FLAMMStore.LANE_ACCRUED_MASK), rate), rate);
}
if (f & FLAMMStore.FEATURE_SWAP_BUY == 0) return (_eArg(FeatureDisabled.selector, 2), 0, rate);
if (sb & FLAMMStore.SWAP_BUY_OPEN == 0) return (_e(PairNotTradable.selector), 0, rate);
if (f & FLAMMStore.CUSTODY_BLIND != 0 && $.paused) return (_e(Paused.selector), 0, rate);
if (
!loose
&& (twoSided
? !_twoSidedPays(false)
: !_othersDebtFree($) || (lane & FLAMMStore.LANE_STRICT != 0 && !_debtFree(c1)))
) return (_e(NotDebtFree.selector), 0, rate);
return (0, _less(h0, pb & FLAMMStore.POOL_SPREAD_OWED != 0 ? $.spreadFeeOwed[0] : 0), rate);
}
/// @dev A two-sided pool's rule on the hook pair's side, and a custody-blind pool's in strict mode
/// (`FLAMMRoute.pays`, out of the front's code): a bid pays token 1 for the pool asset, an ask the pool asset
/// for token 1.
function _twoSidedPays(bool bid) private view returns (bool) {
return bid ? FLAMMRoute.pays(0, 1) : FLAMMRoute.pays(1, 0);
}
/// @dev Whether no live pair owes token `c`'s, or it is proven debt-free.
function _debtFree(FLAMMStore.TokenCfg storage c) private view returns (bool) {
return c.partner == FLAMMStore.NO_PARTNER || c.debtFree;
}
/// @dev Whether every token past token 1 is debt-free in that sense: on a one-sided pool, where no pair owes the
/// pool asset, the rule of an ask on the hook pair.
function _othersDebtFree(FLAMMStore.S storage $) private view returns (bool) {
uint256 n = $.tokenCount;
for (uint256 t = 2; t < n; ++t) {
if (!_debtFree($.tokens[t])) return false;
}
return true;
}
/// @notice The cheap lane's debt rule, which reads no price: it may pay token `y` for token `x` only while `y` is
/// owed nowhere or proven debt-free (`TokenCfg.debtFree`) and every live pair that posts `y` as its
/// collateral is proven to owe nothing (`S.pairsFree`), save, on a one-sided pool outside strict mode, a
/// pair whose debt is `x` itself, which the input nets. In words: the cheap lane never pays out a token
/// while paying it could raise a debt or take backing from one, but the debt its own input pays down.
/// @dev Strict mode and a two-sided pool (`POOL_TWO_SIDED`, a pair that owes the pool asset or posts a token past
/// it) keep the stronger rule, with no such exception. A proof stands from a position read that shows the pair
/// owing nothing until the next draw at it, or until a fence's lift brings back a venue of it that owes (a
/// read leaves a fenced venue out); only a read sets one again (`FLAMM.proveDebtFree`, a flush). A
/// custody-blind pool outside strict mode takes no rule: its callers skip it there ({_side}, `FLAMMRoute`).
function pays(FLAMMStore.S storage $, uint256 x, uint256 y) internal view returns (bool) {
if (!_debtFree($.tokens[y])) return false;
(, uint256 posting) = FLAMMStore.lanes($, y);
if (posting == 0) return true;
uint256 open = posting & ~uint256($.pairsFree);
if (open == 0) return true;
if ($.laneWord & FLAMMStore.LANE_STRICT != 0 || $.poolBits & FLAMMStore.POOL_TWO_SIDED != 0) return false;
(uint256 owingX,) = FLAMMStore.lanes($, x);
return open & ~owingX == 0;
}
// ------------------------------------------------------------------ the credit path
/// @notice A swap's plan on a pool whose cheap lane is on (`FLAMMSwapLib`): on a pair its front prices (`hook`, the
/// plan's pricer, the swap hook), refuses while the credit path is off (a custody-blind pool's is off for
/// good, and it takes no pair hook, {updatePairHook}, so its own swap runs on no pair); on any pair, folds
/// the outflow room of the token it pays, `y`, into the hook's ceiling ({roomOf}), so every payout of the
/// pool, whoever prices it, stays within the caps. One bucket per token serves every pricer: the front's
/// cheap fills, its credit path and a pair hook's curve all draw on it, so a token's caps are sized for all
/// of them.
function ceilingOf(FLAMMStore.S storage $, uint256 y, uint256 ceiling, address hook)
public
view
returns (uint256)
{
if (hook == $.invariantHook && $.laneConfig & FLAMMStore.LANE_CREDIT_OFF != 0) revert CreditPathOff();
return _min(roomOf($, y), ceiling);
}
/// @notice Token `y`'s outflow room now, base units: its bucket refilled to now, a side of `laneWord` for the pool
/// asset (the ask's) and token 1 (the bid's), its own word from token 2 on (`S.laneTok`).
function roomOf(FLAMMStore.S storage $, uint256 y) internal view returns (uint256) {
if (y > 1) return (refillTok($.laneTok[y]) & FLAMMStore.TOK_LEVEL_MASK) * unitOf($.tokens[y].scale);
uint256 lane = refill($.laneWord, $.laneConfig);
return y == 1
? ((lane >> FLAMMStore.LANE_BID_SHIFT) & FLAMMStore.LANE_LEVEL_MASK) * unitOf($.tokens[1].scale)
: ((lane >> FLAMMStore.LANE_ASK_SHIFT) & FLAMMStore.LANE_LEVEL_MASK) * unitOf($.shareScale);
}
/// @notice A hook-priced fill's effects on the spread fee (`FLAMMSwapLib`, after its settlement or its custody-only
/// fill), on any pool. Returns the part booked. Linked, so the swap's unit carries none of it; a swap that
/// owes no part and no share on a pool book that keeps no fee never calls it.
/// @dev - `pf` holds the fill's part in its low 128 bits and the operator's share above them
/// (`FLAMMSwapLib.validate`): the two move and are cut together, `pf` the sum from here, and the part
/// alone rides above `flags`' 128 bits, bit 2 set, for {_split}. A fill that owes no share sets no bit
/// above the part's, so it moves, cuts and books exactly as on a pool that sets none.
/// - With `flags` bit 0 the custody word the settlement wrote, the pool's own, has what custody keeps of the
/// fee owed in each of its tokens added back (`kept`: the pool asset's in its low 128 bits, token 1's above
/// them) and the fill's part and share, which the settlement kept out of the pool's own custody
/// (`FLAMMSettleLib.Settle.keep`'s high half), so the payout's funding covered them.
/// - Then the part, at most what custody of `y` holds beside the fee already owed in it (the protocol forgoes
/// the rest), owed in `y` and paid in kind (`FLAMMFloatLib.collectSpreadFee`), a liability the next pool
/// book keeps out of the pool's own custody: on a pool whose cheap lane is on (bit 1) settled in the cheap
/// lane ({book}), else recorded. The part holds the pair's notional floor already, which the swap's checks
/// added and its settlement funded with the payout (`FLAMMSwapLib.validate`).
/// - Then the share, at most what that custody holds beside the fee and the part, the part cut first: booked
/// with the part, in the same record, and counted as the operator's ({_split},
/// `FLAMMFloatLib.collectOperatorFee`), all of it, as `shareOf` cut it to the room left in the operator's
/// counter before the settlement funded it, so the record never holds an amount that neither the protocol
/// nor the operator owns. What either cut leaves stays with the LPs.
/// - On a cheap-lane pool, which books every swap here, a swap whose payout pair may draw `y` (`flags` bits
/// 8-15, `FLAMMStore.NO_PAIR` for none) clears that pair's proof (`FLAMMStore.S.pairsFree`) where `y` is
/// owed after it (a draw clears `y`'s debt-free flag first, `FLAMMSettleLib`, and a pair's proof stands only
/// beside its debt token's flag), before the swap's lock lifts, so no cheap fill reads a stale proof.
function post(FLAMMStore.S storage $, uint256 y, uint256 out, uint256 pf, uint256 kept, uint256 flags)
public
returns (uint256)
{
// a share above the part's 128 bits moves and is cut with the part ({_split}): `pf` the two together from
// here, the part above `flags`' 128 bits, bit 2 set
if (pf >> 128 != 0) (pf, flags) = (uint128(pf) + (pf >> 128), flags | 4 | pf << 128);
// custody moves only where it keeps a fee or the fill owes a part
if (flags & 1 != 0 && kept | pf != 0) {
(uint256 h0, uint256 h1) = ($.held0, $.held1);
(h0, h1) = (h0 + (kept & type(uint128).max), h1 + (kept >> 128));
if (y == 0) h0 += pf;
else if (y == 1) h1 += pf;
else if (pf != 0) $.tokens[y].heldRest += pf;
FLAMMStore.setCustody($, h0, h1);
}
if (pf != 0) {
(uint256 h, uint256 f) = (FLAMMStore.heldOf($, y), FLAMMStore.feeOwed($, y));
uint256 room = h > f ? h - f : 0;
if (pf > room) pf = room;
}
if (flags & 2 != 0) {
book($, y, y, out + pf, pf);
// the payout pair's proof goes where `y` is owed now: the settlement's draw cleared `y`'s flag
uint256 drawn = (flags >> 8) & 0xff;
if (drawn != FLAMMStore.NO_PAIR && !$.tokens[y].debtFree) FLAMMGateLib.drawAt($, drawn);
} else if (pf != 0) {
record($, y, pf);
}
return flags & 4 == 0 ? pf : _split($, y, pf, flags >> 128);
}
/// @dev {post}'s split where the fill owes a share beside its part `part`: of `booked`, the two together as
/// custody cut them, the part first and the rest the share, which the operator's counter of `y` takes whole
/// (`FLAMMStore.addShare` cuts none of it, as `shareOf` cut the share to the counter's room). Returns the
/// part.
function _split(FLAMMStore.S storage $, uint256 y, uint256 booked, uint256 part) private returns (uint256) {
if (part > booked) part = booked;
if (booked != part) FLAMMStore.addShare($, y, booked - part);
return part;
}
/// @notice A fill's settlement on a pool whose cheap lane is on: debits `out` of `y` from its bucket, rounded up to
/// its unit (`OutflowCap` past its level), and books `fee` in `q`, token 1's in the accrual in `laneWord`
/// and any other token's in its record ({record}). One write of the bucket's word. A route fill
/// (`FLAMMRoute.fillFromFront`) debits its payout and books its part in the pair's quote; a hook-priced
/// fill ({post}) debits its payout and its part together, as both leave the pool's own custody (the ceiling
/// that {ceilingOf} folded the room into bounds the two), and books the part in `y`.
function book(FLAMMStore.S storage $, uint256 y, uint256 q, uint256 out, uint256 fee) internal {
if (y > 1) {
$.laneTok[y] = _debitAt(refillTok($.laneTok[y]), 0, out, unitOf($.tokens[y].scale));
if (fee != 0) {
if (q == 1) $.laneWord = _accrue($.laneWord, fee);
else record($, q, fee);
}
return;
}
uint256 lane = refill($.laneWord, $.laneConfig);
lane = _debit(lane, y == 1, out, y == 1 ? unitOf($.tokens[1].scale) : unitOf($.shareScale));
if (fee != 0) {
if (q == 1) lane = _accrue(lane, fee);
else record($, q, fee);
}
$.laneWord = lane;
}
/// @notice Clears `FLAMMStore.POOL_SPREAD_OWED` once no token's record owes anything, and no token's fence record
/// is open, which keeps it set (`FLAMMStore.SWAP_FENCE`): at a collection that empties a record
/// ({drainOwed}) and at the last token record's close (`FLAMMFenceLib.liftToken`).
function clearOwed(FLAMMStore.S storage $) internal {
if ($.swapBits & FLAMMStore.SWAP_FENCE != 0) return;
uint256 n = $.tokenCount;
for (uint256 i; i < n; ++i) {
if ($.spreadFeeOwed[i] != 0) return;
}
$.poolBits &= ~FLAMMStore.POOL_SPREAD_OWED;
}
/// @notice Token `t`'s owed record (`FLAMMStore.feeOwed`) in its two parts: the hook fills' record, read while some
/// fee is owed, and token 1's accrual in `laneWord` on a cheap-lane pool. The collections read it
/// (`FLAMMFloatLib.collectSpreadFee`, `FLAMMFloatLib.collectOperatorFee`).
function owedParts(FLAMMStore.S storage $, uint256 t) internal view returns (uint256 recorded, uint256 accrued) {
recorded = $.poolBits & FLAMMStore.POOL_SPREAD_OWED != 0 ? $.spreadFeeOwed[t] : 0;
accrued = t == 1 && $.swapBits & FLAMMStore.SWAP_LANE != 0 ? $.laneWord & FLAMMStore.LANE_ACCRUED_MASK : 0;
}
/// @notice A collection's payment `pay`, at most `recorded + accrued` ({owedParts}), off token `t`'s owed record:
/// `laneWord`'s accrual first, then the hook fills' record, whose emptying clears the owed bit where no
/// record owes ({clearOwed}).
function drainOwed(FLAMMStore.S storage $, uint256 t, uint256 pay, uint256 recorded, uint256 accrued) internal {
uint256 fromLane = Math.min(accrued, pay);
if (fromLane != 0) $.laneWord -= fromLane;
if (pay != fromLane) {
$.spreadFeeOwed[t] = recorded - (pay - fromLane);
if (recorded == pay - fromLane) clearOwed($);
}
}
// ------------------------------------------------------------------ the pair hook's install
/// @notice `FLAMMFloatLib.setPairHook`'s body, out of that library so it keeps its room: the curator installs,
/// replaces or (`hook` zero) removes the pair hook, the guardian only removes it; an install or a
/// replacement waits the pool's delay on the pending table, as a cap's raise does ({_due}, the key the
/// setter's selector), and passes its checks at the schedule and again at the application
/// ({_checkPairHook}); a removal applies at once and drops the installation scheduled.
function updatePairHook(FLAMMStore.S storage $, address hook, uint256 mask) public {
bool guardian = FLAMMStore.curatorOrGuardian($);
ReentrancyGuardLib._guard();
uint256 old = $.pairHookWord;
if (hook == address(0)) {
if (mask != 0 || old == 0) revert InvalidConfig();
_due($, bytes32(SET_PAIR_HOOK), true, "");
} else {
if (guardian) revert GuardianMayOnlyTighten();
_checkPairHook($, hook, mask);
if (_due($, bytes32(SET_PAIR_HOOK), false, abi.encode(SET_PAIR_HOOK, hook, mask)) != 0) {
ReentrancyGuardLib._unlockGuard();
return;
}
}
uint256 w = uint256(uint160(hook)) | mask;
// the old word's pairs past the new one's, each of them at a removal, pass back to the swap hook closed: in
// the trade mask, its scheduled opening and a fenced token's lift (`FLAMMFenceLib.liftToken`). An installation
// opens nothing: a closed pair, one closed since the schedule included, waits its opening
uint256 drop = orderedPairs($, old) & ~orderedPairs($, w);
uint256 t = $.tradePairs;
if (t & drop != 0) {
$.tradePairs = t & ~drop;
emit TradePairsSet(t & ~drop, msg.sender);
}
if ($.pendingTradePairs & drop != 0) $.pendingTradePairs &= ~drop;
if ($.fenceTrades & drop != 0) $.fenceTrades &= ~drop;
$.pairHookWord = w;
uint8 bits = $.swapBits;
$.swapBits = w == 0 ? bits & ~FLAMMStore.SWAP_PAIR_HOOK : bits | FLAMMStore.SWAP_PAIR_HOOK;
FLAMMOpsLib.syncCapabilities($);
syncPairs($);
emit PairHookSet(hook, mask);
ReentrancyGuardLib._unlockGuard();
}
/// @dev The pool is not custody-blind (`InvalidConfig`: such a pool runs no swap of its own, which is all a pair
/// hook prices). The mask names only pairs of listed tokens under `PAIR_HOOK_TOKENS` (a pair `{lo, hi}` at bit
/// `160 + hi * (hi - 1) / 2 + lo`, so the listed ones are contiguous), the hook pair's (bit 160) not among
/// them; the hook has code, names this pool and answers the interface version (`FLAMMOpsLib.checkIdentity`),
/// declares `HOOK_CAP_PAIR_HOOK` and meets the band mode and the pairs listed (`FLAMMGateLib.checkHook`); and
/// it prices each of the mask's pairs both ways, the front, on a cheap-lane pool, neither way. Each read fails
/// closed ({asks}): an answer not given (a revert, or a word that is not a bool) reads as a pair the hook does
/// not price and one the front does, so neither the schedule nor the installation passes on it.
function _checkPairHook(FLAMMStore.S storage $, address hook, uint256 mask) private view {
// a custody-blind pool runs no swap of its own, which is all a pair hook prices
if ($.features & FLAMMStore.CUSTODY_BLIND != 0) revert InvalidConfig();
uint256 n = $.tokenCount;
if (n > FLAMMStore.PAIR_HOOK_TOKENS) n = FLAMMStore.PAIR_HOOK_TOKENS;
if (mask == 0 || mask & ~(((uint256(1) << (n * (n - 1) / 2)) - 2) << 160) != 0) revert InvalidConfig();
FLAMMOpsLib.checkIdentity(hook, true);
FLAMMGateLib.requireCapability(hook, HOOK_CAP_PAIR_HOOK);
FLAMMGateLib.checkHook($, hook);
(bool lane, address front) = ($.swapBits & FLAMMStore.SWAP_LANE != 0, $.invariantHook);
// one pricer a pair: the hook, both ways, and on a cheap-lane pool never the front
uint256 pairs = orderedPairs($, mask);
for (uint256 k; pairs >> k != 0; ++k) {
if ((pairs >> k) & 1 == 0) continue;
(address a, address c) = (FLAMMStore.tokenOf($, k >> 4), FLAMMStore.tokenOf($, k & 15));
// the hook must price the pair, and the front must not (one that gives no answer is read as pricing it)
if (asks(hook, a, c) != 1 || (lane && asks(front, a, c) != 0)) revert InvalidConfig();
}
}
/// @notice The trade-mask bits (`16 * i + j`, both ways) of the unordered pairs a pair hook's word `w` names
/// (`FLAMMStore.pairHookBit`).
function orderedPairs(FLAMMStore.S storage $, uint256 w) internal view returns (uint256 o) {
uint256 n = $.tokenCount;
if (n > FLAMMStore.PAIR_HOOK_TOKENS) n = FLAMMStore.PAIR_HOOK_TOKENS;
for (uint256 j = 2; j < n; ++j) {
for (uint256 i; i < j; ++i) {
if (w & FLAMMStore.pairHookBit(i, j) != 0) {
o |= (uint256(1) << (16 * i + j)) | (uint256(1) << (16 * j + i));
}
}
}
}
/// @notice Records `fee` as owed to the protocol in token `t` (`S.spreadFeeOwed`, `POOL_SPREAD_OWED`): any token's
/// part on a pool whose cheap lane is off, and any token's but token 1's on a cheap-lane pool, whose
/// `laneWord` accrues token 1's.
function record(FLAMMStore.S storage $, uint256 t, uint256 fee) internal {
$.spreadFeeOwed[t] += fee;
uint8 bits = $.poolBits;
if (bits & FLAMMStore.POOL_SPREAD_OWED == 0) $.poolBits = bits | FLAMMStore.POOL_SPREAD_OWED;
}
// ------------------------------------------------------------------ the pairs' proofs
/// @notice `FLAMM.proveDebtFree` on a pool whose cheap lane is on: `FLAMMGateLib.markRead` of a fresh position
/// read, and the proof of each live pair it shows owing nothing (`S.pairsFree`, {_markPairs}): the one
/// way a proof is set after a pair's admission (a flush with `prove` runs it too). A flow's own read sets
/// none, so no flow pays for it. Any other pool proves through `FLAMMGateLib.proveDebtFree`, core's path.
function proveDebtFree(FLAMMStore.S storage $) public {
FLAMMGateLib.Book memory b = FLAMMGateLib.bookOf($);
FLAMMGateLib.markRead($, b);
_markPairs($, b);
}
/// @notice `FLAMMFloatLib.flushPair`'s bound on a repay at pair `p` of token `y`, a token with two or more live
/// pairs, on any pool, out of the hot libraries. Owed at one of them (`many` false), at no price read: none
/// for the keeper or the curator and nothing for anyone else, as the law reads such a token's debt net of
/// its custody, so the repay moves none of its terms and only places custody that may pay another live
/// pair's sellers. Owed at two or more: none for those two where its custody covers the whole debt (`short`
/// false), at no price read, as it then covers what is left; else `FLAMMLawLib.repayRoom` at a fresh priced
/// read, the caller one of those two or anyone. Its selector sorts after the credit path's two.
function flushPairRoom(FLAMMStore.S storage $, uint256 y, uint256 p, bool short, bool many)
public
view
returns (uint256)
{
bool steward = msg.sender == $.core.keeper() || msg.sender == $.core.owner();
if (!many || !short) {
if (steward) return type(uint256).max;
if (!many) return 0;
}
FLAMMGateLib.Book memory b = FLAMMGateLib.bookOf($);
FLAMMGateLib.priceIn($, b);
return FLAMMLawLib.repayRoom($, b, y, p, steward);
}
/// @dev Sets the proof (`S.pairsFree`) of each live pair `b` shows owing nothing: a pair whose debt token another
/// live pair owes too by the per-pair read (`FLAMMGateLib.Book.pairOwed`; none read: no proof), any other by
/// its token's whole debt. Never clears one: a draw does (`FLAMMGateLib.drawAt`).
function _markPairs(FLAMMStore.S storage $, FLAMMGateLib.Book memory b) private {
(uint256 n, uint256 multi, uint32 free) = ($.pairCount, $.multiPairs, $.pairsFree);
uint32 next = free;
for (uint256 p; p < n; ++p) {
FLAMMStore.PairCfg storage pc = $.pairs[p];
if (!pc.live) continue;
uint256 owed = (multi >> p) & 1 == 0 ? b.legs[pc.debt].owed : p < b.pairOwed.length ? b.pairOwed[p] : 1;
if (owed == 0) next |= uint32(1 << p);
}
if (next != free) $.pairsFree = next;
}
// ------------------------------------------------------------------ the pairs each hook prices
/// @notice Asks the swap hook which ordered pairs of the listed tokens it prices (`IPairHook.pricesPair`, read by
/// hand: {asks}), the pair hook for its own pairs where one is set (`FLAMMStore.pairHookOf`), and caches
/// the answers (`S.hookPairs`, bit `16 * i + j` for token `i` for token `j`; `HOOK_PAIRS_SPLIT` while a
/// pair hook is set). Run at each installation of a swap hook or of a pair hook, at each pair hook's
/// removal and at each token's listing.
/// @dev - `S.lanePairs` drops the pair hook's pairs, so a pair it takes leaves the cheap lane at once; a pair the
/// front does not price yet stays, its listing to go live later ({syncListings}).
/// - On a pool whose cheap lane is on, as at the listings' resync, a pair the hook gives no answer for (a
/// revert, or a word that is not a bool) stands as it was, and a pair of the front's past the hook pair off
/// `S.lanePairs` may only close, so a pair hook's installation or removal or a token's listing reopens none
/// the cheap lane keeps shut; elsewhere a pair with no answer reads as unpriced.
/// - Its selector sorts after the credit path's two.
function syncPairs(FLAMMStore.S storage $) public {
(address hook, uint256 n, uint256 old) = ($.invariantHook, $.tokenCount, $.hookPairs);
uint8 swapBits = $.swapBits;
bool split = swapBits & FLAMMStore.SWAP_PAIR_HOOK != 0;
bool lane = swapBits & FLAMMStore.SWAP_LANE != 0;
uint256 mask = split ? FLAMMStore.HOOK_PAIRS_SPLIT : 0;
for (uint256 i; i < n; ++i) {
address ti = FLAMMStore.tokenOf($, i);
for (uint256 j; j < n; ++j) {
if (i == j) continue;
address h = split ? FLAMMStore.pairHookOf($, i, j) : address(0);
if (h == address(0)) h = hook;
uint256 bit = uint256(1) << (16 * i + j);
uint256 v = asks(h, ti, FLAMMStore.tokenOf($, j));
if (v == 1) mask |= bit;
else if (v == 2 && lane) mask |= old & bit;
}
}
uint256 lp = $.lanePairs;
uint256 taken = split ? orderedPairs($, $.pairHookWord) : 0;
if (lp & taken != 0) {
lp &= ~taken;
$.lanePairs = lp;
emit LanePairsSet(lp);
}
if (lane) {
// the front's pairs past the hook pair off `lanePairs` only close, as at the listings' resync
uint256 front = ~(lp | taken | FLAMMStore.HOOK_PAIR_BITS | FLAMMStore.HOOK_PAIRS_SPLIT);
mask &= ~front | old;
}
$.hookPairs = mask;
if (lane) FLAMMStore.syncRoute($);
FLAMMAdmitLib.syncSwapBits($, mask, $.tradePairs);
emit HookPairsSynced(mask);
}
/// @notice The listings' resync, out of line: asks the front again which pairs past the hook pair it prices
/// ({asks}), among those `only` names, and records each answer in `S.hookPairs`. Returns the mask it
/// leaves, `HOOK_PAIRS_SPLIT` cleared.
/// @dev - Of `S.lanePairs` it records each as it answers, and of every other pair `S.hookPairs` holds open for the
/// front a no alone, which closes it; never of the hook pair's or a pair hook's.
/// - 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, so no caller's gas makes an answer read as no and no pair's failure stops
/// another's resync.
/// - `FLAMMFloatLib.syncListings` asks of every pair, and an opening of `S.lanePairs` of the pairs it opens
/// (`FLAMMFloatLib.setLanePairs`), so a listing that went live before its pair joined the cheap lane trades
/// once the opening applies.
/// - Its selector sorts after the credit path's two.
function syncListings(FLAMMStore.S storage $, uint256 only) public returns (uint256) {
uint256 lp = $.lanePairs;
uint256 hp = $.hookPairs;
// `lanePairs`, and the others the front's answers hold open past the hook pair, which may only close
uint256 m = (lp | (hp & ~(FLAMMStore.HOOK_PAIRS_SPLIT | FLAMMStore.HOOK_PAIR_BITS))) & only;
if (hp & FLAMMStore.HOOK_PAIRS_SPLIT != 0) m &= ~orderedPairs($, $.pairHookWord);
(address front, uint256 next) = ($.invariantHook, hp);
for (uint256 b; m >> b != 0; ++b) {
if ((m >> b) & 1 == 0) continue;
uint256 bit = uint256(1) << b;
uint256 v = asks(front, FLAMMStore.tokenOf($, b >> 4), FLAMMStore.tokenOf($, b & 15));
if (v == 1) next |= bit & lp;
else if (v == 0) next &= ~bit;
}
if (next != hp) {
$.hookPairs = next;
FLAMMStore.syncRoute($);
emit HookPairsSynced(next);
}
return next & ~FLAMMStore.HOOK_PAIRS_SPLIT;
}
/// @dev `h`'s `IPairHook.pricesPair` answer for this pool and the pair of `a` for `c`, read by hand so a malformed
/// answer reverts nothing here: 1 for yes, 0 for no, 2 for none (a revert, a call short of gas included, or a
/// word that is not a bool).
function asks(address h, address a, address c) internal view returns (uint256 v) {
bytes4 sel = IPairHook.pricesPair.selector;
assembly ("memory-safe") {
let m := mload(0x40)
mstore(m, sel)
mstore(add(m, 4), address())
mstore(add(m, 36), a)
mstore(add(m, 68), c)
v := 2
if staticcall(gas(), h, m, 100, 0, 32) {
if gt(returndatasize(), 31) {
let w := mload(0)
if lt(w, 2) { v := w }
}
}
}
}
// ------------------------------------------------------------------ the curator's caps and floors, the fee mark
/// @notice When a change to a cap is due (`FLAMMOpsLib`'s cap and switch setters, `FLAMM.setMintProRataCap`): zero,
/// now, on a pool whose cheap lane is off. On one whose cheap lane is on, a tightening (`tighter`), the
/// curator's or the guardian's, applies now and drops the same cap's scheduled raise
/// (`AdmissionCancelled`); a loosening, the curator's, goes through the pending table as an admission: the
/// first call schedules `data` for the pool's delay, replacing the same cap's earlier raise, and returns
/// when it is due; the identical call within its window applies it (zero); the curator or the guardian
/// cancels it (`FLAMMAdmitLib.cancel`). A cap is its setter and the token, pair or venue it sets: `data`'s first
/// two words, or its first alone where it has two (a pool-wide cap). On a pool whose cheap lane is off,
/// `FLAMMPolicyLib.setTokenConfig` and `FLAMMPolicyLib.setFeeBounds` hold a cut of a fee floor to the same table
/// instead ({scheduledCut}).
function capDue(FLAMMStore.S storage $, bool tighter, bytes memory data) public returns (uint256) {
if ($.swapBits & FLAMMStore.SWAP_LANE == 0) return 0;
bytes32 key;
assembly ("memory-safe") {
key := keccak256(add(data, 0x20), shl(5, sub(2, lt(mload(data), 0x60))))
}
return _due($, key, tighter, data);
}
/// @notice When a change of a fee floor is due on a pool whose cheap lane is off: the pending table's rule
/// ({_due}), `tighter` a floor at or above the one in force. A cut, the curator's alone (`setFeeBounds` is
/// the curator's, and the guardian's `setTokenConfig` may only tighten), waits the pool's delay: the first
/// call schedules `data` (`AdmissionScheduled`), replacing the setter's cut scheduled before, and the
/// identical call applies it from its due time until one delay later, past which it lapses and that call
/// schedules it again; any other call of the setter applies now (zero) and drops the cut scheduled, so a
/// stale config never lands later; the curator or the guardian cancels it (`FLAMMAdmitLib.cancel`), and no other
/// call applies it. A due cut stays armed for its whole window, so LPs act on its scheduling event
/// (`AdmissionScheduled`), not on the wait itself. `key` names the setter's one cut in `capRaises`: the
/// pool's floor's (`FLAMMPolicyLib.setFeeBounds`) its selector alone, whatever the call's values; a token's
/// (`FLAMMPolicyLib.setTokenConfig`, the pool asset's aside, as no fill reads it) its selector and the token,
/// as {capDue} keys a cap.
/// @dev Its selector sorts after every other entry here, the lane pause's included, so no other entry's call pays
/// to skip it in this library's dispatcher. It stays in this library, which no fallback reaches: its caller
/// names the storage and the key.
function scheduledCut(FLAMMStore.S storage $, bytes32 key, bool tighter, bytes memory data)
public
returns (uint256)
{
return _due($, key, tighter, data);
}
/// @dev The pending table's rule for an entry `data` (its selector and arguments, abi-encoded as one tuple) whose
/// one scheduled loosening stands under `key` in `capRaises`, on every pool: a tightening applies now (zero)
/// and drops the loosening scheduled under `key`; a loosening's first call schedules `data` for the pool's
/// delay, replacing that one, and returns when it is due; the identical call within its window once due
/// applies it (zero); one before its due time reverts `HookSetNotReady`; past the window it lapses. The pair
/// hook's installations (`key` its setter's selector), the curator's caps ({capDue}, a raise the loosening)
/// and, on a pool whose cheap lane is off, the cuts of its fee floors ({scheduledCut}, a cut the loosening)
/// run it.
function _due(FLAMMStore.S storage $, bytes32 key, bool tighter, bytes memory data)
private
returns (uint256 dueAt)
{
bytes32 armed = $.capRaises[key];
bytes32 h = keccak256(data);
if (armed != 0 && (tighter || armed != h)) {
delete $.capRaises[key];
if ($.pending[armed] != 0) {
delete $.pending[armed];
emit AdmissionCancelled(armed, msg.sender);
}
}
if (tighter) return 0;
dueAt = $.pending[h];
uint256 delay = $.governanceDelaySec;
if (dueAt != 0) {
if (block.timestamp < dueAt) revert HookSetNotReady();
if (block.timestamp <= dueAt + FLAMMStore.executionWindow(delay)) {
delete $.pending[h];
delete $.capRaises[key];
return 0;
}
}
dueAt = block.timestamp + delay;
($.pending[h], $.capRaises[key]) = (uint48(dueAt), h);
emit AdmissionScheduled(h, bytes4(data), uint48(dueAt), msg.sender, data);
}
/// @notice After each of the curator's seeds on a pool whose cheap lane is on (`FLAMM.seedLeg`, which runs only
/// while the curator holds every share but the dead ones and before the pool has opened,
/// `FLAMMStore.S.opened`: no share has moved and none went to another holder, so no one else's fee mark
/// moves): records the deposit basket afresh from the pool book the seed leaves, where it holds or
/// supplies token 1, and restarts the curator's fee mark at 1e18 (`FLAMMGateLib.setBasket`). The seed's
/// skim ran first, at the old fee mark. Nothing else records it: a pool whose curator's fee cap is nonzero
/// takes no pro-rata entry until a seed of token 1 has (`FLAMMGateLib.basketGated`), so the curator seeds
/// token 1 after the pool's launch through `PropAMMLauncher`, which seeds the pool asset alone, and
/// before any share leaves them: a pool opened first never records it.
function recordBasket(FLAMMStore.S storage $, uint256 supply) public {
FLAMMGateLib.setBasket($, FLAMMGateLib.bookOf($), supply);
}
// ------------------------------------------------------------------ the pauses
/// @notice `FLAMM.setPaused` on a pool whose cheap lane is on, `p` the pause asked for: the curator's pause and the
/// guardian's (`LANE_CURATOR_PAUSE`, `LANE_GUARDIAN_PAUSE`), each set and cleared by its own; returns
/// whether the pool is paused, which it is while either stands. The guardian's records the guardian that
/// set it (`lanePauser`), and a pause by the guardian in office takes over one a guardian rotated out left.
/// The guardian in office lifts it; the curator lifts it only once the guardian that set it is not the
/// pool's any more, a rotation that waits the authority's `DELAY` (at least `governanceDelaySec`); no
/// protocol role lifts it (`GuardianPauseStands`). A guardian's pause of a paused pool never reverts, so
/// one standing pause cannot stop the guardian's batch over many pools. A pause with neither bit, which
/// `FLAMMFloatLib.initLane` leaves on no pool (it records a birth pause as the curator's), still counts as
/// the curator's.
/// @dev Its selector sorts after every other entry here but {scheduledCut}'s, so no swap's call of {ceilingOf} or
/// {post} pays to skip it in this library's dispatcher.
function setLanePause(FLAMMStore.S storage $, bool p) public returns (bool) {
uint256 both = FLAMMStore.LANE_GUARDIAN_PAUSE | FLAMMStore.LANE_CURATOR_PAUSE;
uint256 cfg = $.laneConfig;
if ($.paused && cfg & both == 0) cfg |= FLAMMStore.LANE_CURATOR_PAUSE;
bool curator = msg.sender == $.core.owner();
address g = $.core.guardian();
bool guardian = msg.sender == g;
if (p) {
if (curator) {
cfg |= FLAMMStore.LANE_CURATOR_PAUSE;
} else {
if (!guardian) revert NotGuardianOrCurator();
// the guardian in office holds the guardian's pause, taking over one a guardian rotated out left
(cfg, $.lanePauser) = (cfg | FLAMMStore.LANE_GUARDIAN_PAUSE, msg.sender);
}
} else if (cfg & FLAMMStore.LANE_GUARDIAN_PAUSE != 0) {
// the guardian in office, or the curator once the guardian that set it was rotated out
if (!guardian && !(curator && $.lanePauser != g)) revert GuardianPauseStands();
(cfg, $.lanePauser) = (cfg & ~FLAMMStore.LANE_GUARDIAN_PAUSE, address(0));
} else {
if (!curator) revert NotCurator();
cfg &= ~FLAMMStore.LANE_CURATOR_PAUSE;
}
$.laneConfig = cfg;
return cfg & both != 0;
}
// ------------------------------------------------------------------ the buckets
/// @notice `lane` with both sides' levels refilled to now at their rates, each at most its burst (and its field),
/// so a cut of the caps binds at once, and the refill time now.
function refill(uint256 lane, uint256 cfg) internal view returns (uint256) {
uint256 last = (lane >> FLAMMStore.LANE_TIME_SHIFT) & 0xffffffff;
// the time since the last refill, taken only once now is past it
unchecked {
uint256 dt = block.timestamp > last ? block.timestamp - last : 0;
lane = _level(lane, cfg, FLAMMStore.LANE_BID_SHIFT, 0, dt);
lane = _level(lane, cfg, FLAMMStore.LANE_ASK_SHIFT, 48, dt);
}
lane &= ~(uint256(0xffffffff) << FLAMMStore.LANE_TIME_SHIFT);
return lane | (block.timestamp << FLAMMStore.LANE_TIME_SHIFT);
}
/// @dev One side's level, or a token's bucket's ({refillTok}): `shift` its field in `laneWord` (or in the token's
/// word), `c` its rate's place in `laneConfig` (or in the token's caps; the burst 24 bits above), refilled for
/// `dt` seconds with no overflow.
function _level(uint256 lane, uint256 cfg, uint256 shift, uint256 c, uint256 dt) private pure returns (uint256) {
uint256 burst = PropAMMLaneLib.amount24((cfg >> (c + 24)) & 0xffffff);
if (burst > FLAMMStore.LANE_LEVEL_MASK) burst = FLAMMStore.LANE_LEVEL_MASK;
uint256 level = (lane >> shift) & FLAMMStore.LANE_LEVEL_MASK;
if (level >= burst) {
level = burst;
} else if (dt != 0) {
uint256 rate = PropAMMLaneLib.amount24((cfg >> c) & 0xffffff);
// the level is under its burst, at most 2^60 - 1, and the rate under 2^228 (an 18-bit mantissa times 10^63
// at most), so the gap and the rounded quotient's sum cannot wrap; `rate * dt` runs only where it is under
// the gap, so the level stays under the burst; the division keeps its zero check, after `rate != 0`
unchecked {
uint256 gap = burst - level;
level = rate != 0 && dt >= (gap + rate - 1) / rate ? burst : level + rate * dt;
}
}
return (lane & ~(FLAMMStore.LANE_LEVEL_MASK << shift)) | (level << shift);
}
/// @dev Debits a payout of `out` base units from the side's level, rounded up to its `unit`: `OutflowCap` past it.
function _debit(uint256 lane, bool bid, uint256 out, uint256 unit) private pure returns (uint256) {
return _debitAt(lane, bid ? FLAMMStore.LANE_BID_SHIFT : FLAMMStore.LANE_ASK_SHIFT, out, unit);
}
/// @dev Debits `out` base units, rounded up to `unit`, from the 60-bit level at `shift` of `w` (`OutflowCap`
/// past it).
function _debitAt(uint256 w, uint256 shift, uint256 out, uint256 unit) private pure returns (uint256) {
uint256 level = (w >> shift) & FLAMMStore.LANE_LEVEL_MASK;
// `debit * unit` is at most `out`, the increment runs only under it, and the debit is at most the level, so
// the subtraction stays within the level's 60-bit field; the division keeps its zero check
unchecked {
uint256 debit = out / unit;
if (debit * unit != out) ++debit;
if (debit > level) revert OutflowCap();
return w - (debit << shift);
}
}
/// @notice A token's bucket word from token 2 on (`S.laneTok`) with its level refilled to now at its rate, at most
/// its burst, and its refill time now.
function refillTok(uint256 w) internal view returns (uint256) {
uint256 last = (w >> FLAMMStore.TOK_TIME_SHIFT) & 0xffffffff;
uint256 dt = block.timestamp > last ? block.timestamp - last : 0;
w = _level(w, w >> FLAMMStore.TOK_CAPS_SHIFT, 0, 0, dt);
w &= ~(uint256(0xffffffff) << FLAMMStore.TOK_TIME_SHIFT);
return w | (block.timestamp << FLAMMStore.TOK_TIME_SHIFT);
}
/// @dev Adds `fee` to the accrued field: `OutflowCap` where it would pass the field.
function _accrue(uint256 lane, uint256 fee) private pure returns (uint256) {
if ((lane & FLAMMStore.LANE_ACCRUED_MASK) + fee > FLAMMStore.LANE_ACCRUED_MASK) revert OutflowCap();
return lane + fee;
}
/// @notice A token's bucket unit from its scale (`10^(18 - decimals)`): `10^(decimals - 6)` base units, one under
/// six decimals.
function unitOf(uint256 scale) internal pure returns (uint256) {
return scale < 1e12 ? 1e12 / scale : 1;
}
/// @dev Token 1's bucket unit ({unitOf}) from its power of ten in `laneConfig`, here `cfg`
/// (`FLAMMStore.LANE_UNIT_SHIFT`).
function _unit1(uint256 cfg) private pure returns (uint256) {
return 10 ** ((cfg >> FLAMMStore.LANE_UNIT_SHIFT) & 0xf);
}
// ------------------------------------------------------------------ helpers
function _less(uint256 a, uint256 b) private pure returns (uint256) {
return a > b ? a - b : 0;
}
function _min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
}
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.