Verified contractPartialUNLICENSED
PropAMMAdminColdRegistry
Address0x9e46428ef7bdb8b4d6a4f33227ecc718f656c582
- 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
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,480,546
- Creation transaction
- 0x1652c113cb…fcf82bb71c
22 files
- src/propamm/PropAMMAdminCold.solmain43.21 KB
- lib/openzeppelin-contracts-compat/contracts/token/ERC20/IERC20.sol2.77 KB
- lib/openzeppelin-contracts-compat/contracts/utils/math/Math.sol12.51 KB
- lib/solady/src/utils/CREATE3.sol6.57 KB
- src/interfaces/core/IEverlongCore.sol889 B
- src/interfaces/core/flamm/IFLAMM.sol52.68 KB
- src/interfaces/core/flamm/IFLAMMHooks.sol8.36 KB
- src/interfaces/core/flamm/IFLAMMLane.sol16.85 KB
- src/interfaces/core/flamm/IPairHook.sol14.14 KB
- src/libraries/Constants.sol2.11 KB
- src/libraries/DelayLib.sol11.22 KB
- src/propamm/PropAMMDeskCellCode.sol9.73 KB
- src/propamm/PropAMMDeskCode.sol9.13 KB
- src/propamm/PropAMMShared.sol25.91 KB
- src/propamm/interfaces/IAssetModule.sol10.9 KB
- src/propamm/interfaces/IPriceSource.sol10.45 KB
- src/propamm/interfaces/IPropAMMFront.sol43.74 KB
- src/propamm/libraries/PropAMMClock.sol5.26 KB
- src/propamm/libraries/PropAMMLaneLib.sol2.31 KB
- src/propamm/libraries/PropAMMRegistryRule.sol3.59 KB
- src/propamm/libraries/PropAMMStore.sol16.36 KB
- src/propamm/libraries/PropAMMWords.sol38.16 KB
src/propamm/PropAMMAdminCold.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {PropAMMShared} from "src/propamm/PropAMMShared.sol";
import {IPriceLane} from "src/propamm/interfaces/IPriceSource.sol";
import {IAssetModule} from "src/propamm/interfaces/IAssetModule.sol";
import {PropAMMStore} from "src/propamm/libraries/PropAMMStore.sol";
import {PropAMMWords as W} from "src/propamm/libraries/PropAMMWords.sol";
import {PropAMMClock} from "src/propamm/libraries/PropAMMClock.sol";
import {PropAMMRegistryRule} from "src/propamm/libraries/PropAMMRegistryRule.sol";
import {CREATE3} from "solady/utils/CREATE3.sol";
import {DelayLib} from "src/libraries/DelayLib.sol";
/// @notice The build's clock, answered by the hot implementation through the proxy: a stored price lane must keep it.
interface IFrontClock {
/// @notice The build's maker-time windows and clock (`PropAMMFront.clock`): of them a lane keeps to the pull
/// lead and the clock's mode, block and milliseconds.
function clock() external view returns (PropAMMClock.Timing memory);
}
/// @notice The build's two quote assets, answered by the hot implementation through the proxy: only the seed of the
/// stored quote list, which `initialize` lists at ranks 1 and 2 (`QuoteAssetSet`). `addPair` reads the stored
/// list (`quoteRank`, `setQuoteAsset`), never these immutables.
interface IFrontQuotes {
/// @notice The chain's first quote asset.
function QUOTE0() external view returns (address);
/// @notice The chain's second quote asset, zero for none.
function QUOTE1() external view returns (address);
}
/// @notice What `initialize` reads of a launcher: the runtime codehash of the authorities it builds.
interface ILauncherPin {
/// @notice The runtime code hash of the `DelayedAuthority` the launcher builds.
function AUTHORITY_CODEHASH() external view returns (bytes32);
}
/// @notice What the admin module's two parts share (`PropAMMAdmin`, `PropAMMAdminCold`): the build's kind, a view
/// asked under `SOURCE_GAS`, and the rule an asset module is held to.
abstract contract PropAMMAdminShared is PropAMMShared {
/// @dev The storage build's `LANE_KIND`.
uint256 internal constant LANE_STORAGE = 1;
/// @dev Whether `module` may rule `listing` (0 at the pair's birth) of a pair of base `base` and family `family`:
/// an account with code (more than a delegation designator's 23 bytes) that names this front (`FRONT`), reads
/// the base as the family (`isFamily`) and has never held a word for the listing (`isBound`), each answer
/// one word.
function _assetOk(address module, address base, uint256 family, uint256 listing) internal view returns (bool ok) {
if (module.code.length <= 23) return false;
(bytes4 sFront, bytes4 sFamily, bytes4 sBound) =
(IAssetModule.FRONT.selector, IAssetModule.isFamily.selector, IAssetModule.isBound.selector);
assembly ("memory-safe") {
let m := mload(0x40)
mstore(m, sFront)
// Yul evaluates arguments right to left: each call first, in its own statement
let s := staticcall(gas(), module, m, 4, 0, 0x20)
ok := and(and(s, eq(returndatasize(), 0x20)), eq(mload(0), address()))
if ok {
mstore(m, sFamily)
mstore(add(m, 4), base)
mstore(add(m, 0x24), family)
s := staticcall(gas(), module, m, 0x44, 0, 0x20)
ok := and(and(s, eq(returndatasize(), 0x20)), eq(mload(0), 1))
}
if ok {
mstore(m, sBound)
mstore(add(m, 4), listing)
s := staticcall(gas(), module, m, 0x24, 0, 0x20)
ok := and(and(s, eq(returndatasize(), 0x20)), iszero(mload(0)))
}
}
}
/// @dev `a`'s answer to its view `sel` with the word `arg` (which a view of none ignores), its first three words,
/// by one call under `SOURCE_GAS`: a call that fails or answers other than `size` bytes refuses (`BadConfig`),
/// or is the caller's short limit (`GasShort`, `_starved`).
function _view(address a, bytes4 sel, uint256 arg, uint256 size)
internal
view
returns (uint256 w0, uint256 w1, uint256 w2)
{
uint256 g = gasleft();
bool ok;
assembly ("memory-safe") {
let m := mload(0x40)
mstore(m, sel)
mstore(add(m, 4), arg)
// Yul evaluates arguments right to left: the call first, in its own statement
let s := staticcall(SOURCE_GAS, a, m, 0x24, m, 0x60)
ok := and(s, eq(returndatasize(), size))
w0 := mload(m)
w1 := mload(add(m, 0x20))
w2 := mload(add(m, 0x40))
}
if (!ok) {
_starved(g);
revert BadConfig();
}
}
}
/// @notice The admin module's cold part: the front-wide calls no listing's own call and no fill reaches, reached by
/// DELEGATECALL from the admin part's fallback (`PropAMMAdmin.COLD`) for every selector the admin part does
/// not serve, so it runs in the proxy's context and on its ERC-7201 namespace as the admin part does: the
/// front's setup (`initialize`), the owner's setters (the code freeze, the protocol guardian, the protocol's
/// asset module, the quote assets, a pair's retirement), the opening of desks, the registration of pairs and
/// price sources, and the listing scan (`listingsOn`). Each costs one DELEGATECALL more than the admin
/// part's own calls.
/// @dev Created by its kind's admin leaf (`PropAMMAdmin._cold`) from the inputs that leaf checked, so the two parts
/// are one build; it reads its own immutables, never the admin part's. Its own storage is marked initialized
/// at construction and never used: called directly, not through the proxy, it writes nothing but there.
abstract contract PropAMMAdminCold is PropAMMAdminShared {
using W for uint256;
/// @dev The gas `retirePair` holds before each claim it asks (`_claim`): over the nine reads the protocol's module
/// makes for one at most (`StockModule.familyOf`: one of family 3, three each of 1 and 2, and the two of a
/// noted code's mark), each under its `READ_GAS` (28,000) with its call's cost (5,300 at most), the module's
/// own steps and the 1/64 its call keeps back: about 265,000 at the worst, under the 295,000 it forwards.
uint256 internal constant CLAIM_GAS = 300_000;
// ---------------------------------------------------------------- deployment
/// @dev The pull-price age ceiling, ms (`PropAMMAdmin.AGE_CEIL_MS`): the most a source's window may reach.
uint256 internal immutable AGE_CEIL_MS;
/// @dev The runtime code hash of `DelayedAuthority` (`PropAMMAdmin.AUTHORITY_CODEHASH`), which a launcher's
/// authorities must have.
bytes32 internal immutable AUTHORITY_CODEHASH;
/// @notice Fixes the build's inputs, as its admin leaf checked them (`PropAMMAdmin`'s constructor), and marks the
/// part's own storage initialized.
/// @param ageCeilMs `AGE_CEIL_MS`.
/// @param authorityCodehash `AUTHORITY_CODEHASH`.
constructor(uint256 ageCeilMs, bytes32 authorityCodehash) {
AGE_CEIL_MS = ageCeilMs;
AUTHORITY_CODEHASH = authorityCodehash;
// The part's own storage is never used: mark it initialized so it cannot be.
PropAMMStore.state().ids = 1 << 255;
}
// ================================================================ initialization
/// @notice Once, by the deployer in the call that creates the proxy: the owner, the protocol owner and the protocol
/// guardian, the registry on a builder build, the launcher and the protocol's asset module.
/// @dev Nothing here logs: the deployer's `FrontDeployed` names its caller, the front, the timelock, the canceller
/// and the implementation, and the rest of the set is in the creation calldata and in storage (the `owner`,
/// `instantOwner` and `protocolGuardian` getters, the rest through `extSloads`).
/// @param owner_ The owner: the front's timelock.
/// @param safe_ The protocol owner.
/// @param guardian_ The protocol guardian.
/// @param source The registry on a builder build, zero on a storage build, whose prices come from the stored price
/// lanes its listings bind. The registry must be one the build takes (`PropAMMRegistryRule`, the rule its
/// registry path applies too): on Ethereum one that holds every builder lane to its block's own time,
/// `MAX_UPDATE_AGE` and `MAX_UPDATE_LEAD_TIME` zero, as a desk's cell reads its builder lane; on BNB Chain
/// zero, or a desk-lane adapter over the chain's update registry.
/// @param launcher_ The launcher, for good, under `_launcherOk`'s rule; never zero.
/// @param launcherCodehash The hash the launcher's code must have.
/// @param assetModule_ The protocol's asset module (slot 26), whose claim (`IAssetModule.familyOf`) makes a pair an
/// asset-module pair at `addPair`; zero for none; the owner replaces it (`setProtocolAssetModule`). Its code
/// is not checked here, as it may come after the front: until it has code no pair is added (`NotDue`).
function initialize(
address owner_,
address safe_,
address guardian_,
address source,
address launcher_,
bytes32 launcherCodehash,
address assetModule_
) external {
PropAMMStore.Layout storage $ = PropAMMStore.state();
if ($.ids >> 255 != 0 || owner_ == address(0) || safe_ == address(0) || guardian_ == address(0)) {
revert BadConfig();
}
$.ids = (1 << 255) | 1 | (uint256(1) << 32);
$.owner = owner_;
$.safe = safe_;
$.protocolGuardian = guardian_;
if (!_launcherOk(launcher_, launcherCodehash)) revert BadConfig();
$.launcher = launcher_;
$.assetModule = assetModule_;
// the build's quote assets are the list's first two ranks; the owner changes it from then on
address q0 = address(uint160(_hotWord(IFrontQuotes.QUOTE0.selector)));
address q1 = address(uint160(_hotWord(IFrontQuotes.QUOTE1.selector)));
if (q0 != address(0)) _setQuote($, q0, 1);
if (q1 != address(0) && q1 != q0) _setQuote($, q1, 2);
// a builder build's builder lanes come from its registry: on Ethereum one the rule takes, on BNB Chain zero or
// a relayer adapter (with zero, its desks land by their own pushes until the protocol owner installs one
// through the registry's path); a storage build's prices from its stored price lanes alone
uint256 kind = _laneKind();
if (
kind == LANE_STORAGE
? source != address(0)
: (kind == 0 || source != address(0)) && !PropAMMRegistryRule.ok(source, kind)
) revert BadConfig();
// and desks open from this call on (bit 163), for good
$.g0 = uint160(source) | (uint256(1) << 163);
}
/// @dev The launcher's rule at `initialize`: a launcher of the reviewed code (`codehash`, nonzero), so the checks
/// it holds are the reviewed ones, its pins this front's. No proxy, whose hash pins none of its logic, and no
/// account of 23 bytes or less (none, an EOA, or one delegated under EIP-7702, whose codehash is its
/// designator's). The authorities it builds must hash to this build's `AUTHORITY_CODEHASH`, so its launches
/// pass `confirmPool`; their guardian is each operator's own choice. A new launcher takes an upgrade.
function _launcherOk(address launcher_, bytes32 codehash) internal view returns (bool) {
return codehash != bytes32(0) && launcher_.codehash == codehash && launcher_.code.length > 23
&& ILauncherPin(launcher_).AUTHORITY_CODEHASH() == AUTHORITY_CODEHASH;
}
// ================================================================ owner (the timelock): its delayed changes
/// @notice The live listings on `pairId` among the ids [max(from, 1), from + maxScan), stopping at the next unused
/// id, in id order, and `next`, the first id not scanned (0 at the end): the discovery path for a pair's
/// listings, which no list holds (the pairs come from `PairAdded`). A listing fills only while bound to a
/// desk, so one born unbound, or unbound since, is listed too: `doorView` names its desk (0 for none).
function listingsOn(uint32 pairId, uint24 from, uint24 maxScan)
external
view
returns (uint24[] memory listings, uint24 next)
{
PropAMMStore.Layout storage $ = PropAMMStore.state();
uint256 stop = ($.ids >> 32) & W.M24;
uint256 end = uint256(from) + maxScan;
if (end > stop) end = stop;
uint256 i = from == 0 ? 1 : from;
listings = new uint24[](end > i ? end - i : 0);
uint256 n;
for (; i < end; ++i) {
uint256 s0 = $.pools[i].p0;
if (s0 & W.F_LIVE != 0 && s0.sPairId() == pairId) listings[n++] = uint24(i);
}
assembly ("memory-safe") {
mstore(listings, n)
}
if (end < stop) next = uint24(end);
}
/// @notice The owner (the timelock, after its delay) freezes the front's code for good: every later upgrade
/// reverts. The front stays upgradeable for fixes until then; registrations, pauses and every setter stay
/// after, only `upgradeToAndCall` stops. It cannot be undone.
function freezeCode() external {
PropAMMStore.Layout storage $ = _owner();
$.ids |= uint256(1) << 254;
emit CodeFrozen();
}
/// @notice Rotates the protocol guardian (the timelock, after its delay); the guardian being replaced can never
/// cancel it.
function setProtocolGuardian(address guardian_) external {
if (guardian_ == address(0)) revert BadConfig();
_owner().protocolGuardian = guardian_;
}
/// @notice Replaces the protocol's asset module (slot 26; the owner, the timelock), zero for none, so a new family
/// takes a new module and no upgrade. Only a pair added after it reads it (`addPair`): every pair already
/// added keeps for good the module it was bound to, or none (a plain pair it claims a token of, until the
/// owner retires it, `retirePair`), and its listings their own. Its code is not checked here: until it has
/// code no pair is added (`NotDue`). Logged as pair 0's (`AssetModuleSet`).
function setProtocolAssetModule(address module) external {
_owner().assetModule = module;
emit AssetModuleSet(0, 0, module);
}
/// @notice Lists `token` as a quote asset of rank `rank` (the owner, the timelock), 0 to delist it: only a pair
/// added after it reads the list (`addPair`), so every pair added before keeps its orientation and units
/// (a plain pair the list now orients otherwise, until the owner retires it, `retirePair`). Of two quote
/// assets the lower rank is the quote. A quote asset's ask board counts hundredths of it, so the list
/// holds tokens worth about one dollar.
function setQuoteAsset(address token, uint8 rank) external {
PropAMMStore.Layout storage $ = _owner();
if (token == address(0)) revert BadConfig();
_setQuote($, token, rank);
}
function _setQuote(PropAMMStore.Layout storage $, address token, uint256 rank) internal {
$.quoteRank[uint160(token)] = rank;
emit QuoteAssetSet(token, rank);
}
// ================================================================ anyone: pairs and price sources
/// @notice Adds the pair of `tokenA` and `tokenB` (anyone, at once) and returns its id, or returns the id of the
/// pair where it exists, writing and logging nothing. A pair's facts follow its two tokens, the quote list
/// and the protocol's asset module as they stand at the call, so they are the same whoever adds it then.
/// `retirePair` (the owner's) clears a plain pair that today's `addPair` would build differently, so the
/// next `addPair` rebuilds it. Every pair is of one kind: any number of listings, each reached by its id
/// and each binding its own price sources (`setSource`).
/// @dev - The tokens sorted are token0 and token1; zero or equal tokens are refused.
/// - The base and the quote follow the chain's quote assets as the list stands (`quoteRank`, slot 46; the
/// build's `QUOTE0` and `QUOTE1` its first two ranks, `setQuoteAsset`): the quote is the quote asset where
/// one token is one, the lower rank where both are (token0 the base at equal ranks); where neither is (a
/// volatile pair), the base is the token the asset module claims, else token0. Pair-word bit 10
/// (`PAIR_QUOTE_ASSET`) marks a quote asset, which sets the ask board's exponent.
/// - Each token's `decimals()` answers one word under `SOURCE_GAS`: the base's 6-18, the quote's at most 18.
/// The price unit is u = 24 + quote decimals - base decimals, so every pair's cross scale k is 12, and the
/// board exponents follow the decimals alone.
/// - Where the protocol's asset module is set (slot 26), no pair is added before it has code (`NotDue`), a
/// token it claims (`IAssetModule.familyOf` nonzero) is never the quote, and a base it claims makes the
/// pair an asset-module pair, bound for good to the module and the base's family (held to `_assetOk`),
/// which every quote and fill of it asks. A claim the caller's gas limit cut short reverts (`GasShort`), so
/// a short limit never adds a claimed base as a plain pair.
function addPair(address tokenA, address tokenB) external returns (uint32 pairId) {
PropAMMStore.Layout storage $ = _unlocked();
(address t0, address t1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
if (t0 == address(0) || t0 == t1) revert BadConfig();
bytes32 key = _pairKey(t0, t1);
uint256 have = $.pairIdOf[key];
if (have != 0) return uint32(have);
(address m, uint256 fam1, bool baseIs0, bool listedQ) = _sides($, t0, t1, 0);
(address base, address quoteT) = baseIs0 ? (t0, t1) : (t1, t0);
uint256 decB = _decimals(base);
uint256 decQ = _decimals(quoteT);
// keeps the anchor's price unit at most 10^48, so level prices fit the walk's arithmetic
if (decB < 6 || decB > 18 || decQ > 18) revert BadConfig();
uint256 asset;
if (m != address(0)) {
if (_familyOf(m, quoteT) != 0) revert BadConfig();
// a claimed token1 of a volatile pair is its base, asked above
uint256 fam = fam1 != 0 ? fam1 : _familyOf(m, base);
if (fam != 0) {
if (fam > 15 || !_assetOk(m, base, fam, 0)) revert BadConfig();
asset = uint160(m) | (fam << 160);
}
}
uint256 pw = 1 | (baseIs0 ? W.PAIR_BASE_IS_T0 : 0) | (listedQ ? W.PAIR_QUOTE_ASSET : 0)
| (asset != 0 ? W.PAIR_ASSET : 0) | (uint256(1) << 16) | (uint256(1) << 24) | ((24 + decQ - decB) << 96)
| ((decB - 6) << 112) | ((listedQ ? (decQ > 2 ? decQ - 2 : 0) : (decQ > 6 ? decQ - 6 : 0)) << 120)
| (decB << 176) | (decQ << 184);
uint256 ids = $.ids;
pairId = uint32(ids);
if (pairId == type(uint32).max) revert BadConfig();
$.ids = ids + 1;
// the fills read an asset-module pair's module and the pair word's facts from the word they resolve the pair by
$.pairIdOf[key] = uint256(pairId) | (asset << 32) | W.entryFacts(pw);
PropAMMStore.Pair storage pr = $.pairs[pairId];
pr.cfg = pw;
pr.token0 = t0;
pr.token1 = t1;
emit PairAdded(pairId, t0, t1, pw);
if (asset != 0) {
pr.asset = asset;
emit AssetModuleSet(pairId, 0, m);
}
}
/// @dev The sides the rules give the pair of token0 `t0` and token1 `t1` as they stand, `addPair`'s and
/// `retirePair`'s one reading of them: the protocol's asset module `m` (zero none; `NotDue` before it has
/// code), the family it claims token1 for (`fam1`: asked on a volatile pair, which it orients, and on every
/// pair where `need` is nonzero), whether the base is token0 and whether the quote is a quote asset. `need`
/// is the gas a claim is asked with in hand (`_claim`), zero for no such line.
function _sides(PropAMMStore.Layout storage $, address t0, address t1, uint256 need)
internal
view
returns (address m, uint256 fam1, bool baseIs0, bool listedQ)
{
uint256 ra = $.quoteRank[uint160(t0)];
uint256 rb = $.quoteRank[uint160(t1)];
(bool a, bool b) = (ra != 0, rb != 0);
m = $.assetModule;
if (m != address(0)) {
// nothing is added before the module exists, so no claimed base is ever added as a plain pair
if (m.code.length <= 23) revert NotDue();
// a volatile pair's claimed token is its base whatever the addresses' order
if (need != 0 || (!a && !b)) fam1 = _claim(m, t1, need);
}
// the base is the token that is no quote asset; of two, the higher rank (token0 at equal ranks); of none, the
// one the module claims, else token0
baseIs0 = a && b ? ra >= rb : (a || b ? !a : fam1 == 0);
listedQ = baseIs0 ? b : a;
}
/// @notice Retires a plain pair the rules no longer build as it stands (the owner, the timelock), so its tokens'
/// pair is none until anyone adds it anew (`addPair`, a new id, by the rules as they stand then, or
/// refused where they refuse): a pair added before the protocol's module claimed one of its tokens, or
/// before a quote asset's listing, no longer holds its tokens for good.
/// @dev - Retirable: a pair that is its tokens' current one and no asset-module pair, where the protocol's module
/// claims either token (`IAssetModule.familyOf` nonzero), or the quote list gives another base side or
/// another quote-asset bit than its pair word holds (`_sides`, `addPair`'s own reading).
/// - Refused (`BadConfig`): an id no pair took, a retired pair, an asset-module pair whatever the protocol's
/// module is now (`removeAssetModule` is that pair's exit), and a pair `addPair` would build the same. A
/// module set before its code is `NotDue`.
/// - Each claim is asked with `CLAIM_GAS` in hand (`GasShort` under it), so no limit of the caller's, the
/// timelock's executor included, starves a read inside the module and has its fallback counted as a
/// family; `_familyOf`'s own starvation rule holds beside it.
/// - The retired pair's record and its listings' records stay. Its listings fill no more on any path (a fill
/// resolves the pair from its tokens: `UnsupportedPair` until the pair is added anew, `NotLive` after), the
/// front holds nothing of theirs, their pools' own entries and exits never ask the front for the pair, and
/// their operators' and guardians' calls stand (`retirePool`, `freeze`).
/// - No pool or listing is born on a retired pair (`reservePool`, `reserveListing`, `addListing`:
/// `BadConfig`). A pool takes a further listing on the new pair (`addListing`).
/// - Retiring a pair strands the cheap lane of every pool whose first listing is on it (the pool's own
/// tokens 0 and 1): that listing stays the retired pair's for good, and the pool's cheap lane fills no
/// further listing of its tokens 0 and 1 (`PairNotTradable`). Those pools' LPs exit as ever (the pool's
/// `redeemProRata`, which calls no front), their listing deposits refund once retired, and their operators
/// open a new pool on the rebuilt pair.
function retirePair(uint32 pairId) external {
PropAMMStore.Layout storage $ = _owner();
PropAMMStore.Pair storage pr = $.pairs[pairId];
(address t0, address t1) = (pr.token0, pr.token1);
bytes32 key = _pairKey(t0, t1);
uint256 pw = pr.cfg;
// an id no pair took holds no word, an asset-module pair holds its asset word, and a retired pair's id is not
// its tokens' entry's (bits 0-31; the entry carries the facts above)
if (pw == 0 || pr.asset != 0 || ($.pairIdOf[key] & W.M32) != pairId) revert BadConfig();
(address m, uint256 fam1, bool baseIs0, bool listedQ) = _sides($, t0, t1, CLAIM_GAS);
if (
baseIs0 == (pw & W.PAIR_BASE_IS_T0 != 0) && listedQ == (pw & W.PAIR_QUOTE_ASSET != 0) && fam1 == 0
&& (m == address(0) || _claim(m, t0, CLAIM_GAS) == 0)
) revert BadConfig();
delete $.pairIdOf[key];
emit PairRetired(pairId);
}
/// @dev `_familyOf` asked with at least `need` gas in hand, `GasShort` under it: with `CLAIM_GAS`, every read the
/// module makes for the claim runs under its own cap, never under the caller's limit.
function _claim(address m, address t, uint256 need) internal view returns (uint256) {
if (gasleft() < need) revert GasShort();
return _familyOf(m, t);
}
/// @dev The family the asset module `m` claims token `t` for (`IAssetModule.familyOf`, 0 none), by a call given all
/// the gas, as the module caps its own reads: a call that fails or answers other than one word refuses
/// (`BadConfig`), and a failure or a zero answer the caller's limit starved is `GasShort` (`_starved`), so no
/// short limit makes a claimed token read as unclaimed.
function _familyOf(address m, address t) internal view returns (uint256 fam) {
uint256 g = gasleft();
bool ok;
assembly ("memory-safe") {
mstore(0, shl(224, 0x287156b5)) // familyOf(address)
mstore(4, t)
// Yul evaluates arguments right to left: the call first, in its own statement
let s := staticcall(gas(), m, 0, 0x24, 0, 0x20)
ok := and(s, eq(returndatasize(), 0x20))
fam := mload(0)
}
if (!ok || fam == 0) _starved(g);
if (!ok) revert BadConfig();
}
/// @dev Token `t`'s `decimals()`, one word under `SOURCE_GAS` (`_view`).
function _decimals(address t) internal view returns (uint256 d) {
(d,,) = _view(t, 0x313ce567, 0, 0x20); // decimals()
}
/// @notice Registers a price source (anyone, at once) under the next global id, which it returns: an entry written
/// once and never edited, which no listing reads until its operator binds it (`setSource`, or the
/// listing's birth), so a registration moves no live listing. Ids start at 1 and are never reused.
/// @dev `cfg`: [0-15] the base slot | [16-31] the quote slot (a stored price lane's; zero on a builder build) |
/// [32-63] the source's floor, millionths of a whole quote token (0 none): the least minimum fill of a PRINT
/// listing that binds it, on any pair | [64-87] zero | [88-95] its window, 500 ms steps, in
/// (0, `AGE_CEIL_MS`]: a fill takes its print while the print's earlier leg is at most that old on the age
/// clock | [96] the jump guard, a storage build's alone (`E_GUARD`): a fill reading the source asks its lane
/// for the fill's side over the prints the lane holds, a tied listing binds only such a source, and a listing
/// opts in by binding it (two sources on one lane, guarded and not, are two registrations) | [97-255] zero.
/// - A builder build deploys the source itself, from `code` (its creation code), by CREATE3 at salt
/// `bytes32(id)`, so a fill derives its address from the id and only this front places a source there
/// (`src` zero). The id and the entry are written first and the front's lock is held across the deploy, so
/// the constructor reaches nothing of the front's but its views (`Locked`).
/// - A storage build takes a stored price lane (`src`, `IPriceLane`, no code) that serves this front, runs on
/// this build's clock with a lead (`MAX_LEAD_MS`) at most this build's pull lead (`PULL_LEAD_MS`) and lists
/// both slots, nonzero and distinct, the quote's no equity feed (a jump threshold). A base slot of an
/// equity feed marks the entry (`E_EQUITY`): it binds on an asset-module pair, and only there. Each read is
/// one capped call of an exact size (`_view`). These are sanity checks of an honest lane: a hostile one
/// answers what it likes, and only the listings that bind it rely on it.
/// - No print is checked here: a source names no pair, and each fill holds its print to the pair's scale.
function registerSource(address src, uint256 cfg, bytes calldata code) external returns (uint32 id) {
PropAMMStore.Layout storage $ = _unlocked();
uint256 win = (cfg >> 88) & W.M8;
uint256 slots = cfg & W.M32;
if (cfg >> 97 != 0 || (cfg >> 64) & W.M24 != 0 || win == 0 || win * 500 > AGE_CEIL_MS) revert BadConfig();
uint256 ids = $.ids;
uint256 last = (ids >> 88) & W.M32;
if (last == W.M32) revert BadConfig();
id = uint32(last + 1);
uint256 e = (((cfg >> 32) & W.M32) << 192) | W.winBits(win) | (((cfg >> 96) & 1) << 247);
if (_laneKind() == LANE_STORAGE) {
uint256 sb = slots & W.M16;
uint256 sq = slots >> 16;
if (code.length != 0 || src.code.length == 0 || sb == 0 || sq == 0 || sb == sq) revert BadConfig();
// the hot implementation's own clock and pull lead, read through the proxy
PropAMMClock.Timing memory c = IFrontClock(address(this)).clock();
(uint256 m0, uint256 b0, uint256 ms0) = _view(src, IPriceLane.clockConfig.selector, 0, 0x60);
(uint256 reader,,) = _view(src, IPriceLane.isReader.selector, uint160(address(this)), 0x20);
(uint256 lead,,) = _view(src, IPriceLane.MAX_LEAD_MS.selector, 0, 0x20);
// an unlisted slot fails its read (`BadConfig`); an equity feed is a base leg alone
(uint256 jq,,) = _view(src, IPriceLane.jumpsOf.selector, sq, 0x40);
if (
reader != 1 || m0 != c.clockMode || b0 != c.clockBlock || ms0 != c.clockMs || lead > c.pullLeadMs
|| jq != 0
) revert BadConfig();
(uint256 jb,,) = _view(src, IPriceLane.jumpsOf.selector, sb, 0x40);
if (jb != 0) e |= W.E_EQUITY;
$.ids = ids + (uint256(1) << 88);
$.sources[id] = e | uint160(src) | (slots << 160) | W.E_LANE;
} else {
if (src != address(0) || slots != 0 || code.length == 0 || cfg >> 96 != 0) revert BadConfig();
src = CREATE3.predictDeterministicAddress(bytes32(uint256(id)));
// effects first: the id and the entry stand before the registrant's code runs, under the front's lock
$.ids = ids + (uint256(1) << 88);
$.sources[id] = e | uint160(src);
PropAMMStore.lock();
CREATE3.deployDeterministic(code, bytes32(uint256(id)));
PropAMMStore.unlock();
}
emit SourceRegistered(id, src, msg.sender, cfg);
}
// ================================================================ internals
/// @dev The state, with the front unlocked and the caller its owner, the timelock.
function _owner() internal view returns (PropAMMStore.Layout storage $) {
$ = _unlocked();
if (msg.sender != $.owner) revert Unauthorized();
}
/// @dev A one-word getter of the hot implementation, read through the proxy.
function _hotWord(bytes4 sel) internal view returns (uint256 v) {
assembly ("memory-safe") {
mstore(0, sel)
if iszero(staticcall(gas(), address(), 0, 4, 0, 0x20)) { revert(0, 0) }
v := mload(0)
}
}
}
/// @notice What the builder builds' cold admin parts (Ethereum, BNB Chain) add: a desk's landing through the
/// front's registry, the listings' leases and the registry's own 48 h path, reached as every cold call is
/// (`PropAMMAdmin.COLD`). The storage build's cold part has none of them, so there each refuses as a selector
/// no part serves.
abstract contract PropAMMAdminColdBuilder is PropAMMAdminCold {
/// @param ageCeilMs `AGE_CEIL_MS`.
/// @param authorityCodehash `AUTHORITY_CODEHASH`.
constructor(uint256 ageCeilMs, bytes32 authorityCodehash) PropAMMAdminCold(ageCeilMs, authorityCodehash) {}
/// @notice The desk's cold key sets the registry its cell lands through: zero (its own push only) or the front's
/// registry, which every read of the cell passes it: Ethereum's priority-update registry, or on BNB Chain a
/// relayer adapter where the front has one (with none, the desks land by their own pushes). An adapter the
/// protocol owner installs through the registry's 48 h path reaches every desk that points here with no
/// upgrade. After a registry change the cell reads no builder lane until it is pointed at the new one; its
/// own push still lands.
function setDeskLanding(uint32 desk, address registry) external {
PropAMMStore.Layout storage $ = _unlocked();
PropAMMStore.Desk storage r = $.desks[desk];
_coldKey(r);
if (registry != address(0) && registry != address(uint160($.g0))) revert BadConfig();
_cellOp(_deskCell(desk), 5, uint160(registry));
emit DeskLanding(desk, registry);
}
// ================================================================ the listings' leases
/// @notice Anyone: lets the listing's live source (its primary, or its backup once the primary is darkened; P2,
/// `price`) honour a trust it caches for one more day (P2 bits 200-231, unix s), once that source
/// confirms it by its vendor's own verifier (`IPriceCheck.cacheValid`, asked under `SOURCE_GAS`: exactly
/// one word, true). `BadConfig` on an unpriced or dark listing and on any other answer, held to the
/// starvation rule (`_starved`). A new binding of the listing's sources (`setSource`, `darkenSource`)
/// starts with no lease, so the next renewal asks the source it moved to. The lease binds a source that
/// caches a trust alone, and a source's code decides what it honours. No Pyth source of this front caches
/// one: each passes every update to Pyth's verifier (`verifyUpdate`), a posted one at its post and a
/// carried one at the fill, answers `cacheValid` true and reads the same with the lease or without it, so
/// a lease, its lapse and its cut change no fill on such a source.
function refreshLease(uint24 listing) external {
PropAMMStore.Pool storage r = _unlocked().pools[listing];
uint256 l = r.price;
// the live source's derived address, its lease flag aside: none on an unpriced or dark listing
(uint256 src,,) = _srcOf(l, true, 0);
if (src == 0) revert BadConfig();
bool ok;
uint256 g = gasleft();
assembly ("memory-safe") {
mstore(0, shl(224, 0xe61db1fa)) // cacheValid()
// Yul evaluates arguments right to left: the call first, in its own statement
ok := staticcall(SOURCE_GAS, and(src, 0xffffffffffffffffffffffffffffffffffffffff), 0, 4, 0, 0x20)
ok := and(ok, and(eq(returndatasize(), 0x20), eq(mload(0), 1)))
}
if (!ok) {
_starved(g);
revert BadConfig();
}
uint256 until = block.timestamp + 1 days;
r.price = (l & ~(uint256(W.M32) << 200)) | (until << 200);
emit LeaseSet(listing, uint32(until), msg.sender);
}
/// @notice Ends a listing's lease at once (stop-only): the protocol guardian, the protocol owner, or the listing's
/// pool's operator or guardian (`_stopRole`); or with `listing` 0 every listing's (g0 bit 161), the
/// protocol guardian or the protocol owner alone, until the protocol owner lifts that cut
/// (`liftLeaseCut`), which nothing else clears, a registry change included. A listing's own cut stands
/// until a renewal (`refreshLease`), which anyone may make once its live source confirms its trust again.
/// A source that caches a trust then honours none of it. A Pyth source of this front caches none and
/// reads the same after the cut: every update it reads has passed Pyth's verifier. `NotLive` for a
/// listing never reserved.
function cutLease(uint24 listing) external {
PropAMMStore.Layout storage $ = _unlocked();
bool prot = msg.sender == $.protocolGuardian || msg.sender == $.safe;
if (listing == 0) {
if (!prot) revert Unauthorized();
$.g0 |= uint256(1) << 161;
} else {
PropAMMStore.Pool storage r = $.pools[listing];
uint256 s0 = r.p0;
if (s0 == 0) revert NotLive();
if (!prot && !_stopRole(address(uint160(s0)))) revert Unauthorized();
r.price &= ~(uint256(W.M32) << 200);
}
emit LeaseSet(listing, 0, msg.sender);
}
/// @notice The protocol owner lifts the cut of every lease (`cutLease(0)`); each listing's own lease then counts
/// again, as it stands, a lease renewed before the revocation the cut answered and never confirmed since
/// among them: the protocol owner first cuts each listing concerned (`cutLease(listing)`), or waits for
/// its lease to lapse.
function liftLeaseCut() external {
PropAMMStore.Layout storage $ = _safe();
$.g0 &= ~(uint256(1) << 161);
emit LeaseSet(0, type(uint32).max, msg.sender);
}
// ================================================================ the registry's path
/// @notice The registry's only path: a new registry after 48 h, the protocol guardian free to cancel; once it
/// executes, every fill stays paused until the protocol owner has reviewed the new registry and unpauses (a
/// registry can feed the desks' cells any builder lane). Anyone executes it within the execution window of
/// its due time; later it has lapsed, and the protocol owner schedules it again or cancels it. The registry
/// must be one the build takes, as `initialize` requires. A new schedule replaces the one standing, its
/// delay starting again.
function scheduleRegistry(address registry) external {
PropAMMStore.Layout storage $ = _safe();
if (!PropAMMRegistryRule.ok(registry, _laneKind())) revert BadConfig();
uint256 due = block.timestamp + PropAMMRegistryRule.REGISTRY_DELAY;
$.pendingRegistry = uint160(registry) | (due << 160);
emit RegistryScheduled(registry, uint64(due));
}
/// @notice The protocol owner or the protocol guardian drops the scheduled registry (`NotPending` where none is).
function cancelRegistry() external {
PropAMMStore.Layout storage $ = _unlocked();
if (msg.sender != $.safe && msg.sender != $.protocolGuardian) revert Unauthorized();
if ($.pendingRegistry == 0) revert NotPending();
$.pendingRegistry = 0;
emit RegistryCancelled(msg.sender);
}
/// @notice Installs the scheduled registry once due, within the execution window, and pauses every fill until the
/// protocol owner has reviewed it (`unpauseAll`). The build's rule (`PropAMMRegistryRule.ok`) is read again
/// here: a registry whose answers moved since `scheduleRegistry` is refused, and the current one stays
/// live. `unpauseAll` reads nothing: no point check binds a registry that can change its answers later, so
/// the protocol owner's review (immutable answers, no upgrade path) is the gate.
function executeRegistry() external {
PropAMMStore.Layout storage $ = _unlocked();
uint256 pr = $.pendingRegistry;
if (pr == 0) revert NotPending();
DelayLib.Phase p = DelayLib.phase(pr >> 160, PropAMMRegistryRule.EXECUTION_WINDOW_SEC);
if (p == DelayLib.Phase.Waiting) revert NotDue();
if (p != DelayLib.Phase.Due) revert Lapsed();
if (!PropAMMRegistryRule.ok(address(uint160(pr)), _laneKind())) revert BadConfig();
// the registry and the pause; the flags above them (the cut of every lease, bit 161, which only
// `liftLeaseCut` lifts, and the desks' opening, bit 163, set at `initialize`) stand
$.g0 = (($.g0 >> 161) << 161) | uint160(pr) | (1 << 160);
$.pendingRegistry = 0;
emit RegistrySet(address(uint160(pr)));
emit AllPaused(address(this));
}
}
/// @notice Ethereum's builder build's cold admin part, which `PropAMMAdminRegistry` creates.
contract PropAMMAdminColdRegistry is PropAMMAdminColdBuilder {
/// @param ageCeilMs `AGE_CEIL_MS`.
/// @param authorityCodehash `AUTHORITY_CODEHASH`.
constructor(uint256 ageCeilMs, bytes32 authorityCodehash)
PropAMMAdminColdBuilder(ageCeilMs, authorityCodehash)
{}
/// @dev `LANE_KIND` 0: Ethereum's builder build.
function _laneKind() internal pure override returns (uint256) {
return 0;
}
}
/// @notice The storage build's cold admin part, which `PropAMMAdminStorage` creates.
contract PropAMMAdminColdStorage is PropAMMAdminCold {
/// @param ageCeilMs `AGE_CEIL_MS`.
/// @param authorityCodehash `AUTHORITY_CODEHASH`.
constructor(uint256 ageCeilMs, bytes32 authorityCodehash) PropAMMAdminCold(ageCeilMs, authorityCodehash) {}
/// @dev `LANE_KIND` 1: the storage build.
function _laneKind() internal pure override returns (uint256) {
return 1;
}
}
/// @notice BNB Chain's builder build's cold admin part, which `PropAMMAdminBnb` creates.
contract PropAMMAdminColdBnb is PropAMMAdminColdBuilder {
/// @param ageCeilMs `AGE_CEIL_MS`.
/// @param authorityCodehash `AUTHORITY_CODEHASH`.
constructor(uint256 ageCeilMs, bytes32 authorityCodehash)
PropAMMAdminColdBuilder(ageCeilMs, authorityCodehash)
{}
/// @dev `LANE_KIND` 2: BNB Chain's builder build.
function _laneKind() internal pure override returns (uint256) {
return 2;
}
}
lib/openzeppelin-contracts-compat/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
lib/openzeppelin-contracts-compat/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10**64) {
value /= 10**64;
result += 64;
}
if (value >= 10**32) {
value /= 10**32;
result += 32;
}
if (value >= 10**16) {
value /= 10**16;
result += 16;
}
if (value >= 10**8) {
value /= 10**8;
result += 8;
}
if (value >= 10**4) {
value /= 10**4;
result += 4;
}
if (value >= 10**2) {
value /= 10**2;
result += 2;
}
if (value >= 10**1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
lib/solady/src/utils/CREATE3.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Deterministic deployments agnostic to the initialization code.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/CREATE3.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/CREATE3.sol)
/// @author Modified from 0xSequence (https://github.com/0xSequence/create3/blob/master/contracts/Create3.sol)
library CREATE3 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unable to deploy the contract.
error DeploymentFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTECODE CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/**
* -------------------------------------------------------------------+
* Opcode | Mnemonic | Stack | Memory |
* -------------------------------------------------------------------|
* 36 | CALLDATASIZE | cds | |
* 3d | RETURNDATASIZE | 0 cds | |
* 3d | RETURNDATASIZE | 0 0 cds | |
* 37 | CALLDATACOPY | | [0..cds): calldata |
* 36 | CALLDATASIZE | cds | [0..cds): calldata |
* 3d | RETURNDATASIZE | 0 cds | [0..cds): calldata |
* 34 | CALLVALUE | value 0 cds | [0..cds): calldata |
* f0 | CREATE | newContract | [0..cds): calldata |
* -------------------------------------------------------------------|
* Opcode | Mnemonic | Stack | Memory |
* -------------------------------------------------------------------|
* 67 bytecode | PUSH8 bytecode | bytecode | |
* 3d | RETURNDATASIZE | 0 bytecode | |
* 52 | MSTORE | | [0..8): bytecode |
* 60 0x08 | PUSH1 0x08 | 0x08 | [0..8): bytecode |
* 60 0x18 | PUSH1 0x18 | 0x18 0x08 | [0..8): bytecode |
* f3 | RETURN | | [0..8): bytecode |
* -------------------------------------------------------------------+
*/
/// @dev The proxy initialization code.
uint256 private constant _PROXY_INITCODE = 0x67363d3d37363d34f03d5260086018f3;
/// @dev Hash of the `_PROXY_INITCODE`.
/// Equivalent to `keccak256(abi.encodePacked(hex"67363d3d37363d34f03d5260086018f3"))`.
bytes32 internal constant PROXY_INITCODE_HASH =
0x21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CREATE3 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Deploys `initCode` deterministically with a `salt`.
/// Returns the deterministic address of the deployed contract,
/// which solely depends on `salt`.
function deployDeterministic(bytes memory initCode, bytes32 salt)
internal
returns (address deployed)
{
deployed = deployDeterministic(0, initCode, salt);
}
/// @dev Deploys `initCode` deterministically with a `salt`.
/// The deployed contract is funded with `value` (in wei) ETH.
/// Returns the deterministic address of the deployed contract,
/// which solely depends on `salt`.
function deployDeterministic(uint256 value, bytes memory initCode, bytes32 salt)
internal
returns (address deployed)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, _PROXY_INITCODE) // Store the `_PROXY_INITCODE`.
let proxy := create2(0, 0x10, 0x10, salt)
if iszero(proxy) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, proxy) // Store the proxy's address.
// 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
// 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
mstore(0x00, 0xd694)
mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
deployed := keccak256(0x1e, 0x17)
if iszero(
mul( // The arguments of `mul` are evaluated last to first.
extcodesize(deployed),
call(gas(), proxy, value, add(initCode, 0x20), mload(initCode), 0x00, 0x00)
)
) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns the deterministic address for `salt`.
function predictDeterministicAddress(bytes32 salt) internal view returns (address deployed) {
deployed = predictDeterministicAddress(salt, address(this));
}
/// @dev Returns the deterministic address for `salt` with `deployer`.
function predictDeterministicAddress(bytes32 salt, address deployer)
internal
pure
returns (address deployed)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, deployer) // Store `deployer`.
mstore8(0x0b, 0xff) // Store the prefix.
mstore(0x20, salt) // Store the salt.
mstore(0x40, PROXY_INITCODE_HASH) // Store the bytecode hash.
mstore(0x14, keccak256(0x0b, 0x55)) // Store the proxy's address.
mstore(0x40, m) // Restore the free memory pointer.
// 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
// 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
mstore(0x00, 0xd694)
mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
deployed := keccak256(0x1e, 0x17)
}
}
}
src/interfaces/core/IEverlongCore.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice A pool's authority record as the pool and its periphery read it: `EverlongCore`, or `DelayedAuthority`,
/// which answers the same getters with delays on the owner and the guardian. The pool reads the roles from it
/// on each call, so a change there applies to the pool at once.
interface IEverlongCore {
/// @notice The pool's curator.
function owner() external view returns (address);
/// @notice The pool's guardian; zero for none.
function guardian() external view returns (address);
/// @notice The pool's keeper; zero for none.
function keeper() external view returns (address);
/// @notice The receiver of the curator's performance fee, never zero.
function feeReceiver() external view returns (address);
}
src/interfaces/core/flamm/IFLAMM.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {PoolContext} from "src/interfaces/core/flamm/IFLAMMHooks.sol";
import {PairRequest} from "src/interfaces/core/flamm/IPairHook.sol";
/// @notice The external surface of a pool that periphery, the Router, the Factory and the tranches rely on, and the
/// entries `FLAMMFront` serves or routes (`swap`, `previewSwap`, `pairRequest`, `switches`, `paused`,
/// `tokenConfig`, `pairConfig`, `position`, `collateralReserve`, `pending`, `poke`, `recenter`). The pool lists
/// tokens: token 0 is `asset()`, the share and NAV unit, and token 1 is `loanAsset()`, the numeraire and the
/// hook pair's quote; its credit pairs each borrow a debt token against a collateral token. Entries no contract
/// calls through it (the hook-set ceremony and its view, the governance setters, the admissions,
/// `maintainCollateral`, `maintain`, `emergency`, `executePerformanceFee`) are declared and documented on
/// `FLAMM` alone, and those `FLAMM`'s fallback hands to `FLAMMFloatLib` (the cheap lane's settings,
/// `collectSpreadFee`, the float actions) on that library. The fences' entries are on `IFLAMMFence`, the
/// front's on `IFLAMMLane`.
/// @dev FLAMM stands for financed-leg automated market maker. Who calls whom:
/// - `FLAMMFactory` creates pools for anyone, is their beacon and constructs the one shared `MMRouter`.
/// - A pool is a `FLAMMProxy` over `FLAMMFront`, the Factory's implementation, which hands every entry it does
/// not serve to `FLAMM` and its libraries. The pool keeps the custody, the shares and the pool book.
/// - `MMRouter` (`IMMRouter`) keeps each pool's pairs and venues, takes each pool's calls for its own alone and
/// drives the pool's financing accounts. It never holds a token.
/// - A financing account (`IFinancingAccount`) carries a pool's legs at one lender, a venue kind being one
/// lender's code. The Router calls its normal path and its pool calls the emergency path.
/// - `PriceFeed` (`IPriceFeed`) serves the checked USD prices the pool reads; the Router reads no feed, but takes
/// each price from the pool's call (`usd`).
/// - `core()` (`IEverlongCore`: an `EverlongCore`, or a `DelayedAuthority`, which puts delays on its owner and
/// guardian) names the pool's roles.
/// - The swap hook (`hooks().hook`: `IPairHook`, `IRecenterHook`) prices every pair but a pair hook's; a pair hook
/// (the `setPairHook` slot) prices its own pairs; the controller (`hooks().controller`) holds a routing role.
/// - A PropAMM front (`IPropAMMFront`) is the swap hook of a pool with a cheap lane, for the pool's life, and
/// settles fills through `IFLAMMLane`. The doors in `src/periphery/door` take routers' fills to the front.
///
/// Terms:
/// - Hook pair: tokens 0 and 1, {asset} and {loanAsset}.
/// - Credit pair: a debt token borrowed against a collateral token at venues ({PairConfig}, `IMMRouter`).
/// - Cheap lane: a fill the front prices and the pool settles from tracked custody, never touching the lender
/// (`IFLAMMLane`), on a pool whose front opened it at birth and whose curator set `FEATURE_CHEAP_FILL`. A pool's
/// cheap lane is on from that birth for good (`SWAP_LANE`), whatever `FEATURE_CHEAP_FILL` says; that bit opens
/// and stops its fills.
/// - Credit path: the pool's own {swap} through the swap hook.
/// - The four legs of a token ({position}): held (custody, unlent), supplied (lent at a venue), posted (collateral
/// at a venue) and owed (borrowed from a venue).
/// - Curator: the owner of `core()`, the role `src/propamm` and `src/periphery/door` call the operator.
/// - Guardian: `core()`'s second key, which cancels scheduled changes, tightens settings and calls the emergency
/// path (`FLAMM`).
/// - Keeper: `core()`'s operations key, which moves dials and runs maintenance beside the curator (`FLAMM`).
/// - D: `governanceDelaySec`, the pool's delay, written once at birth ({switches}).
/// - `EverlongHook`: the canonical swap hook, bound to one pool, which carries the Everlong curve and the pool's
/// leverage quote.
/// - Venue fence and price fence are unrelated: core's fence sets a venue or a token's custody apart from the pool
/// (`IFLAMMFence`); the front's price fence holds a fill's levels within a one-sided limit taken from the price
/// its listing is fenced to, where the listing has one (`IPropAMMFront`).
interface IFLAMM is IERC20 {
/// @notice The custody maintenance moves. DO NOT REORDER: the values are part of the ABI; a new member needs a
/// branch in `FLAMMMaintainLib.maintain`.
enum MaintainKind {
TopUp,
Release,
Refinance,
MigrateSupply,
/// `Refinance` with the caller lending what custody cannot bridge: the caller needs an allowance to the pool
/// for this transaction, for at most the move, and is repaid in full in it (`FLAMMMaintainLib.maintain`).
FundedRefinance
}
/// @notice The emergency path's moves. DO NOT REORDER: the values are part of the ABI; a new member needs a
/// branch in `FLAMMMaintainLib.emergency`.
enum EmergencyKind {
Repay,
/// At a fenced venue the post is the curator's alone and pulls part of it from the caller in the venue's
/// collateral token, within the caller's allowance to the pool (`FLAMMMaintainLib.emergency`).
TopUp,
WithdrawSupplied,
WithdrawCollateral
}
/// @dev The pool's hooks: the swap hook, one contract in every pricing role (it prices every pair but a pair
/// hook's, and its own fee, and recenters the pool book it prices), and the optional controller.
struct HookSet {
address hook; // the swap hook (`IPairHook`), which prices every pair but a pair hook's
address controller; // routing role (`setPriorities`, `maintain`, `recenter`, `unwindFence`); zero: none
}
/// @notice A venue of credit pair `pair` (the Router's pair index), as `FLAMM.addVenue` admits it.
struct VenueInit {
uint8 kind; // the venue kind, one lender
uint8 pair; // the Router's pair index
bytes venueParams; // the kind's parameters (`IMMRouter.addVenue`)
bool borrowEnabled; // the venue's borrow switch
bool supplyEnabled; // the venue's supply switch
uint128 debtCap; // the venue's debt cap, debt-token base units; zero: none
uint128 supplyCap; // the venue's supply cap, debt-token base units; zero: none
uint64 maxBorrowRateWad; // the highest borrow rate a borrow there may leave, per second, WAD; zero: none
}
/// @notice One venue's leg of a pro-rata flow, in the venue's own tokens: `collateral` of its pair's collateral
/// token, `owed` and `supplied` of its debt token.
struct VenueLeg {
uint16 id; // the venue's slot at the Router
uint8 pair; // its credit pair's index
uint256 collateral; // base units
uint256 owed; // base units
uint256 supplied; // base units
}
/// @notice One listed token: its binding, its swap policy, its lending policy and its custody. `partner` is the
/// token whose collateral backs a debt in this one, the collateral of the credit pair `pairId` that owes
/// it (`255`: no live pair owes it; `254`: two or more do, `pairId` the first of them); `debtFree` its
/// proven debt-free flag. `pairId` means something only while `partner` is not `255`: it reads zero for a
/// token no pair ever owed, and keeps the retired pair's index after `FLAMMAdmitLib.retirePair`.
struct TokenConfig {
address token; // the token's address
uint8 decimals; // at most 18
uint64 swapPriceBandWad; // how far a fill may stray from the feed, WAD; token 1's is the market band
uint64 feeFloorWad; // the least fee rate a swap of this token takes, WAD
uint256 maxSwapNotional; // the most of it one swap takes or pays, base units; zero: none
uint256 reserveTarget; // the custody a swap keeps unlent and a refill brings back, base units
uint256 minSupplyBatch; // the least surplus over the target a swap lends, base units; `max`: it lends none
uint256 held; // the custody tracked, the fee kept for the protocol included, base units
uint8 partner; // see above
uint8 pairId; // see above
bool debtFree; // a position read showed no unfenced venue lending it to the pool; a draw clears it
}
/// @notice One credit pair, which borrows `debt` against `coll`: its two dials (the LTV, which is the Router's pin,
/// and the credit `phiWad` of incoming collateral when a borrow's room is sized), the room's shave, the
/// dials' write-once envelope, step, structural floor and cooldown, its last dial move, the pool's mirror
/// of its borrow switch and whether it is live (not retired). The credit is at most `1 / (1 + band)` of the
/// pair's tokens' tighter swap band, as a fill inside the band may bring an input worth as little as that
/// share of its output: the admission caps the dial there, a dial move inside the envelope stores at most
/// that as the band stands (never below the envelope's floor), and a draw's or a rotation's room credits no
/// more however the band moves since.
struct PairConfig {
uint8 coll; // the collateral token's index
uint8 debt; // the debt token's index
uint64 ltvWad; // the LTV dial, the Router's pin, WAD
uint64 phiWad; // the credit dial, WAD
uint64 roomEpsilonWad; // the share taken off the room once the credit has lifted it, WAD
uint64 ltvMinWad; // the LTV dial's floor, WAD, write-once
uint64 ltvMaxWad; // the LTV dial's ceiling, WAD, write-once
uint64 phiMinWad; // the credit dial's floor, WAD, write-once
uint64 phiMaxWad; // the credit dial's ceiling, WAD, write-once
uint64 ltvMaxStepWad; // the most one raise moves the LTV dial, WAD
uint64 minStructDistWad; // the least `1 - ltv / lltv` a raise of the LTV leaves, WAD
uint32 ltvCooldownSec; // the seconds a dial move waits after the last one
uint48 lastDialMoveTs; // when the dials last moved, unix seconds; the pair's admission counts as a move
bool borrowOff; // the pool's mirror of the Router's borrow switch for the pair: true when it is off
bool live; // false once retired, for good
}
/// @notice The pool's caps, guards and fee policy in one read.
struct Limits {
uint32 maxPriceAgeSec; // the oldest USD print a swap past the hook pair prices on, seconds; zero: none trades
uint64 feeFloorWad; // the pool's fee floor, WAD; a swap takes the highest of this and its two tokens'
uint64 feeCapWad; // the highest fee rate (`feeWad`) a hook's fill may report, WAD; not a bound on its `feeOut`
/// @dev The curator's rate, charged on the gain over the high-water mark at the pre-mint share price, in
/// minted shares, so the receiver realises bp of the gain diluted by the mint; the rest stays with LPs,
/// never recharged. A rise waits `governanceDelaySec`, and none lands while the pool has no market band; a
/// cut applies at once.
uint16 performanceFeeBp;
/// @dev The high-water mark of the unrealised NAV per share (pool-asset base units per share, WAD), rounded
/// down from the pool's own fee mark, which it carries at 18 decimals of par whatever the pool asset.
/// Seeded at bootstrap and only ever raised, also while both rates are 0, so a fee armed later starts from
/// it. A charged gain is never refunded. On a pool whose cheap lane is on and whose deposit basket is set
/// (`basketTokens()`, every token's entry), it is instead the high-water mark of NAV per share against the
/// basket's value at the same prices, a WAD ratio (the pool carries it times the share scale, as it
/// carries every fee mark): each record of the basket restarts it at 1e18, and only gains above it raise
/// it.
uint128 peakSharePriceWad;
uint16 maxPerformanceFeeBp; // the curator rate's cap, bp, write-once
/// @dev The protocol's rate, charged on the same gain beside the curator's, in shares minted to the Factory's
/// `protocolFeeReceiver`; the Factory sets it, a rise after the longer of its `UPGRADE_DELAY` and ten days
/// and, once the pool is seeded, only while it has a market band.
uint16 protocolFeeBp;
/// @dev The curator's scheduled rise and when anyone may execute it (`executePerformanceFee`); zero when none.
uint16 pendingPerformanceFeeBp;
uint48 performanceFeeExecutableAt; // unix seconds
/// @dev The supply `FLAMM.mintProRata` may lift the pool to, in shares (zero closes that entry).
uint256 mintProRataCap;
}
// identity
/// @notice Token 0: the pool asset, the share and NAV unit.
function asset() external view returns (address);
/// @notice Token 1: the numeraire and the token every periphery binding uses.
function loanAsset() external view returns (address);
/// @notice The tokens the pool lists, the pool asset included.
function tokenCount() external view returns (uint256);
/// @notice The credit pairs the pool holds, retired ones included.
function pairCount() external view returns (uint256);
/// @notice Token `t`'s record ({TokenConfig}); reverts `BadTokenIndex` past the list.
function tokenConfig(uint8 t) external view returns (TokenConfig memory);
/// @notice Pair `p`'s record ({PairConfig}); reverts `BadPairIndex` past the list.
function pairConfig(uint8 p) external view returns (PairConfig memory);
/// @notice Token `t`'s collateral reserve rule (`FLAMMPolicyLib.setCollateralReserve`); `BadTokenIndex` past the list.
/// @param t The token's index.
/// @return venueId The venue the rule names, zero while it is off.
/// @return reserve The custody a release refills up to, in token `t`'s base units, zero while the rule is off.
function collateralReserve(uint8 t) external view returns (uint16 venueId, uint128 reserve);
/// @notice When the pending table's entry `h` may execute, `h` being the keccak256 of the scheduled call (its
/// selector and arguments abi-encoded as one tuple): an admission (`FLAMM.addToken`, `addPair`,
/// `addVenue`), a fence's delayed call (`writeOff`, `abandonFence`, `liftFence`, `liftToken`), the pair
/// hook's installation, a fee floor's cut (`setFeeBounds`, `setTokenConfig`) on a pool whose cheap lane is
/// off, and a cap's raise on one whose lane is on. Zero when none, as once its window has lapsed
/// (past `dueAt` by `governanceDelaySec` or one day, whichever is longer): the identical call then schedules it again.
function pending(bytes32 h) external view returns (uint48 dueAt);
/// @notice The money-market Router (`IMMRouter`) that holds the pool's venues.
function router() external view returns (address);
/// @notice The USD price feed (`IPriceFeed`).
function priceFeed() external view returns (address);
/// @notice The pool's roles (`IEverlongCore`): its curator, guardian, keeper and fee receiver.
function core() external view returns (address);
/// @notice The allowlist that decides who may receive an entry's shares (`IDepositAllowlist`); zero: anyone.
function depositAllowlist() external view returns (address);
/// @notice The Factory, the pool's beacon.
function factory() external view returns (address);
/// @notice The pool's hooks ({HookSet}).
function hooks() external view returns (HookSet memory);
/// @notice Whether the pool is paused (`FLAMM.setPaused`).
function paused() external view returns (bool);
// facts
/// @notice Token `t`'s four legs, as the Router's `book` recognizes them (a retired venue holds none, and a fenced
/// one's stay out of that `book`); reverts `BadTokenIndex` past the list.
/// @dev `held` is less than {tokenConfig}'s `held` by the fee kept for the protocol, which that record counts.
/// @param t The token's index.
/// @return held The custody the pool owns, the fee kept for the protocol left out, in base units.
/// @return supplied What the pool lends at its venues, in base units.
/// @return posted What the pool posts as collateral at its venues, in base units.
/// @return owed What the pool owes at its venues, in base units.
function position(uint8 t) external view returns (uint256 held, uint256 supplied, uint256 posted, uint256 owed);
/// @notice NAV in pool-asset base units at the pool's checked prices: every token's held, supplied and posted legs
/// less its owed one, the pool asset at par and every other token at its checked price, holdings rounded
/// down and debt up, never below zero.
/// @dev Reverts:
/// - `PriceUnchecked` while a token with a position has an unchecked feed.
/// - `PriceUnchecked`, while a fee rate is on and the pool has a band, while the fee mark cannot read, held or
/// not: a cheap-lane pool's deposit basket needs token 1's price, and a pending record of what exits
/// forfeited at frozen venue marks needs its tokens' prices (so nothing priced at NAV trades a fee the skim
/// could not charge).
/// - `VenueFrozen` while a live venue holding a position allows no action, its kind one that can refuse one
/// (`CAP_ACTION_GATES`): such a kind answers a frozen venue mark while its protocol cannot be read
/// (`IFinancingAccount`). A lender that refuses every action while still readable reads the same way, which
/// is conservative. No flow enters at its figures (`VenueFrozen`), and an exit forfeits its slice of such a
/// venue that owes nothing ({redeemProRata}), which no skim counts as performance.
function totalAssets() external view returns (uint256);
/// @notice The pool-wide policy ({Limits}); per-token and per-pair policy live on {tokenConfig} and {pairConfig}.
function limits() external view returns (Limits memory);
/// @notice A cheap-lane pool's deposit basket per 1e18 shares: its first two entries, the pool asset's net legs and
/// token 1's (`FLAMMFloatLib.basket`); zero on any other pool. A basket holds every token's entry
/// ({basketTokens}), against whose whole value `Limits.peakSharePriceWad` is NAV per share.
/// @return basketPool The pool asset's entry, in its base units.
/// @return basketLoan Token 1's entry, in its base units.
function basket() external view returns (uint128 basketPool, uint128 basketLoan);
/// @notice A cheap-lane pool's deposit basket per 1e18 shares, one entry per listed token in its base units
/// (`FLAMMFloatLib.basketTokens`): where it is set, `Limits.peakSharePriceWad` is NAV per share against the
/// value of every entry; all zero on any other pool.
function basketTokens() external view returns (uint256[] memory entries);
/// @notice The venue slots the pool's walks skip, bit `i` for slot `i`: those it has retired, cleared when an
/// admission reuses the slot, and those it has fenced, cleared at the fence's lift (`IFLAMMFence`, whose
/// `fencedVenues` tells the fenced apart). No walk of the pool's venues calls the Router for one, as a
/// retired venue's lender may have stopped answering and a fenced one's takes no leg.
function retiredVenues() external view returns (uint256);
// ERC-4626 conversions at NAV, excluding fees as ERC-4626 asks: at the supply before a pending performance fee is
// minted, which the pro-rata previews include. No synchronous ERC-4626 path: the pro-rata flows below are the entry
// and exit. Both revert as `totalAssets` does: at an unchecked price or, while a fee rate and a band are on, an
// unread fee mark (`PriceUnchecked`), and at a frozen venue mark (`VenueFrozen`).
/// @notice The shares `assets` of the pool asset buy at NAV, rounded down.
function convertToShares(uint256 assets) external view returns (uint256);
/// @notice The pool-asset base units `shares` are worth at NAV, rounded down.
function convertToAssets(uint256 shares) external view returns (uint256);
// proportional flows: no hook or callback runs on an entry, an exit or a redemption
/// @notice A pro-rata entry sized in the pool asset: exactly `poolAssets` of it, for that share of the pool asset
/// the pool holds, posts and lends, and the same share of every other token's legs, each netted per token:
/// `maxLoanAssetIn` and `minLoanAssetOut` bound tokens 1 onwards, and the entry returns token 1's net in
/// and out.
/// @dev Reverts `BookOwesPoolAsset` while the pool owes its pool asset: such a pool book enters through
/// `mintProRata`.
///
/// Either entry refuses, as its preview does and its maximum reads zero:
/// - `CustodyMismatch` while a spread fee is owed past custody, which no call of the pool's leaves (a guard):
/// no venue draws it, so the entrant's slice would come out of the custody kept for it. The next inflow of
/// the token covers it again; where the token is owed, its debt takes that inflow first, so the entries stay
/// closed until the debt is repaid (with strict mode on, a cheap-lane pool's asks wait for that too).
/// - `BasketNotRecorded` on a pool whose cheap lane is on and whose curator's fee cap is nonzero, until the
/// curator's seed of token 1 records the deposit basket (`seedLeg`), the one basket the fee mark is measured
/// against.
///
/// Either entry also refuses `PriceUnchecked` while a fee rate is on, the pool has a band and the fee mark
/// cannot read ({totalAssets}: a cheap-lane pool's basket needs token 1's price, a pending forfeit record its
/// tokens' prices, held or not), as its skim would charge nothing and the next one the gain on the entrant's
/// shares too; its maximum reads zero there.
///
/// On a pool book that owes:
/// - A borrow leg refuses before the entry pulls anything (`PriceUnchecked` where its pair's price is
/// unchecked, `PegBroken` where one of its tokens is off its peg).
/// - The entry gate, the credit law read once the legs have moved, refuses `PriceUnchecked` where a debt its
/// token's holdings and supply do not cover has no checked price against its collateral, as a dust debt
/// whose slice is no borrow leg can: the maximum reads zero there, and an entrant short of its inputs meets
/// its own pull's error first.
///
/// Refused also `Expired`, `Paused`, `FeatureDisabled` with `FEATURE_DEPOSITS` off, `VenueFrozen` while a
/// fence holds a pool part, `DepositNotPermitted` for a receiver the allowlist refuses, `NotBootstrapped`,
/// `ZeroShares` and `Slippage`; a leg past its bound reverts `TokenInExceeded` or `TokenOutBelowMin`.
/// @param poolAssets The pool asset paid in, in its base units, above zero (`InvalidAmount`).
/// @param receiver The receiver of the shares; net outputs go to the caller.
/// @param maxLoanAssetIn The most of each token paid in, token 1 first, `tokenCount - 1` long (`InvalidAmount`).
/// @param minLoanAssetOut The least of each token paid out, token 1 first, `tokenCount - 1` long (`InvalidAmount`).
/// @param minSharesOut The least shares minted.
/// @param deadline The last unix second it executes.
/// @return shares The shares minted, rounded down.
/// @return loanAssetIn Token 1's net input, in its base units.
/// @return loanAssetOut Token 1's net output, in its base units.
function depositProRata(
uint256 poolAssets,
address receiver,
uint256[] calldata maxLoanAssetIn,
uint256[] calldata minLoanAssetOut,
uint256 minSharesOut,
uint256 deadline
) external returns (uint256 shares, uint256 loanAssetIn, uint256 loanAssetOut);
/// @notice A pro-rata entry sized in shares, on any pool book: exactly `shares`, for that slice of every token's
/// legs, its holdings paid in rounded up and its debt borrowed for the entrant rounded down, netted per
/// token. The arrays are `tokenCount` long, token 0 first.
/// @dev Either entry refuses, and the entry maxima read 0 there:
/// - `IMMRouter.Unhealthy` where its borrow leg would leave a venue past its pin in the collateral the pool
/// recognizes, as its preview does.
/// - `VenueFrozen` at a frozen venue mark ({totalAssets}), whose figures are no price to enter at and whose
/// thaw's first skim would charge the entrant for gains made before it entered.
/// - `PriceUnchecked` while a fee rate is on, the pool has a band and the fee mark cannot read, as
/// `depositProRata` does.
///
/// `mintProRata` also refuses:
/// - Under the same rates and band, `PriceUnchecked` where the share price is past the fee mark's range
/// (`type(uint128).max` at 18 decimals of par).
/// - An unchecked price or a broken peg at its borrow legs and its entry gate, as `depositProRata`'s do.
/// - `DepositCapExceeded` past `Limits.mintProRataCap` on the supply after it.
/// - `Expired`, `Paused`, `FeatureDisabled`, `DepositNotPermitted` and `NotBootstrapped` as `depositProRata`.
/// - `TokenInExceeded` or `TokenOutBelowMin` for a leg past its bound.
/// @param shares The shares to mint, above zero (`InvalidAmount`).
/// @param receiver The receiver of the shares; net outputs go to the caller.
/// @param maxIn The most of each token paid in, in its base units.
/// @param minOut The least of each token paid out, in its base units.
/// @param deadline The last unix second it executes.
/// @return tokenIn Each token's net input, in its base units, token 0 first.
/// @return tokenOut Each token's net output, in its base units, token 0 first.
function mintProRata(
uint256 shares,
address receiver,
uint256[] calldata maxIn,
uint256[] calldata minOut,
uint256 deadline
) external returns (uint256[] memory tokenIn, uint256[] memory tokenOut);
/// @notice A pro-rata exit, price-free and never paused: `shares` of `owner`'s for that slice of every token's
/// legs, its debt repaid by the caller rounded up and its holdings paid to `receiver` rounded down, netted
/// per token. The arrays are `tokenCount` long, token 0 first. A caller other than `owner` spends its
/// allowance. Refused also, past the cases below, `Expired`, `BelowMinimumShares` where the supply left
/// would pass under the dead shares, `TokenInExceeded` and `TokenOutBelowMin` past the bounds, and
/// `ExitWorsensLedger`.
/// @dev A venue that takes less of its repay than asked (a minimum position, a lender's remainder past its market's
/// total borrows):
/// - It releases in proportion to what it took. The rest of the repay nets its debt in custody, which pays the
/// slice the venue keeps posted, or the exit refuses (`CustodyMismatch`) past the dust any exit can leave
/// where custody runs dry.
/// - That dust is the venue's last whole units, bounded at the larger of its pair's safety gap and 1 %, the
/// lenders' rounding and a share under one unit's assets and one, which it releases none of. It stays
/// posted, `minOut` bounds it and the fee mark counts it as forfeited.
/// - A repay that leaves the venue owing nothing holds nothing.
/// - The preview reads no such hold, so it can show an exit this refuses.
/// - The exit maximum reads the holds a kind reports (a minimum position, `IHeldRepay`; a lender's bound,
/// `IRepayable`, one per market, spent across the venues borrowing there in the exit's order), so no exit it
/// advertises refuses for one. At a venue past its threshold whose lender holds the repay of its whole debt
/// short, the remainder can keep the release in proportion past what the lender allows, and the maximum
/// reads zero.
/// - An exit the maximum advertises may pay short of its preview by the dust a held venue leaves: floors taken
/// from the preview, less that dust, hold.
///
/// Dust at a venue that still owes:
/// - It releases nothing under one unit's assets and one, which its kind would release by burning a whole
/// unit: a slice that small stays posted with the venue's last whole units, recorded as dust, whether or not
/// the venue held the repay.
/// - Where the venue held the repay, a share under one unit's assets and one of a larger slice releases none,
/// and custody pays that slice, what it cannot of that share staying posted beside the dust.
///
/// At a venue whose threshold equals its pair's LTV, which reads unhealthy once interest accrues, the maximum
/// reads zero below the size that clears the venue, though smaller exits may execute.
///
/// Haircuts: a slice at a venue whose lender cannot pay all of its face (`IFinancingAccount.haircut`) is paid
/// cut by that share, which stays in custody, so the exiter bears its share of the venue's loss, as NAV does,
/// and the holders who stay none of it. Where the haircut is a fee each redemption pays
/// (`CAP_REDEMPTION_FEE`), the slice leaves net of it instead, so the venue burns the exiter's units and no
/// more. This holds for a loss the venue's kind reports; the comptroller kind (`CTokenAccount`) reports only
/// its lender's redemption fee, as that lender records no bad debt, so there a slice leaves at face and the
/// holders who stay bear the exiter's share of a bad debt the lender has not covered.
///
/// At a frozen venue mark (a venue that allows no action and holds a position):
/// - The exit forfeits its slice of such a venue that owes nothing, or no more than the lenders' rounding
/// (`MMRouterLib.RELEASE_SLACK`, whose share it leaves behind), which stays posted for the holders who
/// remain.
/// - It refuses (`VenueFrozen`) where one owes more, as its debt slice cannot be repaid there.
/// - Its preview shows the smaller payout, and `minOut` bounds it.
/// - A forfeit is never performance: the pool records it, and the first skim that reads the fee mark again
/// raises the fee mark by its value per share before it charges either rate.
///
/// The collateral an exit leaves where the venue still owes after it, and a release in the kind's whole units
/// could take it past its threshold, is treated as a forfeit too:
/// - The slice is cut to keep that floor posted, bounded as the held dust is (one unit's assets and one times
/// `lltv / max(lltv - ltv, gap, 1 %)`), and by up to one unit's assets more where the venue holds less than
/// that floor and a unit, as a slice under one unit's assets and one stays posted whole
/// (`FLAMMGateLib.nearUnitsAt`). Only what it leaves is forfeited.
/// - Where that much posted would leave the venue past its threshold, its lender refuses the release and the
/// exit with it.
/// - No move of the pool's own (a dial move, `setDials`; an admission with borrowing on or a switch-on) leaves
/// a pin within that gap under its threshold.
///
/// A collateral slice a venue cannot release now is paid from the custody the pool owns, never the custody
/// kept for the protocol's spread fee: past it the exit refuses (`CustodyMismatch`).
/// @param shares The shares to burn, above zero and at most `owner`'s (`InvalidAmount`).
/// @param receiver The receiver of the holdings, neither zero nor the pool (`InvalidAmount`), who also takes the
/// shares' claims on a fence's part.
/// @param owner The holder of the shares.
/// @param maxIn The most of each token the caller repays, in its base units.
/// @param minOut The least of each token paid out, in its base units.
/// @param deadline The last unix second it executes.
/// @return tokenIn Each token's net repay, in its base units, token 0 first.
/// @return tokenOut Each token's net output, in its base units, token 0 first.
function redeemProRata(
uint256 shares,
address receiver,
address owner,
uint256[] calldata maxIn,
uint256[] calldata minOut,
uint256 deadline
) external returns (uint256[] memory tokenIn, uint256[] memory tokenOut);
/// @notice The legs and net amounts {depositProRata} of `poolAssets` would take now.
/// @dev The previews price at the supply after the performance fee the flow crystallizes first, both parts. Each
/// quotes the legs, not whether the flow executes, but an entry's refuses (`IMMRouter.Unhealthy`) where a
/// borrow leg would leave its venue past its pin in the collateral the pool recognizes, and an exit's where a
/// frozen venue owes more than the lenders' rounding (`VenueFrozen`), as the flow does; an exit's legs carry
/// the flow's haircut cut and forfeit its slice of a frozen venue that owes no more. An exit's reads no hold
/// of its repay at a venue that takes it short, so the exit can refuse (`CustodyMismatch`) where custody
/// cannot pay the slice that venue keeps posted, or pay short of it by the dust (`redeemProRata`). `tokenIn`
/// and `tokenOut` are per token, token 0 first.
/// @param poolAssets The pool asset paid in, in its base units.
/// @return shares The shares it would mint.
/// @return legs The flow's venue legs.
/// @return tokenIn Each token's net input, in its base units.
/// @return tokenOut Each token's net output, in its base units.
function previewDepositProRata(uint256 poolAssets)
external
view
returns (uint256 shares, VenueLeg[] memory legs, uint256[] memory tokenIn, uint256[] memory tokenOut);
/// @notice The legs and net amounts {mintProRata} of `shares` would take now, as {previewDepositProRata}.
/// @param shares The shares to mint.
/// @return legs The flow's venue legs.
/// @return tokenIn Each token's net input, in its base units.
/// @return tokenOut Each token's net output, in its base units.
function previewMintProRata(uint256 shares)
external
view
returns (VenueLeg[] memory legs, uint256[] memory tokenIn, uint256[] memory tokenOut);
/// @notice The legs and net amounts {redeemProRata} of `shares` would take now, as {previewDepositProRata}.
/// @param shares The shares to burn.
/// @return legs The flow's venue legs.
/// @return tokenIn Each token's net repay, in its base units.
/// @return tokenOut Each token's net output, in its base units.
function previewRedeemProRata(uint256 shares)
external
view
returns (VenueLeg[] memory legs, uint256[] memory tokenIn, uint256[] memory tokenOut);
// swap
/// @notice Exact input, any two listed tokens, the pool asset included: the hook that prices the pair (the swap
/// hook, or a pair hook on its pairs) prices the fill (`IPairHook.fillPair`), and core checks it (its fee
/// inside the bounds, its input, the caller's minimum, the ceiling the credit law and the notional caps
/// leave, the tighter band of the two tokens around their USD prices) and settles it through the Router:
/// the input repays what the pool owes of it first, the output pays from custody, collateral, one rotation
/// or a draw on its pair, the input's surplus is lent, and the credit law holds after. It runs no
/// observation.
/// @dev It runs only for a pair in both trade masks (a hook prices it and the curator lets it trade,
/// `FLAMM.tradablePairs`; `PairNotTradable` otherwise), a sale of the pool asset under `FEATURE_SWAP_SELL` and
/// a buy of it under `FEATURE_SWAP_BUY` (`FeatureDisabled`); a pair past the hook pair needs both its USD
/// prints within `maxPriceAgeSec` (`StalePair`).
///
/// Refused also:
/// - `InvalidPair`: a token not listed, or one token twice.
/// - `Paused`: `FLAMM.setPaused` says which swaps run paused.
/// - `PriceUnchecked`: a pair with no checked price, or an owing pool with no band.
/// - `PegBroken`: a draw with a token off its peg.
/// - `RoomExhausted`: no room for an output some live pair owes, the input owing nothing.
/// - `CreditPathOff`: a pair a cheap-lane pool's front prices while its credit path is off.
/// - Past core's checks of the fill, `FeeOutOfBounds`, `FillInvalid`, `OutputAboveCeiling` and `PriceBand`.
/// - `InputUnused`: a fill of less than `amountIn` where the input was found (below).
///
/// The input is found or pulled at the settling step, after the fill is checked and before any venue moves
/// or anything is paid:
/// - Found: where the pool holds the whole `amountIn` past its tracked custody, nothing is pulled and exactly
/// `amountIn` is credited, and a fill of less reverts `InputUnused`. Input sent first therefore fills whole
/// or comes back with the revert. A found fill makes no call that moves the input, unless a venue takes it
/// in that fill (a repay, a post or a lend), so it fills where that token's transfers are paused or refuse
/// the caller, up to what lay past custody. That balance is read only while the pool's balance is at least
/// its tracked custody: under it the pull runs and custody refuses the fill (`CustodyMismatch`), except on
/// the full path (any fill past the custody-only branch) within what custody keeps of the fee in token 0 or
/// 1 and, on a payout, the fill's part and share, which the reconcile does not read: there the swap fills
/// and the shortfall stays.
/// - Pulled: otherwise the pool pulls what the fill uses from the caller, and a fill of less keeps the rest
/// with the caller. A short delivery reverts `CustodyMismatch`.
/// - Any untracked `tokenIn` counts toward that test: a donation, an overpayment, a payment left by an
/// earlier transaction. The next caller it covers spends it, with no pull, and any allowance that caller
/// gave the pool stands; only what lies past `amountIn` stays untracked.
/// - A payer sends and calls in one transaction with no call between, and holds no allowance to the pool. A
/// send short of `amountIn` is left in the pool and the pull runs.
/// - What a payer leaves behind it can swap away itself at the pool's price only where the pair is open and
/// this entry runs: not on a custody-blind pool, nor, with the credit path off, on a pair the front prices.
/// A stray of the pool asset has no lift: it stays until a swap or a paid fill spends it.
/// - On a fee-on-transfer token a payer that declares what arrived fills where no venue moves the token; a
/// repay or a post of its cut reverts. One that declares the gross amount falls to the pull, unless
/// untracked balance covers the fee, which the swap then spends.
/// - A pool must not list two addresses of one ledger: each leg's custody reads as past the other's tracked
/// custody, so a fill found there is paid from the pool's own custody.
/// - A send sized by `previewSwap` takes the preview from the calling address, and it can still clip: its
/// `amountInUsed` may fill less when executed, and a found fill of less reverts.
///
/// The pool's `Swap` event reports the fill: the tokens' indices, the native amounts and fee, and the hook's
/// fee rate, spot after, gross output, coordinate after and the protocol's part of the fee, with
/// `amountInUsed` equal to `amountIn` on a found fill. Its `sender` is the caller, which need not be the
/// account that paid. From the swap `EverlongHook` emits `Levered` on a leverage fill and nothing on a curve
/// fill.
///
/// A swap that would draw at a pair with a venue that borrows, or rotate from a pair, where a venue reports a
/// loss of 1 bp or more on its collateral (`FLAMMKeptLib.lossAtFloor`), or takes a redemption fee of any size
/// on it, reverts `VenueReportsLoss`; the quote reverts the same, on the same check, where its plan draws or
/// rotates (it reads the releases the Router reports, so a venue that releases less than it reports can leave
/// the swap at a draw the quote did not see). A payout the pair's supply would pay is refused too, and a pair
/// whose only venue that borrows stands under a fee draws nothing until the fee ends.
/// The operator or the guardian ends it at once by switching that venue's borrowing off, or the pair's;
/// switching it back on waits the pool's delay where the cheap lane is on.
///
/// The selector is shared with another swap standard, but this returns two words and has none of its views.
/// @param tokenIn The token paid in, found at the pool or pulled from the caller.
/// @param tokenOut The token paid out.
/// @param amountIn The most to pay in, in `tokenIn` base units, above zero (`InvalidAmount`): all of it where the
/// input is found.
/// @param minAmountOut The least net output, in `tokenOut` base units (`Slippage`).
/// @param to The receiver of the output, neither zero nor the pool (`InvalidAmount`).
/// @param deadline The last unix second it executes (`Expired`).
/// @return amountInUsed The input the hook used, in `tokenIn` base units, at most `amountIn`.
/// @return amountOut The net output paid to `to`, in `tokenOut` base units.
function swap(address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut, address to, uint256 deadline)
external
returns (uint256 amountInUsed, uint256 amountOut);
/// @notice Quotes a swap of `amountIn` of `tokenIn` for `tokenOut` on the pool book as it stands: the swap's own
/// branch, plan and checks, the hook's quote of the swap's request (`IPairHook.quotePair`), re-asked at the
/// input it used, rounded to native units, so a swap of the quoted input, the quoted output its minimum,
/// fills the quote. A payout that draws past what the Router can fund for it now reverts as the swap would
/// (`IMMRouter.InsufficientLiquidity`), rather than quoting a smaller fill the swap would not make. No swap
/// fills under its quote, but at a venue that holds a minimum position a quoted payout can still revert by
/// the slice the swap's plan passes over, and a payout the quote refuses can fill (`IFinancingAccount`
/// ADMISSION).
/// @param tokenIn The token paid in.
/// @param tokenOut The token paid out.
/// @param amountIn The most to pay in, in `tokenIn` base units.
/// @return amountInUsed The input the fill uses, in `tokenIn` base units.
/// @return amountOut The net output, in `tokenOut` base units.
/// @return feeWad The fill's fee rate, WAD.
function previewSwap(address tokenIn, address tokenOut, uint256 amountIn)
external
view
returns (uint256 amountInUsed, uint256 amountOut, uint256 feeWad);
/// @notice The pool context a recenter hands the swap hook now (`PoolContext`): every token's legs through the
/// Router and its custody, the rest at their unrounded USD cross, the hook pair's N36 from the feed's pair,
/// the band, the listed pairs and the features; a poke hands the same with every leg zero, as it reads no
/// pool book. Reverts where the observation could not price: a stale pair, the sequencer, an unchecked
/// price it needs. The hook's curve ceremony reads `priceN36` from it as the feed's print
/// (`EverlongOpsLib.curveGate`), so a pool that cannot price its observation refuses that ceremony too.
function hookContext() external view returns (PoolContext memory);
/// @notice The request a swap of `amountIn` (native units of `tokenIn`) hands the pair's hook now
/// (`PairRequest`), on the swap's branch and plan, `sender` the caller. Reverts where the swap
/// refuses before its fill: the pause or a feature bit, a payout without room, a payout off peg wherever
/// its payout pair may borrow, whatever the backing holds, a price it cannot read, a zero input.
function pairRequest(address tokenIn, address tokenOut, uint256 amountIn) external view returns (PairRequest memory);
// lifecycle (factory only)
/// @notice The pool's first entry, the Factory's alone and once (`AlreadyBootstrapped`): pulls `assets` of the pool
/// asset into custody, mints at par, with `FLAMMStore.MINIMUM_SHARES` to a dead address that never burns
/// them, and sets the fee mark at par. `InvalidAmount` on a zero `assets` or `to`; `BelowMinimumShares`
/// unless the shares pass the dead ones.
/// @param assets The pool asset, in its base units.
/// @param to The receiver of the shares past the dead ones.
/// @return shares The shares minted to `to`.
function bootstrap(uint256 assets, address to) external returns (uint256 shares);
/// @notice The protocol's performance fee, at most `FLAMMStore.MAX_PROTOCOL_FEE_BP`; it skims at the old rates
/// first, and a rise reverts `PriceUnchecked` while that skim cannot read the fee mark, as on a seeded pool
/// with no market band, or while a fence holds a pool part. A nonzero rate on a pool whose cheap lane is on
/// reverts `InvalidConfig`. The Factory applies a cut at once and a rise after the longer of its
/// `UPGRADE_DELAY` and ten days; no upgrade moves the Factory, so every implementation keeps this entry.
/// @param feeBp The rate, bp.
function setProtocolFeeBp(uint16 feeBp) external;
/// @notice The protocol's rates (`FLAMMFloatLib.setSpreadFeeRates`), one word: in bits 0-15 the spread rate, at
/// most `FLAMMFloatLib.MAX_SPREAD_FEE_BP`, the share of a hook's fee the protocol takes in kind, of
/// each fill's edge against its fee price (the pull price, or where the listing reads none its desk's
/// word's mid) on a pool whose cheap lane is on; in bits 16-31 and 32-47 the notional rates of the pool's
/// other pairs and of its correlated pairs (two tokens of one peg group at the Factory), each at most
/// `FLAMMFloatLib.MAX_NOTIONAL_RATE`, in `FLAMMStore.NOTIONAL_SCALE` parts of a fill's notional leg, the
/// floor of the protocol's part of every hook-priced fill and every cheap fill. The Factory applies a cut
/// of a field at once and a rise after the longer of its `UPGRADE_DELAY` and ten days; no upgrade moves
/// the Factory, so every implementation keeps this entry.
/// @param rates The word above.
function setSpreadFeeRates(uint48 rates) external;
// code (beacon proxy: the Factory is the beacon; a new implementation must report a higher code version)
/// @notice The code version of the implementation behind the beacon.
function poolCodeVersion() external pure returns (uint32);
/// @notice The feature bitmap (`FLAMMStore.FEATURE_*`) and the governance delay.
/// @return featureBits The bitmap.
/// @return delaySec The governance delay, seconds, write-once.
function switches() external view returns (uint256 featureBits, uint32 delaySec);
/// @notice The committed ceilings (`FLAMMPolicyLib.setBandAndFeeCeilings`): the widest swap band any token may take and the
/// highest fee cap, each set at once under its ceiling, which starts at the widest band of the pool's
/// tokens and its cap at birth (a band ceiling of `type(uint64).max` admits no band at all); then the
/// scheduled raise, which waits `governanceDelaySec` (one of the band's at least ten days), and when the
/// curator may apply it, zero when none.
/// @return bandWad The band ceiling, WAD.
/// @return feeCapWad The fee cap's ceiling, WAD.
/// @return pendingBandWad The scheduled band ceiling, WAD.
/// @return pendingFeeCapWad The scheduled fee cap ceiling, WAD.
/// @return executableAt When the raise may apply, unix seconds; zero when none.
function ceilings()
external
view
returns (uint64 bandWad, uint64 feeCapWad, uint64 pendingBandWad, uint64 pendingFeeCapWad, uint48 executableAt);
// observation
/// @notice Forwards the feed's print to the swap hook, which folds it; permissionless and refused while paused
/// (`Paused`), and on a pool with no band, which has no print to forward (`NoBand`). A
/// swap forwards none: the folds follow the feed as far as pokes and recenters forward it.
function poke() external;
/// @notice Forwards the feed's print (none on a pool with no band) to the swap hook's recenter, which may move its
/// anchor inside the caller's bounds (`AnchorOutOfBounds` otherwise); refused while paused (`Paused`). The
/// keeper, the curator or the controller hook calls it (`NotKeeperOrCurator`), so a recentering rule can
/// live in a controller, which only the genesis set or the delayed hook-set ceremony installs.
/// @param minAnchorN36 The lowest anchor the caller takes, in the hook's N36 price scale.
/// @param maxAnchorN36 The highest anchor the caller takes, in the same scale, at least `minAnchorN36`
/// (`InvalidConfig`).
/// @param deadline The last unix second it executes (`Expired`).
function recenter(uint256 minAnchorN36, uint256 maxAnchorN36, uint256 deadline) external;
/// @notice Crystallizes the performance fee at the current fee mark, minting the curator's part to the core fee
/// receiver and the protocol's to the Factory's `protocolFeeReceiver`; permissionless. With both parts
/// off it still raises `peakSharePriceWad`, silently.
function skimPerformanceFee() external;
}
/// @notice What a pool and the lens read of the Factory's protocol fee: the receiver of the protocol's part (never
/// zero on the Factory) and a pool's scheduled rise (`feeBp` zero: none).
interface IFLAMMProtocolFee {
/// @notice The receiver of the protocol's part of every pool's fees.
function protocolFeeReceiver() external view returns (address);
/// @notice `pool`'s scheduled rise of its protocol performance fee.
/// @param pool The pool.
/// @return feeBp The scheduled rate, bp; zero: none, or one lapsed.
/// @return executableAt When it may apply, unix seconds.
function pendingProtocolFee(address pool) external view returns (uint16 feeBp, uint48 executableAt);
}
src/interfaces/core/flamm/IFLAMMHooks.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The pool state in a hook's observation (`ObservationContext`), which `FLAMMOpsLib.hookContext` also reads, built
/// by core from its custody, the Router's positions and one checked price. A fill's hook gets a `PairRequest`
/// instead. The pool lists tokens `t0, t1, ...`: `t0` is the pool asset (the share and NAV unit, the base),
/// `t1` the numeraire (the quote), the hook pair. Each holds four legs: held (custody, unlent), supplied
/// (lent at a venue), posted (collateral at a venue) and owed (borrowed from a venue). Base
/// fields are `t0` base units; quote fields are `t1` in N18 (its value at 18 decimals); the rest sum every
/// token from `t2` on in N18 at its USD cross with `t1`, holdings rounded down and debt up, leg by leg.
/// `priceN36` is `t1`'s value at 36 decimals per `t0` base unit (N18 scaled by 1e18), so a cheap 18-decimal
/// pool asset keeps its digits; every hook price below is in the same price scale. A pool with no market band
/// hands `priceN36` zero. A poke's observation reads no pool book: it carries the print, the band, the pairs
/// and the features, every leg zero (`IRecenterHook.observe`).
/// @dev Flat, so core copies it into a call in one move. `bookScale` is reserved and zero. `bandWad` is the hook
/// pair's live swap band (zero: none). `pairs` holds the `CONTEXT_PAIR_*` bits of the credit pairs the pool
/// lists; `features` the pool's `FEATURE_*` bits and, on a custody-blind pool, whose swap hook is its front for
/// life, the law's bit past them (`FLAMMStore.CUSTODY_BLIND`).
struct PoolContext {
uint256 baseHeld; // `t0` held, base units
uint256 baseSupplied; // `t0` supplied, base units
uint256 basePosted; // `t0` posted, base units
uint256 baseOwed; // `t0` owed, base units
uint256 quoteHeld; // `t1` held, N18
uint256 quoteSupplied; // `t1` supplied, N18
uint256 quotePosted; // `t1` posted, N18
uint256 quoteOwed; // `t1` owed, N18
uint256 restHeldN18; // the held, supplied and posted legs of every token from `t2` on, N18, rounded down
uint256 restOwedN18; // the owed legs of every token from `t2` on, N18, rounded up
uint256 priceN36; // `t1` per `t0` base unit, N36; zero with no market band
uint256 bookScale; // reserved, zero
uint64 bandWad; // the hook pair's live swap band, WAD; zero: none
uint32 pairs; // `CONTEXT_PAIR_*` bits
uint32 features; // the pool's `FEATURE_*` bits, and `FLAMMStore.CUSTODY_BLIND` past them
}
/// @notice `EverlongHook`'s own form of a fill of the hook pair, which it builds from the pair request
/// (`PairRequest`): the pool context, the side, the input and the ceiling in its units (token 1 in N18), and
/// the pool's fee bounds. Core hands no hook this struct.
struct SwapContext {
PoolContext pool; // the pool book as the request carries it
bool poolAssetIn; // the input is the pool asset: the pool buys it
uint256 amountIn; // `t0` base units where `poolAssetIn`, else `t1` in N18
uint256 maxAmountOut; // `t1` in N18 where `poolAssetIn`, a ceiling past a word read as none, else `t0` base units
uint64 feeFloorWad; // the least fee rate, WAD
uint64 feeCapWad; // the most fee rate, WAD
}
/// @notice `EverlongHook`'s own fill in its units (`t0` in base units, `t1` leg N18): input used, the curve's gross
/// output, the fee kept from it, the fee rate, the spot after the fill and the curve coordinate after it
/// (`xAfter`, WAD). The hook converts it to the pair fill core settles (`PairFill`).
struct FillResult {
uint256 amountInUsed; // in `SwapContext.amountIn`'s units
uint256 grossOut; // in `SwapContext.maxAmountOut`'s units
uint256 feeOut; // in `SwapContext.maxAmountOut`'s units
uint256 feeWad; // WAD
uint256 spotAfterN36; // N36
uint256 xAfter; // WAD
}
/// @notice One checked reference print and its source timestamp. `poke` and `recenter` forward the feed's current
/// print, which may repeat an `observedAt` already forwarded, even with a moved `referenceN36` (a cross carries
/// its older leg's stamp). A hook MUST treat `observedAt` as non-monotonic, clamp its own elapsed-time step and
/// decline a value it has already folded. A swap forwards none: its request carries the two prices, which a
/// hook may fold itself. A recenter's `pool` is the pool book at that print; a poke's carries the hook pair's
/// N36, the band, the pairs and the features with every leg zero, as core reads no pool book for it. A pool
/// with no market band reads no price: its `poke` refuses (`NoBand`), and its recenter hands a zero reference
/// and stamp.
struct ObservationContext {
PoolContext pool; // the pool book, or the terms beside it, as above
uint256 referenceN36; // the hook pair's print, `t1` per `t0` base unit, N36
uint48 observedAt; // the print's source timestamp, unix seconds; the older leg's
}
/// @notice The swap hook's spot, for readers outside the pool: core reads none, as every swap hook only folds on a
/// poke (`HOOK_CAP_FOLD_ONLY`). The swap hook prices its fills and its own fee through `IPairHook`.
interface IInvariantHook {
/// @notice The hook's marginal price, in `PoolContext.priceN36`'s price scale.
/// @param ctx The pool state. A hook may ignore it, as `EverlongHook` does.
/// @return spotN36 The spot, N36. A hook that holds no curve answers zero.
function spot(PoolContext calldata ctx) external view returns (uint256 spotN36);
}
/// @notice The observation and anchor policy: fold one observation, or fold it and move the anchor. Core runs
/// `observe` on `poke`, and `recenter` on the pool's `recenter` (the keeper's, the curator's or the controller
/// hook's), whose anchor bounds core checks on the anchor the hook returns.
interface IRecenterHook {
/// @notice Folds the print, moving nothing `spot` reads (`HOOK_CAP_FOLD_ONLY`). Core calls it on `IFLAMM.poke`,
/// which anyone may run. A revert reverts the poke.
/// @param ctx The print, with every leg of its context zero.
function observe(ObservationContext calldata ctx) external;
/// @notice Folds the print and moves the anchor where the hook's policy says so. Core calls it on
/// `IFLAMM.recenter`.
/// @param ctx The print and the pool book at it.
/// @return moved Whether the anchor moved; core checks `anchorN36` only then (`AnchorOutOfBounds`).
/// @return anchorN36 The anchor after the call, N36.
function recenter(ObservationContext calldata ctx) external returns (bool moved, uint256 anchorN36);
}
/// @notice A hook's identity, which core checks at installation (`FLAMMOpsLib.checkIdentity`). Every hook must hold
/// code. A hook that prices (the swap hook and a pair hook) must answer both and name its pool; the
/// controller may stay silent, but a nonzero `boundPool` must name the pool and a declared version must match.
interface IHookIdentity {
/// @notice The hook interface version the hook implements, `HOOK_INTERFACE_VERSION`.
function hookInterfaceVersion() external view returns (uint16);
/// @notice The pool the hook serves. A hook shared by many pools answers the pool asking.
function boundPool() external view returns (address);
}
/// @dev The one hook interface version core accepts (`IHookIdentity.hookInterfaceVersion`).
uint16 constant HOOK_INTERFACE_VERSION = 3;
// `PoolContext.pairs`: the credit pairs the pool lists (live, not retired) and whether each borrows.
/// @dev The forward pair, `t1` borrowed against `t0`, is listed.
uint32 constant CONTEXT_PAIR_FORWARD = 1 << 0;
/// @dev The forward pair's borrowing is on.
uint32 constant CONTEXT_PAIR_FORWARD_BORROWS = 1 << 1;
/// @dev The reverse pair, `t0` borrowed against `t1`, is listed.
uint32 constant CONTEXT_PAIR_REVERSE = 1 << 2;
/// @dev The reverse pair's borrowing is on.
uint32 constant CONTEXT_PAIR_REVERSE_BORROWS = 1 << 3;
/// @dev Another pair that owes `t0` or posts a token other than `t0` is listed.
uint32 constant CONTEXT_PAIR_OTHER = 1 << 4;
src/interfaces/core/flamm/IFLAMMLane.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The cheap lane of a PropAMM pool: the entries its front calls. The front prices a fill (a maker-signed
/// ladder, held by the front's price fence where its listing has one, and metered per second) and the pool
/// settles it from tracked custody, never touching the lender. Every pool runs one implementation; the cheap
/// lane is per-pool configuration.
/// @dev Both entries take one side-and-pair word, `sidePair`: bit 0 the side (set: a bid, the taker sells the pair's
/// base and the pool pays its quote; clear: an ask); bits 8-15 the pair's token indices in the pool, the base in
/// bits 8-11 and the quote in bits 12-15, zero for the hook pair (tokens 0 and 1); every other bit refused. The
/// front passes its pool record's top byte (the listing's token indices) as the pair bits. It plans a fill against
/// `laneStateOf` and then calls `fillFromFront` in the same transaction: `fillFromFront` accepts every fill whose
/// output is within the room `laneStateOf` reported and whose input is within its `maxIn`, and the pool's own swap
/// pays that room too, so the view's room lands on every route of the pair. The view nets custody and the bucket
/// of the part the pair's notional floor needs beside the payout, as the pool's own swap pays both from them, and
/// reads each notional cap net of the room that floor needs beside a payout under it, since a route takes it as
/// its out cap; the cheap fill nets the bucket of nothing and refuses one unit past its raw room. A pool that
/// refuses what its `laneStateOf` promised breaks the front's `quote == swap` guarantee.
interface IFLAMMLane {
/// @notice A lift of the guardian's pause by anyone but the guardian in office, or the curator once the guardian
/// that set it is out of office: the pool's `GuardianPauseStands` (`FLAMMStore`), restated so a caller
/// decodes it with this interface.
error GuardianPauseStands();
/// @notice Settles a front-priced fill from tracked custody, never touching the lender. All or nothing. On the hook
/// pair as below; on any other pair (`FLAMMRoute`) the same checks per token: the pair open in the
/// curator's trade mask, in the cheap lane's pairs and among the pairs the front priced when the pool last
/// asked (`syncListings`), the pool unpaused, the debt rule that reads no price (`FLAMMLane.pays`; none on
/// a pool with no band, or on a custody-blind pool outside strict mode), the out token's custody less the
/// fee owed in it and, where the fill owes its part in that token, net of what holds the pair's notional
/// floor beside the payout, each token's notional cap on its own leg net of the room that floor needs
/// beside a payout under it, and the out token's outflow bucket; the protocol's part is then owed in the
/// pair's quote.
/// @dev Checks, in order:
/// 1. The caller is the pool's front (its swap hook, fixed at birth), else `NotFront`.
/// 2. The pool's transient lock (shared with every other entry), else `Reentrant`.
/// 3. The cheap lane, the cheap-fill feature bit and the side's feature bit (`FeatureDisabled`), and the hook
/// pair open for the side (`PairNotTradable`).
/// 4. A bid (the pool buys its pool asset, pays token 1) needs the pool unpaused (`Paused`), token 1 proven
/// debt-free or the pool without a band (`NotDebtFree`), and `amountOut` within the held token 1 less the
/// fee owed in it, net of what holds the pair's notional floor beside the payout (`OutputAboveCeiling`).
/// 5. An ask (the pool sells its pool asset) needs every token past token 1 proven debt-free, token 1 too in
/// strict mode, and `amountOut` within the held pool asset less the fee owed in it. On a two-sided pool,
/// and a custody-blind one in strict mode, both sides take instead the debt rule of every pair,
/// `FLAMMLane.pays`, with no exception for the input; on a custody-blind pool outside strict mode neither
/// side takes a debt rule; on a custody-blind pool an ask needs the pool unpaused too, in strict mode or
/// not.
/// 6. The input already received (`balanceOf(tokenIn)` at least tracked custody plus `amountIn`, else
/// `CustodyMismatch`), exactly `amountIn` credited.
/// 7. Core's per-fill notional cap on the quote leg (`amountOut` on a bid, `amountIn` on an ask; zero is
/// uncapped), net of the floor's room as `laneStateOf` reads it, else `NotionalCap`.
/// 8. The pool's own outflow room for the side, else `OutflowCap`.
///
/// It then writes custody once, debits the outflow bucket, accrues the protocol's part (and, where the pool
/// sets an operator's share, the share beside it, `FLAMMFloatLib.operatorFeeOwed`), pays `recipient` and
/// reconciles. It logs no event of its own: the front's `PoolFill` records the fill.
/// @param sidePair The side and the pair (see above); on the hook pair a bid sells the pool asset.
/// @param amountIn The input, already transferred to this pool by the front.
/// @param amountOut The output this pool pays to `recipient`.
/// @param recipient Who receives `amountOut`.
/// @param pullPrice36 The price P the spread fee's edge is measured against, in the price36 scale (quote base
/// units per base base unit × 1e36): the fill's pull price, or where its listing reads none its desk's
/// word's mid (`PropAMMLaneLib.spreadFee`); zero where the front has neither, and the fill then owes no
/// spread fee and no operator's share, and books the pair's notional floor alone.
/// @return spreadFee The part this fill booked for the protocol: the larger of its spread fee, held to its bounds,
/// and the pair's notional floor (the pair's notional rate of the quote leg), within the custody the fill
/// leaves, in base units of the pair's quote token (token 1 on the hook pair); the operator's share booked
/// beside it is not in it.
function fillFromFront(
uint256 sidePair,
uint256 amountIn,
uint256 amountOut,
address recipient,
uint256 pullPrice36
) external returns (uint256 spreadFee);
/// @notice What `fillFromFront` would accept now on one side of one pair, so the front's planner applies the pool's
/// own predicate and a quote never promises what the pool would refuse. Unguarded: a plain read; both zero
/// while a flow holds the pool's lock and for a word with bits past the side and the pair; a valid word the
/// predicate refuses reads no room beside its `maxIn`.
/// @param sidePair The side and the pair, as `fillFromFront` takes them.
/// @return room The most of the side's out token a fill may pay now: zero where the side refuses (on a pair past
/// the hook pair, one the front did not price when the pool last asked among them, `syncListings`); else
/// the lower of the out token's custody less the spread fee owed in it and the out token's outflow room
/// (the side's on the hook pair), both net of the part the pair's notional floor needs beside the payout,
/// `x * 1e7 / (1e7 + rate)` (custody holds that part already where it is owed in the out token: a bid's on
/// the hook pair), as the pool's own swap pays the payout and that part from both, so this room lands on
/// every route of the pair, while a cheap fill one unit past the raw room refuses; and core's per-fill
/// notional cap on the out token's leg: on the hook pair where the side's quote leg is its output (a bid:
/// token 1 paid), on any other pair the out token's own cap, either side.
/// @return maxIn The most of the side's in token a fill may take, zero uncapped: core's per-fill notional cap on
/// the in token's leg: on the hook pair where the side's quote leg is its input (an ask: token 1
/// taken), on any other pair the in token's own cap, either side. Past the hook pair each token's cap binds
/// its own leg. Each cap here and in `room` reads net of the room the pair's notional floor needs beside a
/// payout under it, `cap * 1e7 / (1e7 + rate)` (the pool's own swap holds that floor inside a cap on its
/// payout; a cap of one unit, which that rounds to none, reads one), so the other side's route may take
/// this as its out cap; the fill takes up to the cap net of that room, as this reports. On the hook pair
/// token 1's cap is read from its mirror in the cheap lane's config word, so a pool with no cheap lane
/// reads zero here.
function laneStateOf(uint256 sidePair) external view returns (uint256 room, uint256 maxIn);
/// @notice The cheap lane's words as they stand: `laneWord` (the spread fee accrued, strict mode, the version, the
/// buckets as last written) and `laneConfig` (`FLAMMStore.LANE_*`: the caps, bits 0-95; the credit path's
/// switch, bit 96; the version, bits 97-103; the guardian's and the curator's pauses, bits 104 and 105,
/// which match `paused()` from birth; token 1's bucket unit as a power of ten, bits 106-109; and token 1's
/// notional cap, bits 128-255, as `tokenConfig(1)` reads it). The third word reads zero: the cheap lane's
/// loosenings wait in the pending table (`IFLAMM.pending`). A custody-blind pool's idle floor is
/// `FLAMMFloatLib.idleFloor`. A plain read, unguarded: answered whole by the pool front itself
/// (`FLAMMFront`'s fallback), so the switches a front reads before a credit route reach no other contract.
/// @dev A call that carries one request word after the selector is answered the route facts it asks as the third
/// word (`FLAMMStore.LANE_FACTS`): the request names a side of a pair as a cheap fill's side word does (bit 0
/// a bid, bits 8-15 the pair's token indices, zero the hook pair) and asks `FLAMMStore.LANE_FLOOR` (a fee
/// floor of the pool or of the pair's tokens past the pool asset stands) or `FLAMMStore.LANE_BORROWS` (a live
/// pair may borrow the token the side pays), each read as `limits`, `tokenConfig` and `pairConfig` answer it
/// in that call; a token past the list reverts `BadTokenIndex`. Where the credit path is off, or the side is a
/// bid and a pause stands, no fact is read.
function lane() external view returns (uint256 laneWord, uint256 laneConfig, uint256 pending);
/// @notice Write-once: the strict bit, the credit path and the outflow caps at birth, which gives both cheap-lane
/// words their nonzero version. Only the pool's front, a front the Factory lists, may call it
/// (`NotFront`), once, from its `confirmPool`. Refused (`InvalidConfig`) where the cheap lane is on
/// already, the pool owes anything, the protocol's high-water rate is set, a pool-asset notional cap is
/// set, a spread fee is recorded, or the Factory's beacon upgrades wait less than
/// `FLAMMStore.MIN_LANE_UPGRADE_DELAY_SEC`.
/// @param strict Asks also need token 1 proven debt-free.
/// @param creditPath 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), on or off from birth, the choice of the pool's launch through
/// `PropAMMLauncher`: off as the pool's `setCreditPath(false)` leaves it, whose turn-on waits the pool's
/// delay.
/// @param outflowCaps The cheap lane's config word: bid rate (0-23), bid burst (24-47), ask rate (48-71), ask burst
/// (72-95), each an 18-bit mantissa (low bits) and a 6-bit exponent of 10, in 1e-6 of a whole out token (one
/// base unit under six decimals); a rate is per second.
function initLane(bool strict, bool creditPath, uint96 outflowCaps) external;
/// @notice Write-once, in `initLane`'s transaction alone: a pool that pays pairs past the hook pair takes their
/// settings at birth, each of which would otherwise wait the pool's delay. Only the pool's front calls it
/// (`NotFront`, as outside that transaction). `InvalidConfig` for a mask past the pairs below, or a caps
/// array that is not one entry per token from 2 on.
/// @param lanePairs The ordered pairs past the hook pair the cheap lane may settle, in `hookPairs`' layout (bit
/// `16 * i + j`: a fill paying token `j` for token `i`): pairs of listed tokens, never the hook pair's nor
/// a pair hook's, a listing that goes live later among them (`syncListings`).
/// @param tokenCaps The outflow caps of each token from 2 on, `tokenCaps[t - 2]`: rate (bits 0-23) and burst
/// (24-47), as `outflowCaps`' amounts.
/// @param maxDrawnTokens The Router's drawn-token limit, raised to it where it is higher (a pool that may owe
/// several tokens at once).
/// @param blind The custody-blind credit law for the pool's life (`FLAMMStore.CUSTODY_BLIND`): the pool's gate
/// reads each token's gross debt against what the pool posts, none of its custody, and every indebted venue
/// within the maintainer's trigger; the cheap lane pays custody with no debt-free proof outside strict mode,
/// and a pause stops both sides; the pool draws through `refill`, the keeper's or the curator's, and its
/// credit path is off at birth: the curator may turn it on through the pool's delay on three tokens or more
/// with token 1 keeping no buffer (`setCreditPath`), and its own swap then draws token 1 on the hook pair
/// alone, posting nothing of the idle floor (`FLAMMLawLib.lawBound`). The front binds such a pool's listings PRINT or WORD, never NONE, on a pair
/// with or without a price source (`PropAMMLandingDesk.bindListing`): PRINT on a priced pair with the
/// minimum fill at least the chain's floor, WORD on any pair where the desk has a word key and the pair's
/// class is not PRINT only, so a WORD fill pays out at the desk's signed word, with no price fence, within
/// the pool's custody, outflow buckets and debt caps.
function initLaneTokens(uint256 lanePairs, uint48[] calldata tokenCaps, uint8 maxDrawnTokens, bool blind)
external;
/// @notice Whether the pool's credit law is custody-blind, set at the cheap lane's birth for good
/// (`initLaneTokens`): the front then binds the pool's listings PRINT or WORD, on a pair with or without a
/// price source, and refuses NONE, at the pool's birth or after it (`initLaneTokens`' `blind`).
function custodyBlind() external view returns (bool);
/// @notice Asks the front again which pairs past the hook pair it prices (`IPairHook.pricesPair`) and opens or
/// closes each by its answer, to the pool's own swap and to the cheap lane alike, so a listing that goes
/// live after the pool's birth trades, and one retired stops. It asks of the cheap lane's pairs, and of
/// every other pair the pool holds open for the front, which may only close; it opens no pair outside the
/// cheap lane's pairs, claims none a pair hook prices and closes one only where the front answers that it
/// does not price it; the curator's trade mask still gates every pair. Permissionless and idempotent: the
/// front calls it when a listing goes live or retires. `InvalidConfig` where the cheap lane is off. A front
/// `pricesPair` that gives no answer, a revert (a call short of gas included) or a word that is not a bool,
/// leaves that one pair as it stood, so the front's answer must not fail while the front holds its own lock
/// in that call, or the pair it was asked of does not move. The pool's pair sync at a pair hook's
/// installation or removal and at a token's listing keeps the same rule off the cheap lane's pairs: there a
/// pair may only close.
/// @return hookPairs The pool's mask of priced pairs it leaves (`FLAMM.tradablePairs`' second word).
function syncListings() external returns (uint256 hookPairs);
}
src/interfaces/core/flamm/IPairHook.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice One exact-input fill request for any two of the pool's tokens, in native units: every pair, the pool asset
/// included, and every mode (cover, borrow, rotation, custody only). Flat, so core writes it into a call in a
/// few moves. `sender` is the swap's caller. `mode` holds the `PAIR_MODE_*` bits of the plan, `features` the
/// pool's `FEATURE_*` bits, `protocolFeeBp` the pool's protocol spread rate (zero where none is set).
/// `IFLAMM.pairRequest` reads the request a swap would send now.
/// @dev Core refuses:
/// - a fill whose `feeWad` is under `feeFloorWad` or over `feeCapWad` (`FeeOutOfBounds`);
/// - one whose net output's value at `usdOut` is outside `bandWad` around the input's value at `usdIn`
/// (`PriceBand`; both prices zero on a pool with no band, which checks none);
/// - one whose `protocolFeeOut` passes `feeOut` or `net * protocolFeeBp / (1e4 - protocolFeeBp)`, where `net` is
/// `grossOut - feeOut` (`FeeOutOfBounds`).
///
/// The amounts:
/// - `amountIn` is at most the input's notional cap.
/// - `maxAmountOut` is core's ceiling for this request, not the pool's depth (where the band's top for the input
/// is under custody it counts the output's supply whole, as no fill the band passes reaches it), less, at a
/// notional rate, the room the protocol's floor needs beside a payout under it: the payout's ceiling times
/// `1e7 / (1e7 + extension)`, rounded down.
/// - Each token's legs are held, supplied, posted and owed, native, as the plan read them.
/// - `restHeldN18` and `restOwedN18` are the USD values (WAD) of every other token's held, supplied and posted
/// legs and of its owed leg, at the feed, so a hook that values the whole pool book (`EverlongHook`'s leverage)
/// sees the tokens outside the pair.
struct PairRequest {
address sender; // the swap's caller
address tokenIn; // the token the pool takes
address tokenOut; // the token the pool pays
uint8 indexIn; // `tokenIn`'s index in the pool
uint8 indexOut; // `tokenOut`'s index in the pool
uint16 mode; // `PAIR_MODE_*` bits
uint16 features; // the pool's `FEATURE_*` bits
uint16 protocolFeeBp; // the pool's protocol spread rate, bp
uint64 feeFloorWad; // the least `PairFill.feeWad`, WAD
uint64 feeCapWad; // the most `PairFill.feeWad`, WAD
uint64 bandWad; // the tighter of the two tokens' swap bands, WAD
uint256 usdIn; // `tokenIn`'s USD per whole token, WAD
uint256 usdOut; // `tokenOut`'s USD per whole token, WAD
uint256 amountIn; // the input, `tokenIn` base units
uint256 maxAmountOut; // core's ceiling on the net output, `tokenOut` base units
uint256 heldIn; // `tokenIn` held, base units
uint256 suppliedIn; // `tokenIn` supplied, base units
uint256 postedIn; // `tokenIn` posted, base units
uint256 owedIn; // `tokenIn` owed, base units
uint256 heldOut; // `tokenOut` held, base units
uint256 suppliedOut; // `tokenOut` supplied, base units
uint256 postedOut; // `tokenOut` posted, base units
uint256 owedOut; // `tokenOut` owed, base units
uint256 restHeldN18; // every other token's held, supplied and posted legs, USD, WAD
uint256 restOwedN18; // every other token's owed leg, USD, WAD
/// @dev In bits 0-15 the pair's notional rate, parts per 1e7 of the net payout, by the pair's kind
/// (`FLAMMStore.rateOf`; zero where none is set): the floor of the protocol's part, which core books whatever
/// `protocolFeeOut` reports ({PairFill}). In bits 16-31, where `features` carry `FLAMMStore.OPERATOR_SHARE`,
/// the operator's share's rate, bp, which core books beside the part but on a cover ({PairFill}); zero
/// otherwise. A later core may widen this word without changing this interface's selectors; a hook must not
/// read more into it than that.
uint256 extension;
}
/// @notice A hook's fill, native units: input used (at most `amountIn`), gross output, the fee kept from it, the
/// fee rate the fill was computed at, two words the pool only reports, and the protocol's share of this fill's
/// spread in the output token (`protocolFeeOut`), which the pool never mints. `spotAfterN36` is the hook's
/// marginal price after the fill (a fill the hook absorbs without moving its price, such as EverlongHook's
/// leverage fills, reports it unchanged); `xAfter` is a coordinate the hook defines.
/// @dev Core pays `grossOut - feeOut`, never alters a committed fill, and asks the hook once per swap. Only the hook
/// that prices the pair sets a swap's amounts, and no hook runs on a deposit's exit or a redemption.
///
/// The protocol's part core books is its own, in kind, out of the pool's custody in the token paid, after
/// `fillPair` returns: `max(min(protocolFeeOut, bound), net * rate / 1e7)`, where `rate` is the notional rate
/// (`extension`'s bits 0-15) and `bound` is `net * band * protocolFeeBp / (1e18 * 1e4)` (`band` the wider of
/// `bandWad` and core's least fee band), cut to the room the net leaves under the request's ceiling
/// (`maxAmountOut * rate / 1e7 + maxAmountOut - net`).
/// It can be more or less than `protocolFeeOut`, and more than `feeOut`; the pool's `Swap` log reports it. A hook
/// that keeps its own reserves must take out the part core booked, not its own report, or re-read its legs from
/// each request.
///
/// Where the pool sets an operator's share (`FLAMMFloatLib.setOperatorShareBp`, rate `share` in bp; the request's
/// `features` carry `FLAMMStore.OPERATOR_SHARE` then), core books it beside the part, the same way and in the same
/// token: at most `min((base - part) * share / 1e4, room - part)` where `base`, the fee read at most at the fill's
/// own rate (`min(feeOut, net * feeWad / (1e18 - feeWad))`, none at a rate of 1e18), passes the part; `room` is
/// the part's. A cover (`PAIR_MODE_COVER`) pays no share: its fee past the part stays with the LPs. Core cuts it
/// further, never past that bound: where a live pair owes the token paid, `room` counts at `1 - ltv * phiWad`, the
/// highest of those pairs', as a payout room may credit the input and the share brings none; on a rotation, to
/// what the output's custody leaves past the rotation's keep, the net and the part; to the room left in the
/// operator's counter of the token paid and to what fits beside the part under 2^128; and at its booking to what
/// custody holds beside the fee owed and the part (`FLAMMLane.post`). No log reports it per fill. A hook that
/// keeps its own reserves must take it out too: the bound is at least what core books. A hook whose spread is in
/// its price reports no fee but its protocol's part; with the share on it may report the spread it earned as
/// `feeOut` instead, and that spread's rate of the gross as `feeWad`, within the request's fee floor and cap (the
/// PropAMM front reports the desk's edge, capped at the band of the quote leg), so the share is of that spread.
struct PairFill {
uint256 amountInUsed; // the input used, base units; zero or past `PairRequest.amountIn` refuses (`FillInvalid`)
uint256 grossOut; // the gross output, base units
uint256 feeOut; // the fee kept from `grossOut`, base units; a zero net refuses (`FillInvalid`)
uint256 feeWad; // the rate the fill was computed at, WAD
uint256 spotAfterN36; // reported only
uint256 xAfter; // reported only
uint256 protocolFeeOut; // the hook's report of the protocol's share, `tokenOut` base units
}
/// @notice The one pricing interface, of the swap hook and of a pair hook, for every pool and pair: the quote, a view,
/// and the committed fill. Equal requests get equal answers, and the request never lets the sender set the
/// price. A hook must not price from the pool's balances: a fill sent first shows it the input, a quote and a
/// pulled fill do not.
interface IPairHook {
/// @notice The fill `r` would get now, with nothing written: the one `fillPair` commits on the same state. The
/// pool's `previewSwap` reads it by a static call and runs the swap's checks on the answer, asking again at
/// the input the hook used while that is under the one asked. A revert bubbles up through the preview; an
/// answer under seven words reverts empty.
/// @param r The request.
/// @return The fill, native units.
function quotePair(PairRequest calldata r) external view returns (PairFill memory);
/// @notice The committed fill of `r`. The pool's swap calls it once, before any token of the fill moves, then runs
/// its checks on the answer ({PairRequest}, {PairFill}) and settles it. A revert bubbles up through the
/// swap, a failed check reverts the hook's writes with it, and an answer under seven words reverts empty.
/// @param r The request.
/// @return The fill, native units.
function fillPair(PairRequest calldata r) external returns (PairFill memory);
/// @notice Whether this hook prices fills of `tokenIn` for `tokenOut` on `pool`. Core asks it for every ordered
/// pair of the pool's listed tokens when the hook is installed and when a token is listed, and caches the
/// answers in one word: a pair the hook does not price never trades, whatever the curator's trade mask
/// says. A cheap-lane pool asks its front again at the listings' resync (`IFLAMMLane.syncListings`) and at
/// a pair hook's removal, and at a pair hook's schedule and installation of the pairs that hook would
/// price, which the front must not: there a front's revert reads as a pair it prices, and the hook's as one
/// it does not. A view that never reverts: equal arguments, equal answer; on a cheap-lane pool a sync reads
/// an answer not given (a revert, or a word that is not a bool) as no change to that pair.
/// @param pool The pool asked of.
/// @param tokenIn The token the pool would take.
/// @param tokenOut The token the pool would pay.
/// @return Whether the hook prices that ordered pair on `pool`.
function pricesPair(address pool, address tokenIn, address tokenOut) external view returns (bool);
}
/// @notice A pool's second hook, for named pairs (`FLAMMFloatLib.setPairHook`): the hook and the unordered pairs it
/// prices, bit `160 + hi * (hi - 1) / 2 + lo` of `mask` for tokens `lo < hi`; zero when none. The curator
/// installs or replaces it after D, the pool's own delay (`governanceDelaySec`), the curator's choice and risk;
/// a removal, the curator's or the guardian's, applies at once.
interface IPairHookSlot {
/// @notice Installs, replaces or removes the pair hook. A nonzero `hook` is the curator's: the first call schedules
/// it, the identical call applies it from D on and for one more D (`HookSetNotReady` sooner), and the
/// curator or the guardian cancels it (`FLAMMAdmitLib.cancel`). A zero `hook` with a zero `mask` removes the hook
/// at once and closes its pairs. `NotGuardianOrCurator` for any other caller, `GuardianMayOnlyTighten` for
/// a guardian naming a hook, `HookInvalid` for a hook that fails its identity or capability checks, and
/// `InvalidConfig` for a removal with a mask or with no hook set, a pool whose credit law is custody-blind,
/// a mask empty or naming a pair outside its tokens or the hook pair, or a pair the hook does not price
/// both ways or, on a cheap-lane pool, one the front prices. The full rules are on
/// `FLAMMFloatLib.setPairHook`.
/// @param hook The hook; zero removes the one set.
/// @param mask The unordered pairs it prices, in the layout above.
function setPairHook(address hook, uint256 mask) external;
/// @notice The pair hook and its pairs; both zero when none.
/// @return hook The pair hook.
/// @return mask The unordered pairs it prices, in the layout above.
function pairHook() external view returns (address hook, uint256 mask);
}
/// @dev The hook prices fills whose payout may move a debt the output backs onto the input (`PAIR_MODE_ROTATE`); core
/// plans no rotation unless the swap hook declares it and, while one is set, the pair hook too. Its sibling
/// `HOOK_CAP_*` bits are in IHookCapabilities.sol.
uint256 constant HOOK_CAP_ROTATE = 1 << 3;
// `PairRequest.mode`
/// @dev The input is owed: the settlement repays it first and draws nothing.
uint16 constant PAIR_MODE_COVER = 1 << 0;
/// @dev A payout past custody and free collateral may draw the output on its pair.
uint16 constant PAIR_MODE_BORROW = 1 << 1;
/// @dev A payout may move a debt the output backs onto the input.
uint16 constant PAIR_MODE_ROTATE = 1 << 2;
/// @dev The pool is paused: the fill runs only where it draws nothing and lends nothing.
uint16 constant PAIR_MODE_PAUSED = 1 << 3;
/// @dev The venue legs were not read (a fill from custody alone): the supplied, posted and owed legs are zero.
uint16 constant PAIR_MODE_HELD_ONLY = 1 << 4;
/// @dev The input repays all of one debt and the output is borrowed on another pair (a crossing).
uint16 constant PAIR_MODE_CROSS = 1 << 5;
/// @dev Some fence holds a pool part (`FLAMMStore.parted`): a fenced venue's position or a fenced token's custody that
/// the pool still owns a part of is out of the book, so the request's legs and its rest of the book leave it out
/// until the part returns or is given up. A hook that marks the whole book from them reads one short of that part.
/// A custody-only request (`PAIR_MODE_HELD_ONLY`) does not carry it: its venue legs read zero either way.
uint16 constant PAIR_MODE_PARTED = 1 << 6;
src/libraries/Constants.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
// The protocol's shared units and delay values, each written once. A contract that names one of its own (a public
// getter, or a constant other files read through it) declares it as this file's value, at its own type, so a change
// of a value here reaches every rule that shares it, and a rule that must differ changes its own line alone. The
// pool's own delay names keep their literal values, as a constant read through another can compile to other code:
// `DelayLib.GRACE`, `PriceFeed.REPLACE_DELAY`, `FLAMMFactory.MIN_FEE_DELAY_SEC` and the pool store's three
// `MIN_*_DELAY_SEC`. The shared-constants test holds each of them to its value here.
// ---------------------------------------------------------------- units
/// @dev One in 18 decimals: the unit of every `*Wad` ratio, of LTVs, bands, rates and USD prices.
uint256 constant WAD = 1e18;
/// @dev Parts per million: the unit of a rate, a rung's offset and a word's skew.
uint256 constant PPM = 1e6;
/// @dev The first amount past 128 bits: an output cap, and the first amount past a door's grid.
uint256 constant CAP_128 = 1 << 128;
// ---------------------------------------------------------------- delays
/// @dev The least delay a pool may take for its operator's own changes: a pool's `governanceDelaySec` at birth, a
/// launched pool's delay, its authority's delay, and the least a listing's change reads as the pool's own.
uint32 constant POOL_DELAY_FLOOR_SEC = 1 hours;
/// @dev What a protocol-level loosening waits: the front's timelock, a feed's replacement, a protocol fee's rise, a
/// band ceiling's raise, the beacon delay a cheap lane asks for, a credit door's config, and a listing's change
/// where its pool's own delay cannot be read.
uint32 constant PROTOCOL_DELAY_SEC = 10 days;
/// @dev How long a due change stays applicable outside the pool, whose own window is its delay or a day, whichever
/// is longer: past it the change has lapsed.
uint32 constant CHANGE_WINDOW_SEC = 7 days;
src/libraries/DelayLib.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The clock of a delayed change, one rule for the contracts that use it, `FLAMMFactory` and `PriceFeed` (a
/// pool's own delayed entries keep their table and window, `FLAMMAdmitLib.due`). A change is one entry under
/// an id its contract derives, `keccak256(abi.encode(selector, subject))`: the setter's selector and the token,
/// pool or kind it sets (zero for a contract-wide setting; a setting of several fields adds the field), so a
/// new change of the same setting replaces the last and restarts its delay.
/// The entry keeps a tag, which commits to the value (the value itself where it fits in 192 bits, else
/// {tagOf} of its encoding; a tag is read modulo 2^192), and the time it falls due. It applies only from that
/// time until `GRACE` after it; later it has lapsed, applies no more and reads as none, and the next schedule
/// overwrites it. The scheduler applies a change by repeating the identical call ({stage}); a change anyone may
/// execute is spent by {consume}. Who may schedule, apply and cancel is the calling contract's check: the
/// library keeps the clock, the tag and the log.
/// The clock itself is one rule, {phase}: a change waits until its due time, is due from that second until
/// its window after it, both ends included, and has lapsed from the next second on. The contracts outside a
/// pool that keep a schedule in storage of their own, under their own events, errors and roles, read their
/// verdict there, each with its own window: a listing's changes, `PropAMMDue`; the front's registry path; the
/// stock module's override. `DelayedAuthority` and `PropAMMDoorConfig` keep their schedules as entries here,
/// under these events and errors and their own windows ({entry} and {take}, each with a window): the
/// authority's `EXECUTION_WINDOW_SEC`, and for the door config a window without end, as its scheduled calls
/// never lapse. The entries under `GRACE`, which `FLAMMFactory` and `PriceFeed` keep, and the failed feed's
/// shorter window in `PriceFeed`, keep their own comparisons, so the pool's code is unchanged: {phase} gives
/// the same verdict at every edge of a window.
/// @dev The entry word: tag (bits 0-191) | due time, unix seconds (bits 192-255); zero is none, and a due time is never
/// zero. The table is one mapping in the ERC-7201 namespace `everlong.storage.delay` ({table}), so in every
/// contract that uses it the entry of `id` sits at `keccak256(abi.encode(id, LOCATION))`; a contract may pass
/// another mapping of the same shape instead. Every function is internal: nothing is deployed for it.
library DelayLib {
/// @notice How long a due change stays applicable: one rule for every change.
uint256 internal constant GRACE = 7 days;
/// @dev keccak256(abi.encode(uint256(keccak256("everlong.storage.delay")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant LOCATION = 0x2a4f7cf5e765882922ccc94a8378a7f0a1255cce43305f000a2a2e7c1fb9d500;
/// @dev The entry's tag bits.
uint256 private constant TAG_MASK = (1 << 192) - 1;
/// @notice The clock's verdict on a scheduled change ({phase}): none stands; it waits its due time; it is due,
/// from its due second until its window after it; it has lapsed.
enum Phase {
None,
Waiting,
Due,
Lapsed
}
/// @notice A change scheduled under `id`, applicable from `dueAt` until its window after it: `GRACE` for the entries
/// that keep it, the caller's own window for {entry} and {take}, which the door config's entries never
/// reach, as its scheduled calls never lapse. `data` is the change as its contract encodes it, for
/// readers: the entry keeps only the tag.
event ChangeScheduled(bytes32 indexed id, uint256 dueAt, address indexed by, bytes data);
/// @notice The change under `id` dropped: cancelled, replaced by a tightening that applied at once, or spent
/// unapplied by its contract (`PriceFeed.executeOracle`).
event ChangeCancelled(bytes32 indexed id, address indexed by);
/// @notice No change stands under `id`, or another tag does.
error NotScheduled(bytes32 id);
/// @notice The change under `id` falls due only at `dueAt`.
error NotDue(bytes32 id, uint256 dueAt);
/// @notice The change under `id` passed its window unapplied: `GRACE` ({consume}), or the caller's own ({take}). The
/// door config's entries have no end and never raise it.
error Lapsed(bytes32 id);
/// @dev The namespace's layout: the table, from its base.
struct Table {
mapping(bytes32 => uint256) entries;
}
/// @notice The table in the namespace.
function table() internal pure returns (mapping(bytes32 => uint256) storage t) {
assembly ("memory-safe") {
t.slot := LOCATION
}
}
/// @notice The one clock rule of a delayed change due at `dueAt`, unix seconds (zero: none), which stays
/// applicable for `window` seconds after it: `Waiting` before `dueAt`, `Due` from `dueAt` to
/// `dueAt + window`, both included, `Lapsed` after. A window of `type(uint256).max` never lapses.
function phase(uint256 dueAt, uint256 window) internal view returns (Phase) {
if (dueAt == 0) return Phase.None;
if (block.timestamp < dueAt) return Phase.Waiting;
return block.timestamp - dueAt > window ? Phase.Lapsed : Phase.Due;
}
/// @notice {phase} of `tag` under the entry word `e`, as a table keeps one ({word}): `None` where the word is
/// empty or keeps another tag. `tag` is the entry's own 192 bits.
function phaseOf(uint256 e, uint256 tag, uint256 window) internal view returns (Phase) {
if (e == 0 || e & TAG_MASK != tag) return Phase.None;
return phase(e >> 192, window);
}
/// @notice The entry word of `tag`, 192 bits, due at `dueAt`.
function word(uint256 tag, uint256 dueAt) internal pure returns (uint256) {
return tag | (dueAt << 192);
}
/// @notice The tag of a value too wide for the entry: the top 192 bits of its encoding's hash.
function tagOf(bytes memory data) internal pure returns (uint256) {
return uint256(keccak256(data)) >> 64;
}
/// @notice The change standing under `id`, its tag and due time; a lapsed one, or none, reads (0, 0).
function entry(mapping(bytes32 => uint256) storage t, bytes32 id) internal view returns (uint256 tag, uint256 dueAt) {
uint256 e = t[id];
dueAt = e >> 192;
if (dueAt != 0 && block.timestamp <= dueAt + GRACE) tag = e & TAG_MASK;
else dueAt = 0;
}
/// @notice {entry} under the caller's own `window` in place of `GRACE`.
function entry(mapping(bytes32 => uint256) storage t, bytes32 id, uint256 window)
internal
view
returns (uint256 tag, uint256 dueAt)
{
uint256 e = t[id];
dueAt = e >> 192;
Phase p = phase(dueAt, window);
if (p == Phase.Waiting || p == Phase.Due) tag = e & TAG_MASK;
else dueAt = 0;
}
/// @notice Schedules `tag` under `id` for `delay` from now, replacing whatever stood there; logs `data`. Every
/// caller's delay fits 32 bits of seconds, so the due time fits its 64.
function schedule(mapping(bytes32 => uint256) storage t, bytes32 id, uint256 tag, uint256 delay, bytes memory data)
internal
returns (uint256 dueAt)
{
dueAt = block.timestamp + delay;
t[id] = (tag & TAG_MASK) | (dueAt << 192);
emit ChangeScheduled(id, dueAt, msg.sender, data);
}
/// @notice The identical call's rule: true where `tag` stands under `id`, due and not lapsed, which it clears so
/// the caller applies it now; `NotDue` while that same tag waits; otherwise (none, another tag, or one
/// lapsed) it schedules `tag` for `delay`, replacing what stood, and returns false. So an apply that comes
/// after its change lapsed or was cancelled does not fail: it schedules the change afresh, for the full
/// delay, and applies nothing; the change's applied event, not the call's success, shows it landed.
function stage(mapping(bytes32 => uint256) storage t, bytes32 id, uint256 tag, uint256 delay, bytes memory data)
internal
returns (bool)
{
uint256 e = t[id];
tag &= TAG_MASK;
if (e != 0 && e & TAG_MASK == tag) {
uint256 dueAt = e >> 192;
if (block.timestamp < dueAt) revert NotDue(id, dueAt);
if (block.timestamp <= dueAt + GRACE) {
delete t[id];
return true;
}
}
schedule(t, id, tag, delay, data);
return false;
}
/// @notice An explicit execution of `tag` under `id`: clears it once due and before it lapses, else reverts
/// (`NotScheduled` for none or another tag, `NotDue`, `Lapsed`).
function consume(mapping(bytes32 => uint256) storage t, bytes32 id, uint256 tag) internal {
uint256 e = t[id];
if (e == 0 || e & TAG_MASK != tag & TAG_MASK) revert NotScheduled(id);
uint256 dueAt = e >> 192;
if (block.timestamp < dueAt) revert NotDue(id, dueAt);
if (block.timestamp > dueAt + GRACE) revert Lapsed(id);
delete t[id];
}
/// @notice An explicit execution of whatever stands under `id`, under the caller's `window`: clears it once due
/// and before it lapses, and returns its tag; else reverts (`NotScheduled` for none, `NotDue`, `Lapsed`).
function take(mapping(bytes32 => uint256) storage t, bytes32 id, uint256 window) internal returns (uint256 tag) {
uint256 e = t[id];
if (e == 0) revert NotScheduled(id);
_spend(t, id, e, window);
tag = e & TAG_MASK;
}
/// @dev Clears the entry `e` under `id` where it is due under `window`; `NotDue` earlier, `Lapsed` later.
function _spend(mapping(bytes32 => uint256) storage t, bytes32 id, uint256 e, uint256 window) private {
Phase p = phase(e >> 192, window);
if (p == Phase.Waiting) revert NotDue(id, e >> 192);
if (p != Phase.Due) revert Lapsed(id);
delete t[id];
}
/// @notice Cancels the change under `id`, a lapsed one included; `NotScheduled` where none stands.
function cancel(mapping(bytes32 => uint256) storage t, bytes32 id) internal {
if (t[id] == 0) revert NotScheduled(id);
delete t[id];
emit ChangeCancelled(id, msg.sender);
}
/// @notice A tightening's drop: clears the change under `id` where one stands, logged as a cancel.
function drop(mapping(bytes32 => uint256) storage t, bytes32 id) internal returns (bool dropped) {
if (t[id] != 0) {
delete t[id];
emit ChangeCancelled(id, msg.sender);
dropped = true;
}
}
}
src/propamm/PropAMMDeskCellCode.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The desk cell's creation code as every build deploys it: `PropAMMDeskCell` as solc 0.8.35 compiles it under
/// the build profile (via-IR, 100 runs), its metadata included, frozen so that a desk's cell address (CREATE2
/// of the front, `(1 << 252) | desk` and `HASH`) never moves with a later compiler, a setting or an edit. A
/// test pins the bytes to the source (metadata aside) and `HASH` to the bytes, and the front refuses an upgrade
/// to a build answering another `CELL_CODEHASH` once any desk exists.
library PropAMMDeskCellCode {
bytes internal constant INIT =
hex"60a0806040523460285733608052610f1c908161002d8239608051818181600b01526103d60152f35b5f80fdfe60806040523461"
hex"0128577f00000000000000000000000000000000000000000000000000000000000000003314610990576001546001600160a01b"
hex"038116801515905f3560e01c90331482166351554f5482141761012c57631626ba7e03610128575f916002548033149015151661"
hex"0097575b50506001600160e01b03195f526100885760205ff35b630b135d3f60e11b5f5260205ff35b60015f54603f1c16610072"
hex"5760035491821515161561007257600435602435923684106100c6575b5050610072565b83600401359060418210153660248488"
hex"0101111516368310166100ea575b506100bf565b6100f78560240184610a7d565b14610103575b806100e4565b61011f94506040"
hex"190192606501916001600160a01b0316610af2565b5f8080806100fd565b5f80fd5b825f5f925f36936351554f54831461094a57"
hex"5b813560f81c6001833560fa1c16601802602f038301915f9660108316610938575b5f9160088416610928575b84935f92602082"
hex"16610912575b60018060075f1987011015818b3560fa1c1615178a3560fd1c16168160028516158b3560fb1c1616178184166041"
hex"028a8a03018314156d0c0800000008000000000000000f60941b8b351615151717960195865b8881106108fb57506108e7576351"
hex"554f5489146107e3575b5060018260bf1c166001883560fa1c16036107d057637fffffff8260a01c16637fffffff883560d81c16"
hex"036107bd57863560fa1c600116156107625763ffffffff873560581c16916103e8420261ffff81818460d01c1665ffffffffffff"
hex"8c3560581c1601109260c01c160165ffffffffffff893560581c16111782151761074f575b5f5499637fffffff883560d81c1663"
hex"ffffffff8c60201c160361073b575f94600183166106cc575b883560fa1c6001161561068e5765ffff000000008c63ffffffff81"
hex"1691829160901c161765ffffffffffff8b3560581c16111590151516617fff8d60701c16617fff8b3560c81c16101761067c575b"
hex"60018c60cd1c168015906002851661064f575b50156105f5575b8a9b506008839b9a9b166105cb575b50873560381b690fffffff"
hex"ffffffffffff60801b811684179360018a3560fa1c16610595575b505060cf1b600160ce1b8835602c1c161790600160cd1b9060"
hex"cc1b168460cc1b171790617fff60701b873560581c1665ffffffffffff60401b883560581c161790677fffffff00000000883560"
hex"b81c161717175f55610538575b5050503560fa1c60011661050f575b6104c25782806103a257005b62ffffff5f3560c81c16636f"
hex"00afef60e11b610100526040610104525f35600b1a61012452816101445281803603610164377f00000000000000000000000000"
hex"000000000000000000000000000000000000005f5260ff600b5363ffffffff5f3560a81c166020527f21c35dbe1b344a2488cf33"
hex"21d6ce542f8e9f305544ff09e4993a62319a497c1f6040526055600b2060145261d6945f5260016034536017601e206001600160"
hex"a01b0316603f603e8301048201610fa0015a106104b3575f92813b61049b575b50505015610475575b005b7fe958fda8f4697bf6"
hex"4fb72adb02b5c42b7a02529c125d4379a7322c19fa08837d5f80a1005b5f8094508093926101009260640193f181808061046a56"
hex"5b631105e59760e31b5f5260045ffd5b6351554f54036104735780806008146104fe576009146104ee57632a62b76f60e21b5f52"
hex"60045260245ffd5b50631ece0cb360e01b5f5260045ffd5b50506361330e9360e01b5f5260045ffd5b7f5f51a2679791c14504a0"
hex"315e6dd07f842f3b15cc7cea98909f754edea4056eec5f80a1610396565b617fff60d21b8435600a1b169060d01b1760ff60c81b"
hex"843560101c1663ffffffff60a81b4260a81b161717905b828110156103875760018101356701fffdffffffffff60a81b19168217"
hex"601082355f1a0155869450602101610565565b610fff60c01b821665ffff000000008b3560581c1663ffffffff42161760901b17"
hex"61ffff60801b92909216171792508c8061032d565b604081901b65ffffffffffff60401b1660509190911b6001600160801b0319"
hex"16176004558c610307565b916001893560921c16875b898110610639575061062457999a8b9a600a191660cc9190911c60021617"
hex"916102f8565b50505050505050505091505060079081610396565b906021906001600f818501351614179101610600565b905080"
hex"60088516156102f1576001915061066a575b8e6102f1565b5060045460e01c8160901c1015610664565b50505050505050505090"
hex"809250610396565b8363ffffffff8d16036102de576351554f548a14617fff8d60701c1601617fff8a3560c81c1610156102de57"
hex"50505050505050505090809250610396565b9450600354801561072657601960f81b5f523060601b600252466016528888038960"
hex"36376107058989038a018a8a036036015f20610a7d565b036107125760019461028f565b50505050505050509150506008908161"
hex"0396565b50505050505050505091505060089081610396565b505050505050505091505060069081610396565b50505050505050"
hex"91505060059081610396565b4363ffffffff169150600f870135602081901c6001600160a01b031680154190911415176107a957"
hex"63ffffffff168214610267575050505050505091505060049081610396565b505050505050505091505060039081610396565b50"
hex"50505050505091505060029081610396565b5050505050505091505060019081610396565b6001600160a01b0383161561071257"
hex"6108c9907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f5f527ffaa4dd5726619f09f64eb5f3"
hex"95d6fba379e8e46ea9b3d76bb593cf9a8771916d6020527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f"
hex"298b8bc6604052466060523060805260a05f20818a610100377ff669272e75dd8f85bfc41b8eddaec7a30f57c897ff043dad45b5"
hex"623251e433bf5f52816101002060205260405f20906119015f526020526040528801808d360303906042601e2060018060a01b03"
hex"8616610af2565b156108d4578b6101e4565b5050505050505091505060089081610396565b505050505050505091505060099081"
hex"610396565b600781355f1a5f19011015909117906021016101cc565b959250600183355f1a9384602102010195610178565b6016"
hex"8501943560501c925061016b565b9296506003873560e81c970192610160565b9493505061ffff5f3560801c169260109061ffff"
hex"5f3560901c16908282870101361060015f35600b1a111761098057509461013f565b9550505091505060099081610396565b6001"
hex"355f3560f81c60018114600482148117610a77575080600214610a1d5780600314610a0457806005146109e9576006146109ca57"
hex"5f80fd5b6001546001600160a01b03918216911681148115151661012857600355005b5060015460018160bf1c16901517811515"
hex"1661012857600255005b6001603f1b608083901c677fffffff0000000016175f55005b506003546001600160a01b038216801582"
hex"15159190921416176101285760015480610a60575b506001555f54600181603f1c16610a5657005b6001603f1b185f55005b6001"
hex"60bf1b16600160bf1b1991909116175f610a43565b82610c44565b5f92916020810135916040820135851a906002601a19830110"
hex"6fa2a8918ca85bafe22016d0b997e4df60600160ff1b0385111516610abc575b50505050565b60805260a0523560c05260e05260"
hex"205f60808060015afa610ae1575b5f808080610ab6565b60203d03610ad8575f519150610ad8565b91905f94939160418314610b"
hex"7e575b8515610b0d5750505050565b833b15610ab6578291630b135d3f60e11b6101005261010452604061012452816101445261"
hex"0164375f8052618ca05a1015610b4a575b8080610ab6565b6020916101005f9260640191617530fa610b66575b5f80610b43565b"
hex"9050630b135d3f60e11b5f5114601f3d111690610b5f565b83610b898284610a7d565b03610b015760019550610b01565b905f92"
hex"918015610bf0578060025403610bf0576102006064610100610220936305b20eb760e21b82524161010452426101245242610144"
hex"525afa610bd85750565b61024051908160051b6060013d146003831416610bf4575b5050565b6102605160018060a01b03811690"
hex"62ffffff80747fffff8fffffffffffffffffff0000ffffffffffff60401b196102a051161594169160a01c161490418114901515"
hex"161616610c405750565b9150565b6020915f549063ffffffff4316905f5f92600185603f1c168163ffffffff8716141715610e0b"
hex"575b506fffff000000000000ffffffffffffffff84169260018560cd1c16610dee575b50505f9260018560a81c16610cda575b50"
hex"610cb1575b5f52825260a31c166020015ff35b7f116df762c24db37e3f3fa41971b3681062ca1382e34ea2e117fd3f5066ad93eb"
hex"5f80a1610ca3565b60ff8560a01c1690815f14610d07575060088110610cfb575b505b5f610c9d565b6010015492505f610cf356"
hex"5b919350508060901c65ffffffffffff81169163ffffffff8116918260018360ce1c16610dd3575b5050603f81605a1c169162ff"
hex"ffff60e81b8260191b16617fff60d21b8360621b161790600160d11b8360061b16600160d01b8460041b16179060ff60c81b8460"
hex"a81b169060a81b1717179261ffff60981b8260181b1661ffff60881b8360281b1617906101ff60781b8360481c169060481b1717"
hex"91602781106303ffffff8360401c1602906008011b90600160108260c51c169160ca1c166002031717171791610cf5565b65ffff"
hex"00000000821617935063ffffffff1691505f80610d2e565b9290919215610e01575b17905f80610c8d565b6004549150610df856"
hex"5b610e2685881c637fffffff166001600160a01b038816610b97565b15610c6c5790508192506102805163ffffffff6102605160"
hex"b81c169060018660cd1c16610eca575b80881c9160e01b906bffffffffffffffffffffffff60801b9060801b1665ffffffffffff"
hex"60401b83161717946102a0516001607f1b93677fffffff00000000600160cc1b9489151560cd1b90617fff60701b161793161717"
hex"17171792600192610eb8575b5f610c6c565b80845f5515610eb25780600455610eb2565b60045460e01c828111610ede575b5061"
hex"0e4e565b91505f610ed856fea26469706673582212202f8d36b8f4ee6660d508bf27233369cb093dacf796a87f46b711a3ff2833"
hex"743264736f6c63430008230033";
bytes32 internal constant HASH = 0x39d7e60cec78d8381afa4fbfb55d5bc687168a5d4e9cac240583e7ec5bbabfa0;
}
src/propamm/PropAMMDeskCode.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The desk contract's creation code as every builder build deploys it: `PropAMMDesk` as solc 0.8.35 compiles
/// it under the build profile (via-IR, 100 runs), its metadata included, frozen so that a desk contract's
/// address (CREATE2 of the front, `(1 << 252) | desk` and `HASH`) never moves with a later compiler, a setting
/// or an edit. A test pins the bytes to the source (metadata aside) and `HASH` to the bytes, and the front
/// refuses an upgrade to a build answering another `CELL_CODEHASH`.
library PropAMMDeskCode {
bytes internal constant INIT =
hex"60a0806040523460285733608052610e16908161002d82396080518181816006015261030a0152f35b5f80fdfe60806040527f00"
hex"00000000000000000000000000000000000000000000000000000000000000331434610935575b61079d576001546001600160a0"
hex"1b038116801515905f3560e01c6351554f54811433831484161761012b57631626ba7e03610127575f9260025480331490151516"
hex"610099575b50506001600160e01b03195f525061008a5760205ff35b630b135d3f60e11b5f5260205ff35b60e01c600116156100"
hex"ab575b80610073565b6003549182151516156100a557600435602435923684106100ce575b50506100a5565b8360040135906041"
hex"82101536602484880101111516368310166100f2575b506100c7565b6100ff856024018461094c565b1461010b575b806100ec56"
hex"5b61011e94506040190192606501916109c1565b5f808080610105565b5f80fd5b5f933693508492836351554f54841461074457"
hex"5b803560f81c9560308201965f9360108216610734575b5f90600883169081610724575b8b600285169560018715893560fb1c16"
hex"168d89600189166041029103018214156e0e400800000008000000000000000f608c1b8a35161515171761070e576351554f548b"
hex"14610601575b50505060018760e01c166105ee57637fffffff8760a01c16637fffffff863560d01c16036105db57601085013560"
hex"2081901c6001600160a01b031680154190911415176105c75763ffffffff8043169116036105b4575f936001841661053e575b89"
hex"9a50610230637fffffff879b9a9b3560011a610100019960a01c168954610a66565b9163ffffffff431663ffffffff8416146105"
hex"11575b60018360cd1c168015926104da575b505015610492575b5090637fffffff60201b929160088216610461575b5083356050"
hex"1c9460cf1b90600160cd1b9060cc1b16179060cc1b690fffffffffffffffffff60801b843560401b16171792617fff60701b8116"
hex"9065ffffffffffff60401b1617913560b01c1663ffffffff431617171790555b6104145782806102d657005b62ffffff5f3560c8"
hex"1c16636f00afef60e11b610100526040610104525f35600b1a61012452816101445281803603610164377f000000000000000000"
hex"00000000000000000000000000000000000000000000005f5260ff600b5363ffffffff5f3560a81c166020527f21c35dbe1b344a"
hex"2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f6040526055600b2060145261d6945f5260016034536017601e2060"
hex"01600160a01b031690603f603e82010481016123283415150201611770015a10610405575f92823b6103ec575b505050156103b2"
hex"575b005b346103dd577fe958fda8f4697bf64fb72adb02b5c42b7a02529c125d4379a7322c19fa08837d5f80a1005b630affdf91"
hex"60e11b5f5260045ffd5b5f935083929161010091606401923491f18180806103a7565b631105e59760e31b5f5260045ffd5b6351"
hex"554f54036103b05780806008146104505760091461044057632a62b76f60e21b5f5260045260245ffd5b50631ece0cb360e01b5f"
hex"5260045ffd5b50506361330e9360e01b5f5260045ffd5b604081901b65ffffffffffff60401b1660509190911b6001600160801b"
hex"03191617610200853560011a01555f610271565b9092939495965060018535608a1c166104c857918896959493916002637fffff"
hex"ff60201b9460cc1c1690600a191617919261025c565b505050505050509050600790816102ca565b915081906104e9575b806102"
hex"54565b600191506104f8575b5f6104e3565b50843560011a610200015460e01c8260901c10156104f2565b6351554f548b14617f"
hex"ff8460701c1601617fff883560c01c161015610245575050505050505050506102ca565b9350986003549081156105a057601960"
hex"f81b5f523060601b6002524660165261057a908681038760363786808203810191036036015f2061094c565b0361058e57969788"
hex"9760019390919061020d565b505050505050915050600890816102ca565b5050505050505050915050600890816102ca565b5050"
hex"5050505050915050600490816102ca565b5050505050505050915050600390816102ca565b505050505050509150506002908161"
hex"02ca565b50505050505050915050600690816102ca565b82156106f857906106d892917f8b73c3c69bb8fe3d512ecc4cf759cc79"
hex"239f7b179b0ffacaa9a75d522b39400f5f527f28e1381bfd0db07bed5344137045cbdb23f73f4d4b67d4b3721552b86c5f9bed60"
hex"20527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604052466060523060805260a05f20818a"
hex"610100377ff669272e75dd8f85bfc41b8eddaec7a30f57c897ff043dad45b5623251e433bf5f52816101002060205260405f2090"
hex"6119015f5260205260405288018091360303916042601e20906109c1565b156106e5575f8b816101ac565b505050505050509150"
hex"50600890816102ca565b50505050505050505050915050600890816102ca565b50505050505050505050915050600990816102ca"
hex"565b60168b019a3560501c9250610162565b60338401983560e81c9450610155565b50935061ffff5f3560801c1693601061ffff"
hex"5f3560901c16968188880101361060015f35600b1a111761078c57508615341515161561013f57505050915050600990816102ca"
hex"565b9650505050915050600990816102ca565b5f3560f81c600781146108e0576021360361012757600135906001811460048214"
hex"81176108da57508060021461087c57806003146108215780600514610807576006146107e8575f80fd5b6001546001600160a01b"
hex"03918216911681148115151661012757600355005b5060018060a01b0316600154158115151661012757600255005b5060015490"
hex"6001637fffffff8360a01c1601637fffffff8260a01c16141560018360e01c1617610127576001600160a01b03909116637fffff"
hex"ff60a01b909116174360e11b6001600160e11b03191617600160e01b17600155005b5060035460018060a01b0382166001546001"
hex"637fffffff8260a01c16637fffffff8660a01c1614158215151691637fffffff43168160e11c149060e01c161617918082149015"
hex"151690151717610127576001600160bf1b0316600155005b82610b3d565b60c1360361012757604060615f376001600160a01b03"
hex"60a1358116604052604135811690602135811690600135167f1eeaa4acf3c225a4033105c2647625dbb298dec93b14e16253c423"
hex"1e26c02b1d60605fa4005b6351554f545f3560e01c141581171561002d575f80fd5b5f92916020810135916040820135851a9060"
hex"02601a198301106fa2a8918ca85bafe22016d0b997e4df60600160ff1b038511151661098b575b50505050565b60805260a05235"
hex"60c05260e05260205f60808060015afa6109b0575b5f808080610985565b60203d036109a7575f5191506109a7565b91905f9493"
hex"9160418314610a4d575b85156109dc5750505050565b833b15610985578291630b135d3f60e11b61010052610104526040610124"
hex"528161014452610164375f8052618ca05a1015610a19575b8080610985565b6020916101005f9260640191617530fa610a35575b"
hex"5f80610a12565b9050630b135d3f60e11b5f5114601f3d111690610a2e565b83610a58828461094c565b036109d0576001955061"
hex"09d0565b5f9291637fffffff8260201c1614610a7b5750565b9150565b915f93928015610ade578060025403610ade5761020060"
hex"64610100610220936305b20eb760e21b8252418760a01b1761010452426101245242610144525afa610ac6575050565b61024051"
hex"918260051b6060013d146003841416610ae3575b505050565b6102605160018060a01b03811691610100176102805160a01c1490"
hex"62ffffff80747fffff8fffffffffffffffffff0000ffffffffffff60401b196102a051161595169160a01c161416904181149015"
hex"15161616610a7b5750565b60209160015490637fffffff8260a01c169060ff8460a01c16928361010001610b67848254610a6656"
hex"5b9463ffffffff4316915f925f9660018660e01c168263ffffffff8b16141715610cf4575b5050506001603f1b8360a11c16637f"
hex"ffffff60201b8460801c166fffff00000000000000000000ffffffff881617179460018760cd1c16610cd2575b5050505f936001"
hex"8660a81c16610c16575b5050610bed575b5f52825260a31c166020015ff35b7f116df762c24db37e3f3fa41971b3681062ca1382"
hex"e34ea2e117fd3f5066ad93eb5f80a1610bdf565b90919350603f81605a1c16908060481c9262ffffff60e81b8260191b16617fff"
hex"60d21b8360621b161790600160d11b8360061b16600160d01b8460041b16179060ff60c81b9060281b1663ffffffff60a81b8460"
hex"a81b161717179261ffff60981b8260181b1661ffff60881b8360281b1617906101ff60781b81169065ffffffffffff60481b1617"
hex"1791602781106303ffffff8360401c1602906008011b90600160108260c51c169160ca1c1660020317171717915f80610bd8565b"
hex"9491929415610ce7575b5017915f8080610bc7565b610200015491505f610cdc565b610d0890846001600160a01b038c16610a7f"
hex"565b610d13575b80610b8b565b92509584955061028051600163ffffffff6102605160b81c169260cd1c16610dc1575b808a1c91"
hex"60e01b906bffffffffffffffffffffffff60801b9060801b1665ffffffffffff60401b831617179283916102a051916001607f1b"
hex"92600160cc1b9285151560cd1b90617fff60701b161791637fffffff60201b8960801c1617171717178097600197610da7575b50"
hex"610d0d565b55610db5575b81865f610da1565b81816102000155610dad565b82610200015460e01c828111610dd8575b50610d36"
hex"565b91505f610dd256fea26469706673582212200f3306925b45b1c1183058583b90a9734ee5cd1a8e6a47ea9ec4a2372bf336b8"
hex"64736f6c63430008230033";
bytes32 internal constant HASH = 0xb4f7512e65eee793ac5939d62b8383d8544eb1ca850c276fd706e97a0b7938de;
}
src/propamm/PropAMMShared.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {IFLAMM} from "src/interfaces/core/flamm/IFLAMM.sol";
import {IFLAMMLane} from "src/interfaces/core/flamm/IFLAMMLane.sol";
import {IEverlongCore} from "src/interfaces/core/IEverlongCore.sol";
import {IPropAMMFrontTypes} from "src/propamm/interfaces/IPropAMMFront.sol";
import {PropAMMStore} from "src/propamm/libraries/PropAMMStore.sol";
import {PropAMMWords as W} from "src/propamm/libraries/PropAMMWords.sol";
import {PropAMMDeskCellCode} from "src/propamm/PropAMMDeskCellCode.sol";
import {PropAMMDeskCode} from "src/propamm/PropAMMDeskCode.sol";
import {CREATE3} from "solady/utils/CREATE3.sol";
/// @notice What the front's three parts share, one copy each: the hot implementation, the landing part and the admin
/// module inherit it, and each runs in the front's own context (reached through the proxy), so `address(this)`
/// is the front's. The error words, the side's bucket, the pool's cheap-lane view, the guards, a desk's cell, a
/// storage desk's standing word and a PRINT listing's source.
abstract contract PropAMMShared is IPropAMMFrontTypes {
using W for uint256;
/// @dev Error words: a selector (0-31), an argument (32-39), bit 40 when the error takes one, and bit 49 when it
/// refuses the block's state (a quote answers 0 for it where the fill reverts with it); every other refusal
/// is the caller's own, which the quote and the fill revert with alike.
uint256 internal constant HAS_ARG = 1 << 40;
uint256 internal constant STATE = 1 << 49;
/// @dev A desk's contract is the CREATE2 child of the front at salt `CELL_RANGE | desk` under the build's frozen
/// desk code (`_deskCodeHash`).
uint256 internal constant CELL_RANGE = 1 << 252;
/// @dev A source's check gas (`_srcCall`: a kept print, or a carried one at the ticket door): room past the Pyth
/// Pro check's parse and its verifier's signer view for a slower vendor's check, or two vendors' in one source.
uint256 internal constant SOURCE_GAS = 250_000;
// ---------------------------------------------------------------- error words
/// @dev The word of an error with no argument.
function _e(bytes4 sel) internal pure returns (uint256) {
return uint256(uint32(sel));
}
/// @dev The word of an error with an argument, which must fit 8 bits: `_fail` reverts with its low byte.
function _eArg(bytes4 sel, uint256 arg) internal pure returns (uint256) {
return uint256(uint32(sel)) | (arg << 32) | HAS_ARG;
}
/// @dev A source's check (`IPriceCheck.check`) by STATICCALL under `SOURCE_GAS`, the check's flags above bit 160
/// of `src` (`_srcOf`). With an empty update (the kept print) `ok` is false on any failure; with a carried
/// print the source's revert data passes on, its first 256 bytes alone, as the caller's own refusal, and `ok`
/// is false for a call the cap starved or an answer of another size. `c` is the answer's pair confidence,
/// `rec` its fifth word where `want` asks for one. The hot part's kept print and the landing part's pull both
/// read here.
function _srcCall(uint256 src, bytes calldata u, uint256 k, uint256 want)
internal
view
returns (bool ok, uint256 ta, uint256 tb, uint256 px, uint256 c, uint256 rec)
{
assembly ("memory-safe") {
let m := mload(0x40)
let n := u.length
mstore(m, shl(224, 0x1c8026cb)) // check(bytes,uint256,uint256)
mstore(add(m, 0x04), 0x60)
mstore(add(m, 0x24), and(shr(160, src), 0xffffffffffffffffffffff))
mstore(add(m, 0x44), k)
mstore(add(m, 0x64), n)
calldatacopy(add(m, 0x84), u.offset, n)
mstore(add(add(m, 0x84), n), 0) // the pad
let size := add(0x84, and(add(n, 31), not(31)))
let target := and(src, 0xffffffffffffffffffffffffffffffffffffffff)
// Yul evaluates arguments right to left: the call first, in its own statement
let success := staticcall(SOURCE_GAS, target, m, size, m, want)
if and(iszero(success), and(gt(returndatasize(), 0), gt(n, 0))) {
// a hostile source's revert data, held to 256 bytes: the copy's memory stays bounded
let r := returndatasize()
if gt(r, 0x100) { r := 0x100 }
returndatacopy(m, 0, r)
revert(m, r)
}
ok := and(success, eq(returndatasize(), want))
ta := mload(m)
tb := mload(add(m, 0x20))
px := mload(add(m, 0x40))
c := mload(add(m, 0x60))
rec := mload(add(m, 0x80))
}
}
/// @dev Source `s`'s two-word answer to `sel` with the arguments `x` and `y`, `n` bytes of call data (0x24 for one
/// argument, 0x44 for two), by STATICCALL under `SOURCE_GAS`: `ok` only where it answered exactly two words.
/// The hot part's `assetFacts` asks a source so, and the landing part's ticket door the hot part itself,
/// through the proxy (`sessionOf`).
function _srcWords(address s, bytes4 sel, uint256 x, uint256 y, uint256 n)
internal
view
returns (bool ok, uint256 w0, uint256 w1)
{
assembly ("memory-safe") {
let m := mload(0x40)
mstore(m, sel)
mstore(add(m, 0x04), x)
mstore(add(m, 0x24), y)
// Yul evaluates arguments right to left: the call first, in its own statement
let success := staticcall(SOURCE_GAS, s, m, n, m, 0x40)
ok := and(success, eq(returndatasize(), 0x40))
w0 := mload(m)
w1 := mload(add(m, 0x20))
}
}
/// @dev The parts' one starvation rule, run where a call the plan makes fails or answers anything but a pass, `g`
/// the gas left just before it: under g / 8 left after it is the caller's limit (`GasShort`), never the
/// block's state. A call whose gas ran out keeps nothing, and each caller above it bubbles the failure with
/// the 1/64 it kept, so one starved up to eight calls down still leaves under g / 8; a call given its whole
/// cap C leaves at least g - C, at or over g / 8 for g at or over 8/7 of C; and one that fails or refuses at
/// once leaves nearly g. A callee's own `GasShort` is a failure like any other, held to this rule.
function _starved(uint256 g) internal view {
if (gasleft() < g / 8) revert GasShort();
}
/// @dev Reverts with the error word's typed error (its argument where bit 40 is set).
function _fail(uint256 e) internal pure {
assembly ("memory-safe") {
mstore(0, shl(224, and(e, 0xffffffff)))
if iszero(and(shr(40, e), 1)) { revert(0, 4) }
mstore(4, and(shr(32, e), 0xff))
revert(0, 36)
}
}
// ---------------------------------------------------------------- the side's bucket and the pool's view
/// @dev The side's bucket room in quote base units: min(burst, level + rate x elapsed), rate the lower of the
/// maker's cap and the operator's ceiling, burst the lower of rate x the maker's seconds and the operator's
/// ceiling.
function _bucket(uint256 ctl, uint256 s1, uint256 b, bool bid, uint256 nowMs) internal pure returns (uint256 room) {
// the rate is held under 2^96 before any product; times 255 s or 2^48 ms: no overflow
unchecked {
uint256 rate = ctl.cRate(bid);
uint256 ceil = s1.rateCeil(bid);
if (ceil < rate) rate = ceil;
if (rate > W.M96) rate = W.M96;
uint256 burst = rate * ctl.cBurstSec();
ceil = s1.burstCeil(bid);
if (ceil < burst) burst = ceil;
if (burst > W.M96) burst = W.M96;
uint256 last = b.bTime();
room = b.bLevel();
if (nowMs > last) room += rate * (nowMs - last) / 1000;
if (room > burst) room = burst;
}
}
/// @dev The pool's acceptance predicate on one side of one pair as it reports it (`IFLAMMLane.laneStateOf`); a
/// pool that does not answer offers nothing, held to the starvation rule (`_starved`).
function _laneStateOf(address pool, uint256 sidePair) internal view returns (uint256 room, uint256 maxIn) {
bytes4 sel = IFLAMMLane.laneStateOf.selector;
bool ok;
uint256 g;
assembly ("memory-safe") {
let m := mload(0x40)
mstore(m, sel)
mstore(add(m, 4), sidePair)
g := gas()
// Yul evaluates arguments right to left: the call first, in its own statement
let success := staticcall(gas(), pool, m, 36, m, 0x40)
ok := and(success, gt(returndatasize(), 0x3f))
if ok {
room := mload(m)
maxIn := mload(add(m, 0x20))
}
}
if (!ok) _starved(g);
}
// ---------------------------------------------------------------- guards
/// @dev The front's storage; `Locked` while a fill holds the front's lock.
function _unlocked() internal view returns (PropAMMStore.Layout storage $) {
if (PropAMMStore.locked()) revert Locked();
return PropAMMStore.state();
}
/// @dev `_unlocked`, for an entry of the protocol owner's: `Unauthorized` for any other caller.
function _safe() internal view returns (PropAMMStore.Layout storage $) {
$ = _unlocked();
if (msg.sender != $.safe) revert Unauthorized();
}
/// @dev The pool's operator, its core's owner, read live.
function _curator(address pool) internal view returns (address) {
return IEverlongCore(IFLAMM(pool).core()).owner();
}
/// @dev Whether the caller may stop the pool's listings: its operator or its guardian, read live from its core
/// (`owner()`; `guardian()`, zero for none).
function _stopRole(address pool) internal view returns (bool) {
IEverlongCore c = IEverlongCore(IFLAMM(pool).core());
return msg.sender == c.owner() || msg.sender == c.guardian();
}
/// @dev Pair `pairId`'s word (`PropAMMWords`); `UnsupportedPair` for a pair never added.
function _pairWord(PropAMMStore.Layout storage $, uint256 pairId) internal view returns (uint256 pw) {
pw = $.pairs[pairId].cfg;
if (pw == 0) revert UnsupportedPair();
}
// ---------------------------------------------------------------- a desk's cell
/// @dev The build's kind, a constant of its leaf and the answer of each part's `LANE_KIND`: 0 Ethereum's builder
/// build (each listing priced by its desk contract, which lands by its own push, a relay entry or a builder
/// lane of the Flashbots registry), 1 the storage build (desk cells landed by their own push, stored price
/// lanes as sources), 2 BNB Chain's builder build (desk contracts, landed by their own push or a relay entry
/// or, where the front's registry is a relayer adapter, a builder lane through it); builder builds read pull
/// checks.
function _laneKind() internal pure virtual returns (uint256);
/// @dev The creation code hash of the build's desks, a constant of the build from the front's birth: a builder
/// build's desk contract (`PropAMMDeskCode`, one a maker with a word a pair slot), the storage build's desk
/// cell (`PropAMMDeskCellCode`).
function _deskCodeHash() internal pure returns (bytes32) {
return _laneKind() == 1 ? PropAMMDeskCellCode.HASH : PropAMMDeskCode.HASH;
}
/// @dev Desk `desk`'s cell as `front` derives it: the CREATE2 child of `front` at `CELL_RANGE | desk` under the
/// build's frozen desk code (`_deskCodeHash`).
function _cellOf(address front, uint256 desk) internal pure returns (address a) {
bytes32 h = _deskCodeHash();
uint256 salt = CELL_RANGE | desk;
assembly ("memory-safe") {
let m := mload(0x40)
mstore(m, or(shl(160, 0xff), front))
mstore(add(m, 0x20), salt)
mstore(add(m, 0x40), h)
a := and(keccak256(add(m, 11), 85), 0xffffffffffffffffffffffffffffffffffffffff)
}
}
/// @dev The desk's record word 0, its cold key the caller.
function _coldKey(PropAMMStore.Desk storage r) internal view returns (uint256 w0) {
w0 = r.w0;
if (w0 == 0 || msg.sender != address(uint160(w0))) revert Unauthorized();
}
/// @dev One op to a desk's cell, `op | word`; a refusal, or no code at the cell (a call to an empty account
/// succeeds), reverts `BadConfig`.
function _cellOp(address cell, uint256 op, uint256 word) internal {
bool ok;
assembly ("memory-safe") {
let m := mload(0x40)
mstore8(m, op)
mstore(add(m, 1), word)
let code := extcodesize(cell)
ok := and(call(gas(), cell, 0, m, 33, 0, 0), iszero(iszero(code)))
}
if (!ok) revert BadConfig();
}
/// @dev A desk's cell from this front.
function _deskCell(uint256 desk) internal view returns (address) {
return _cellOf(address(this), desk);
}
/// @dev Whether pair slot `wordIndex` of desk `desk` is held by a listing other than `listing`: the listing the
/// slot map names for it (`PropAMMStore.Layout.slotListing`, written at each binding) is another one, is live,
/// and still names this desk and this word index in its own words. The map is read against the listing it
/// names, so an unbinding, a rebinding elsewhere or a retirement frees the slot with no write here, and a
/// listing's own rebinding passes. Both binding paths ask it: the landing part's `bindListing` and
/// `bindAtBirth`, and the admin module's `acceptListing`.
function _slotTaken(PropAMMStore.Layout storage $, uint256 listing, uint256 desk, uint256 wordIndex)
internal
view
returns (bool)
{
uint256 held = $.slotListing[(desk << 8) | wordIndex];
if (held == 0 || held == listing) return false;
PropAMMStore.Pool storage o = $.pools[held];
uint256 o0 = o.p0;
return o0 & W.F_LIVE != 0 && o.p1.desk() == desk && o0.sWordIndex() == wordIndex;
}
/// @dev The cell call's argument for a listing's word `i`: the front's registry (`g0`'s low 160 bits: on BNB Chain
/// none unless one was given at `initialize` or installed through the registry's path, none on a storage
/// build), the word index and the word wanted. The named door's reads, `deskView` and `doorView` pass it; the
/// ticket door passes the same registry and word index on every listing, and asks for the word on every
/// fence kind but PRINT, SESSION included (`_cellArgs`): a desk contract's ticket is its pair slot's, so the
/// index is read whether or not the word is wanted.
function _cellArg(uint256 g0, uint256 i) internal pure returns (uint256) {
return uint160(g0) | (i << 160) | (uint256(1) << 168);
}
/// @dev The cell's view op (4) for word argument `a` (`_cellArg`, or the same with the word not wanted for a
/// PRINT listing): its ticket and word where it answered `size` bytes (`ok`), else zeros. On a PRINT listing
/// (`size` 0x20) only the ticket is the cell's: `w` is not, and nothing reads it there.
function _cellLook(address cell, uint256 a, uint256 size) internal view returns (bool ok, uint256 t, uint256 w) {
assembly ("memory-safe") {
let m := mload(0x40)
mstore8(m, 4)
mstore(add(m, 1), a)
// Yul evaluates arguments right to left: the call first, in its own statement
ok := staticcall(gas(), cell, m, 33, m, 0x40)
ok := and(ok, eq(returndatasize(), size))
if ok {
t := mload(m)
w := mload(add(m, 0x20))
}
}
}
/// @dev The cell's consume op (1), a call, answered as `_cellLook`.
function _cellTake(address cell, uint256 a, uint256 size) internal returns (bool ok, uint256 t, uint256 w) {
assembly ("memory-safe") {
let m := mload(0x40)
mstore8(m, 1)
mstore(add(m, 1), a)
// Yul evaluates arguments right to left: the call first, in its own statement
ok := call(gas(), cell, 0, m, 33, m, 0x40)
ok := and(ok, eq(returndatasize(), size))
if ok {
t := mload(m)
w := mload(add(m, 0x20))
}
}
}
/// @dev A builder build's fill's `Swapped` (`IPropAMM`), which the listing's desk contract logs for the front: op
/// 0x07 to the cell of the listing's desk (its P1 `s1`), 193 bytes, the op then `sender`, `tokenIn`,
/// `tokenOut`, `amountIn`, `amountOut` and `recipient` a word each, called once a fill after the pool has
/// paid (the pool's own swap called un-nested: before `fillPair` returns, {PropAMMFront.fillPair}). A
/// refusal reverts the fill: `GasShort` where the call's gas starved it (`_starved`), else `SwapLogFailed`.
/// No code check: every fill has had a size-checked answer of this cell already (`_cellLook`, `_cellTake`),
/// and a listing bound to no desk fills nowhere (`Unbound`). It reads no registry, so a builder build with
/// none logs too. A storage build has no desk contract and makes no call: its doors log.
function _deskLog(
uint256 s1,
address sender,
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOut,
address recipient
) internal {
if (_laneKind() == 1) return;
address cell = _deskCell(s1.desk());
uint256 g = gasleft();
bool ok;
assembly ("memory-safe") {
let m := mload(0x40)
mstore8(m, 7)
mstore(add(m, 1), sender)
mstore(add(m, 33), tokenIn)
mstore(add(m, 65), tokenOut)
mstore(add(m, 97), amountIn)
mstore(add(m, 129), amountOut)
mstore(add(m, 161), recipient)
ok := call(gas(), cell, 0, m, 193, 0, 0)
}
if (!ok) {
_starved(g);
revert SwapLogFailed();
}
}
/// @dev Whether the transaction's tip (`tx.gasprice` above `block.basefee`, zero below) is above the listing's
/// taker tip cap (P1 bits 240-255; 0 off).
function _tipCapped(uint256 s1) internal view returns (bool) {
uint256 c = s1.tipCap();
return c != 0 && tx.gasprice > block.basefee && tx.gasprice - block.basefee > W.tipWei(c);
}
// ---------------------------------------------------------------- a storage desk's standing word
/// @dev Whether a storage build's standing word `w` may fill under its desk's ticket `t` (the listing's P1 `s1`;
/// the pair word is unread), and the life it fills for, in seconds: written by the ticket's own push (the
/// cell stamps a storage word with its push's version, bits 210-224), while the listing's taker tip cap is on;
/// its life then its own. The named door reads it (`_deskFresh`), then holding the word to its maker time,
/// the life and the clock's lead; the ticket door's `_stands` tests the version alone, as its `_ticketStands`
/// holds the other two.
function _storageLife(uint256 t, uint256 w, uint256 s1, uint256) internal pure returns (bool, uint256) {
if (w.wVersion() != t.tVersion() || s1.tipCap() == 0) return (false, 0);
return (true, w.ttl());
}
// ---------------------------------------------------------------- a PRINT listing's band
/// @dev The confidence band of a PRINT listing's fill, the same on both doors, from the side's fence `B` and the
/// listing's ceiling `R` (ppm, each already held to an asset-module pair's module ceiling, so B <= R), the
/// listing's confidence multiplier `k` (tenths, at most 30) and the print's pair confidence `c` (ppm, as its
/// source answers it, uncapped): the fence f = min(max(B, c x k / 10), R) and the refusal distance
/// r = min(2f, R). `wide` where the print refuses (`WidePull`): c > r, or c >= R, which also catches a
/// saturated or broken confidence. A calm print (c x k / 10 <= B), and every print at k = 0, keeps f = B and
/// r = 2B held to R.
function _band(uint256 B, uint256 R, uint256 k, uint256 c) internal pure returns (uint256 f, uint256 r, bool wide) {
if (c >= R) return (0, 0, true);
// c < R <= 655,350 and k < 256 here: no product overflows
unchecked {
f = c * k / 10;
if (f < B) f = B;
if (f > R) f = R;
r = 2 * f;
if (r > R) r = R;
wide = c > r;
}
}
// ---------------------------------------------------------------- a PRINT listing's source
/// @dev The listing's live source as both doors call its check, from its price word `l` (its record's word 2,
/// `PropAMMWords`, P2; `builder` the build's family, `g0` the global word as the caller read it): `src` its
/// address (0-159) and the check's flags above it, the asset flag aside, which each caller adds; `win` its
/// window, 500 ms steps; `role` 1 its primary, 2 its backup (`P2_ON_BACKUP`). A builder build's pull check is
/// the CREATE3 child of the front at salt `bytes32(id)`, flag bit 0 the listing's lease while it runs (to the
/// second at bits 200-231) and is not cut (`g0` bit 161); a storage build's stored price lane takes its base
/// and quote slots as flag bits 8-23 and 24-39, and flag bit 2 where the source is guarded (`E_GUARD`), to
/// which each caller adds bit 3 for a buying taker. All zero where the listing reads none: unpriced or dark.
function _srcOf(uint256 l, bool builder, uint256 g0)
internal
view
returns (uint256 src, uint256 win, uint256 role)
{
win = W.win(l);
role = 1 + ((l >> 244) & 1);
if (builder) {
uint256 id = l & W.M32;
if (id == 0) return (0, 0, 0);
src = uint160(CREATE3.predictDeterministicAddress(bytes32(id), address(this)));
if (block.timestamp <= (l >> 200) & W.M32 && (g0 >> 161) & 1 == 0) src |= uint256(1) << 160;
} else {
if (uint160(l) == 0) return (0, 0, 0);
src = uint160(l) | (((l >> 160) & W.M32) << 168) | (((l >> 247) & 1) << 162);
}
}
/// @dev The floor a PRINT listing bound to sources `w10` (its record's word 10: the primary at 0-31, the backup at
/// 32-63) fills at least, in the quote's base units: the greater of the two sources' floors (`eFloor`,
/// millionths of a whole quote token), on every pair (pair word `pw`), rounded up for a quote of fewer than 6
/// decimals. Id 0's entry is never written, so an absent backup adds nothing.
function _srcFloor(PropAMMStore.Layout storage $, uint256 pw, uint256 w10) internal view returns (uint256) {
uint256 a = W.eFloor($.sources[w10 & W.M32]);
uint256 b = W.eFloor($.sources[(w10 >> 32) & W.M32]);
uint256 f = a > b ? a : b;
uint256 d = pw.decQuote();
// a floor is under 2^32 and the quote's decimals at most 18: no overflow
return d >= 6 ? f * W.pow10(d - 6) : (f + W.pow10(6 - d) - 1) / W.pow10(6 - d);
}
/// @dev Whether the sources of a listing's word 10 `w10` (its primary, and its backup where it has one) are each
/// guarded (`E_GUARD`), as a tied listing's must be.
function _guarded(PropAMMStore.Layout storage $, uint256 w10) internal view returns (bool) {
uint256 b = (w10 >> 32) & W.M32;
return $.sources[w10 & W.M32] & W.E_GUARD != 0 && (b == 0 || $.sources[b] & W.E_GUARD != 0);
}
// ---------------------------------------------------------------- a pool's pair hook
/// @dev Whether `pool`'s pair hook prices its tokens `ix & 15` and `ix >> 4` (`pairHook()`: the hook, and from bit
/// 160 one bit per unordered pair of tokens, the pair `lo < hi` at `160 + hi * (hi - 1) / 2 + lo`,
/// `FLAMMStore.pairHookBit`); a revert or a short answer is no pair hook (as before the pool's genesis). It
/// takes no lock, so the pool asks the front's `pricesPair` with its own lock held.
function _hookPair(address pool, uint256 ix) internal view returns (bool on) {
(uint256 lo, uint256 hi) = ix & 15 < ix >> 4 ? (ix & 15, ix >> 4) : (ix >> 4, ix & 15);
uint256 bit = 160 + hi * (hi - 1) / 2 + lo;
assembly ("memory-safe") {
mstore(0, shl(224, 0x4c95758f)) // pairHook()
// Yul evaluates arguments right to left: the call first, in its own statement
let ok := staticcall(gas(), pool, 0, 4, 0, 0x40)
if and(ok, gt(returndatasize(), 0x3f)) {
on := and(iszero(iszero(shl(96, mload(0)))), and(shr(bit, mload(0x20)), 1))
}
}
}
/// @dev `pairIdOf`'s key: keccak256(abi.encodePacked(token0, token1)), the tokens sorted, in the scratch space.
function _pairKey(address a, address b) internal pure returns (bytes32 k) {
(address t0, address t1) = a < b ? (a, b) : (b, a);
assembly ("memory-safe") {
mstore(0x00, shl(96, t0))
mstore(0x14, shl(96, t1))
k := keccak256(0x00, 0x28)
}
}
}
src/propamm/interfaces/IAssetModule.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {PropAMMClock} from "src/propamm/libraries/PropAMMClock.sol";
/// @notice An asset module: the rules of one asset type (tokenized stocks first) that every listing of an asset-module
/// pair (a pair whose base token the front's module claims, `familyOf`) must pass. A listing is the front's
/// pool id (`poolId`). A listing of any other pair never asks.
/// @dev The rules of the seam:
/// - Install: the module is a contract installed by address: the front binds its chain's one module to a pair at
/// the pair's creation where the module claims the base token, fixed with the family it claims, and the protocol
/// owner may schedule a listing's own module in its place, a replacement that waits the pool's
/// `governanceDelaySec` and that only the pool's operator applies (once due, within the execution window, while
/// the module's code hash is the scheduled one: the hash binds code, not a proxy's implementation); the protocol
/// owner, the operator or the pool's guardian cancels it. An owner who is also the listing's operator cannot
/// apply, as each of its calls reschedules. A module the listing used before, the pair's included, is never put
/// back (`isBound`), so no replaced module's word rules the listing again.
/// - The call: the front asks the one address a listing resolves to on every quote and fill of the listing,
/// before the price fence and the walk, by STATICCALL under a gas cap, and takes only an answer of exactly three
/// words: a revert, running out of gas or an answer of any other size stalls the listing, which then refuses
/// while the pool's exits stay open.
/// - Fence kinds: that ask holds on every fence kind and every door, but only a PRINT listing reads a print. A
/// WORD or NONE listing asks with `price36` and `record` zero, and only the module's verdict counts: no
/// multiplier scales anything and no price fence is held to its ceiling. So what a module draws from the record
/// refuses nothing there, by design: the stock module's session, quiet window and jump tag are dropped, while
/// its halt, latch, multiplier and issuer pause, which need no record, stay. A module that will not answer
/// without a record keeps such a listing dark. A SESSION listing asks as a PRINT listing while its print is
/// fresh; in its closed phase, on a kept print stale long enough, it asks with that print as `price36` and
/// `record` zero: the same stops are dropped, the multiplier scales the stale print its band sits around, and
/// that band's fence and ceiling are held to the module's `fenceCeilPpm`, as a print's are.
/// - The price: on a PRINT listing the front prices the fill at P x `multiplier` / 1e18 (P the pull price; rounded
/// down, and a scaled price of 0 or at the price bound, 2^200, stalls the listing as a dark source would),
/// before the price fence, the maker's refusal check and the walk, so every later site reads the scaled price,
/// and holds each side's price fence and the listing's ceiling to at most `fenceCeilPpm` in the settings word
/// the rest of the plan reads, so the confidence band never passes it. A module may refuse or tighten; it never
/// widens a price fence past the listing's own setting or lifts a bound.
/// - The install's checks: the address has code, names this front (`FRONT`), reads the pair's base token as the
/// family claimed or listed (`isFamily`) and holds no word for the listing it takes (`isBound`). A new asset
/// family needs a new module and an install, never a front upgrade.
/// - The stock rules alone are compiled into the front too (`PropAMMStockRules`): a module that keeps its
/// listing's word in the listing's record (`IAssetFront.setAssetWord`) has the front run those rules on that
/// word inside the named-door fill, with the front's own readers for families 3 and 4, in place of the call. The
/// stock module keeps it there only where its readers hash to the front's (`STOCK_READERS`, which an upgrade
/// keeps). A listing on its pair's module whose record holds no word, and a listing with its own module, are
/// asked by call. The ticket door always asks by call.
/// - `record` is source-neutral: the front composes it from the listing's price source (a stored price lane's
/// record as it stands, or a builder build's source's kept record: its check's fifth word on a fill, its
/// `assetRecord` in `assetFacts`, `IAssetSource`), so a module reads no vendor's format: [0-63] the base's
/// price, 8 decimals (zero: none) | [64-111] that price's time, ms | [112-114] the market session: 0 unknown,
/// 1 closed, 2 pre-market, 3 regular, 4 post-market, 5 overnight, 6 every session but the regular one of a feed
/// priced around the clock (its source reports 3 or 6) | [115] quality: the print met its source's
/// quorum | [116-163] the session's start, ms (when the source first reported it) | [164-179] the jump tag,
/// which counts the base's jumps | [180-243] the tag's source: the low 64 bits of the address of the source that
/// counts the tags, a stored price lane's feed key folded into their high 32 by XOR (another source, or another
/// feed of one price lane, counts its own from 0, so a tag compares only with one from the same source and feed)
/// | [244-255] zero.
interface IAssetModule {
/// @notice Whether the listing may fill now, at what multiplier and under what price fence ceiling, as above.
/// @param listing The listing, the front's `poolId`.
/// @param token The pair's base token.
/// @param price36 The pull price, before any multiplier; zero on a WORD or NONE listing.
/// @param record The base's record (above); zero on a WORD or NONE listing.
/// @param makerMs The maker's time on the words the fill reads: the pool word's; on a guarded quote the standing
/// word's on a WORD listing, else the quote's signed time, which on NONE the maker key alone picks.
/// @param nowMs The front's clock, ms.
/// @return verdict Zero allows; any other value refuses (the front reports it, capped at 255).
/// @return multiplier The base's units one token carries, WAD (1e18 is one); nonzero and under 2^96.
/// @return fenceCeilPpm The price fence either side may use at most, ppm.
function check(uint256 listing, address token, uint256 price36, uint256 record, uint256 makerMs, uint256 nowMs)
external
view
returns (uint256 verdict, uint256 multiplier, uint256 fenceCeilPpm);
/// @notice The front this module rules: an install on any other front is refused.
function FRONT() external view returns (IAssetFront);
/// @notice Whether `token` reads as a base of family `family`, which the front asks at the install: a family is
/// fixed with the install, so a token listed under another family's reads is refused there.
function isFamily(address token, uint256 family) external view returns (bool);
/// @notice The family the module claims `token` as a base of, zero where it claims none, which the front asks at a
/// pair's creation (`addPair`, open to anyone): a nonzero answer makes the pair this module's, under that
/// family (then checked by `isFamily`), and refuses the token as a quote; a zero answer makes it a plain
/// pair. It must never claim a plain token, and must answer one word: the front refuses any other answer,
/// and a zero it took starved of gas (`GasShort`).
function familyOf(address token) external view returns (uint256);
/// @notice Whether the module has ever held a word for `listing` (its operator bound it here; a word is never
/// cleared), which the front asks at the install of a listing's own module and at a pair's birth (listing
/// 0): a module answering true, or answering anything but one word, is refused there.
function isBound(uint256 listing) external view returns (bool);
}
/// @notice What an asset module reads of its front: a listing's identity and its base's record, answered only to the
/// module the listing resolves to (price sources serve their records to registered readers alone), the
/// front's maker lead and its clock.
interface IAssetFront {
/// @notice A listing's identity and its base's record, to the module the listing resolves to alone: any other
/// caller reverts `Unauthorized`, and a listing with no live source `SourceDark`.
/// @return pool The listing's pool.
/// @return token The pair's base token.
/// @return family The base token's family, fixed at the install.
/// @return record The base's record (`IAssetModule`), from the listing's live source; zero on a pair with no price
/// source.
/// @return prices The base's price before each of its last four jumps, as the source keeps them (`jumpsOf`): 8
/// decimals, 64 bits each, the jump tagged t at bit 64 x (t mod 4), zero where there is none; each the
/// last price before that jump's gap. The module orders them (`PropAMMAsset.preJumps`). Zero on a pair with
/// no price source.
function assetFacts(uint256 listing)
external
view
returns (address pool, address token, uint256 family, uint256 record, uint256 prices);
/// @notice The front's maker-time windows and clock, in one answer (`PropAMMFront.clock`). A module reads three
/// of them. `maxLeadMs`: a maker time the front takes lies at most this many ms past its clock (a guarded
/// quote's signed time lies under that), so an accept darkens every word stamped before a time past it.
/// `pullLeadMs`: a pull print the front takes is stamped at most this many ms past its clock, and ages as
/// one at the clock, so a module measures a record's freshness the same way. The clock's mode, block and
/// milliseconds: the clock the front's fills measure ages on.
function clock() external view returns (PropAMMClock.Timing memory);
/// @notice The module's copy of a listing's word into the listing's record (word 12), on its every write of the
/// word, from the module the listing resolves to alone (any other caller reverts `Unauthorized`): the front
/// runs the stock rules (`PropAMMStockRules`) on it inside the named-door fill on a listing of its pair's
/// module.
function setAssetWord(uint256 listing, uint256 word) external;
}
src/propamm/interfaces/IPriceSource.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The front's one seam to a price vendor. A source is a contract anyone registers under a global id
/// (`registerSource`; its entry written once, never edited); each listing binds one and, if it likes, a
/// backup, its operator's choice (`setSource`).
/// @dev How the front reads a source, and what a wrong price can do:
/// - The front reads no vendor format: a builder build's fill asks a pull check (for its kept print, or for the
/// print a ticket fill carries), which the front itself deploys from its registrant's code at its registration
/// (CREATE3 at salt `bytes32(id)`) so a fill derives its address; a storage build's fill asks a stored price
/// lane (`IPriceLane`) for its kept print by the same check.
/// - On a listing of a crypto pair a wrong price only tightens or stops that listing: the price fence clamps
/// toward the pool, so it either refuses the listing's fills or leaves its maker's signed levels unclamped, the
/// risk a pair with no price source already carries.
/// - The protocol's spread fee is measured against the same price and bounded by the fill from above only, so the
/// more prints a source admits for one fill (a wider window, or either of two vendors), the more a poster, or a
/// taker carrying a print, may pick the one that cuts it.
interface IPriceCheck {
/// @notice Verifies a vendor's signed update for a pair's two legs, writing nothing: a fill calls it by STATICCALL
/// under a gas cap, and a ticket fill passes a carried print's refusal's revert data on.
/// @dev The source's word (its feeds, quorums, channel) is its own, fixed at deployment. The front takes exactly
/// five words under `flags` bit 1 and exactly four without it, and reads any other answer as a failure. The
/// source's window (its entry's, copied into the listing's price word) bounds the earlier leg's age at the
/// fill.
/// @param update The vendor's update: empty asks a source that keeps prints for its kept print.
/// @param flags The front's flags:
/// - bit 0: the listing's lease, under which a source that caches a trust may honour it. A Pyth source
/// caches none and ignores the bit.
/// - bit 1: set on every check of an asset-module pair (pair word bit 15) and on no other: asks a fifth
/// word, the base's record (`IAssetModule`: bits 0-179 as there, the rest the source's own). Such a pair's
/// source on a builder build serves its module that record too (`IAssetSource`).
/// - bits 2-3, on every storage build's print, both doors: bit 2 asks the price that is worst for the
/// fill's taker among the prints the price lane holds, bit 3 names that taker's side (set where it buys
/// the base). A source that holds prints answers `conf` with bit 255 set, which the front takes off
/// before the band reads it; one that ignores the flags answers its kept print with the bit clear, which
/// a PRINT or SESSION listing takes as its print and a tied listing's named fill as no price.
/// - bits 4-7: reserved, zero.
/// - bits 8-39, on a storage build: the source entry's base slot (8-23) and quote slot (24-39), by which a
/// stored price lane serving many pairs reads the pair's two records.
/// - bits 40-87: reserved, zero.
/// @param k The pair's cross scale.
/// @return ta The first leg's feed time, microseconds.
/// @return tb The second leg's feed time, microseconds.
/// @return px P = pa x 10^k / pb, rounded down, both legs at one exponent.
/// @return conf The pair's confidence, ppm of P, both legs' summed, in whatever measure the source keeps (a
/// vendor's confidence, a quote's spread, two vendors' disagreement); 0 where it has none. Uncapped: the
/// front reads it against the listing's ceiling. Under bit 1 a fifth word follows, the base's record.
function check(bytes calldata update, uint256 flags, uint256 k)
external
view
returns (uint256 ta, uint256 tb, uint256 px, uint256 conf);
/// @notice Whether a trust the source caches still holds by its vendor's own verifier: a listing's daily lease
/// renews only on true (`refreshLease`, anyone). A source with no cache, each Pyth source among them,
/// answers true and ignores the lease. A cached trust revoked after a renewal stays honoured until the
/// lease lapses, at most a day, unless the listing's operator or its pool's guardian, the protocol
/// guardian or the protocol owner cuts the lease.
function cacheValid() external view returns (bool);
}
/// @notice An asset-module pair's source on a builder build (`IPriceCheck` under flags bit 1) also serves the pair's
/// module the base's record outside a fill (`IAssetFront.assetFacts`: the module's bind, latch, re-arms and
/// large syncs), which the front probes when a listing of such a pair binds it, so a source that answers a
/// fill but not the module is never bound. A storage build's stored price lane serves the same through
/// `IPriceLane` (`records`, `jumpsOf`).
interface IAssetSource {
/// @notice The base's record as the source keeps it (the one its check answers as the fifth word) and the price
/// before each of its last four jumps (8 decimals, 64 bits each, the jump tagged t at bit 64 x (t mod 4)),
/// to the front alone; `lease` the listing's lease flag. Exactly two words.
function assetRecord(bool lease) external view returns (uint256 record, uint256 prices);
}
/// @notice A storage build's stored price lane: a vendor's posted prints, one record per feed, each at a fixed slot.
/// A fill reads a pair's two by the price lane's `check` under a gas cap, and an asset module's facts read
/// the base's (`records`, `jumpsOf`).
/// @dev A record is the source-neutral record an asset module reads, but for its bits 180-243, where that record names
/// the tag's source and the front writes the price lane's own address with the feed's key folded in
/// (`PropAMMAsset.record`): [0-63] price, exponent -8 (zero: none) | [64-111] its time, ms | [112-114] the market
/// session (0 unknown, 1 closed, 2 pre-market, 3 regular, 4 post-market, 5 overnight, 6 a 24/7 feed's outside its
/// regular one) | [115] the print met its source's quorum, which every record a fill reads must have | [116-163]
/// the session's start, ms | [164-179] the jump tag | [180-211] the price lane's own, which every reader masks (a
/// Pyth price lane's: [180-187] the feed's quorum, [188-203] its jump threshold, bp, [204] a 24/7 feed, [205-207]
/// that feed's own session, [208-211] reserved) | [212-243] the price lane's own per-slot identity, opaque to the
/// front and never changed | [244-255] the price lane's own (a Pyth price lane's: the print's leg confidence, 1
/// bp units). A price lane's written obligation: a slot's feed never changes. The front checks no feed key, so a
/// fill and the front's `assetFacts` read a listing's records by slot alone.
interface IPriceLane {
/// @notice `IPriceCheck.check` as a storage build calls it, on every fill.
/// @dev The front reads an answer of any other size than five words under `flags` bit 1 and four without it as a
/// failure. A price lane need not answer `IPriceCheck.cacheValid`, which no storage build calls.
/// @param update Empty, asking the price lane's kept print: any other update is refused, a refusal a ticket fill
/// carrying a print passes on.
/// @param flags Bit 0 the front's lease, which a price lane may ignore; bit 1 set exactly on an asset-module pair;
/// bit 2 set on every fill's print, with its taker's side at bit 3 (`IPriceCheck.check`); bits 8-23 the base
/// feed's slot and 24-39 the quote's (the listing's source entry, 1-65,535 each, never equal); bits 40-87
/// zero.
/// @param k The pair's cross scale.
/// @return ta The first leg's feed time, as `IPriceCheck.check` answers it.
/// @return tb The second leg's feed time, as `IPriceCheck.check` answers it.
/// @return px The price, as `IPriceCheck.check` answers it.
/// @return conf The pair's confidence, ppm, as `IPriceCheck.check` answers it. Under bit 1 a fifth word follows,
/// the base's record as stored.
function check(bytes calldata update, uint256 flags, uint256 k)
external
view
returns (uint256 ta, uint256 tb, uint256 px, uint256 conf);
/// @notice Records `i` and `j`, served to the price lane's registered readers alone.
function records(uint256 i, uint256 j) external view returns (uint256 ri, uint256 rj);
/// @notice Whether `who` may read records.
function isReader(address who) external view returns (bool);
/// @notice The front whose owner appends feeds to the price lane's list. The front does not check it at
/// `registerSource`: a third-party price lane names its own.
function GOVERNOR() external view returns (address);
/// @notice The fronts' clock the price lane holds stored times to (`PropAMMClock`): its mode, and the block and
/// milliseconds mode 2 counts from. A front registers only a price lane on its own clock whose lead
/// (`MAX_LEAD_MS`) is at most its own pull lead, so no stored time is further ahead of the clock a fill
/// reads in the same block than the fill admits.
function clockConfig() external view returns (uint256 mode, uint256 block0, uint256 ms0);
/// @notice How far a stored feed time may run ahead of the fronts' clock in the post's block, ms.
function MAX_LEAD_MS() external view returns (uint256);
/// @notice Feed `i`'s jump threshold, bp (nonzero exactly on an equity feed, which only a stock's base leg may
/// read), and its last four pre-jump prices (exponent -8, 64 bits each); served to the registered readers.
function jumpsOf(uint256 i) external view returns (uint256 jumpBps, uint256 prices);
}
src/propamm/interfaces/IPropAMMFront.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The front's structs, events and errors, shared by its three parts (the hot implementation, the landing
/// part and the admin module) and by integrators. The proxy's whole surface is the three parts' ABIs together.
/// @dev The front's terms, each with the contract that owns it:
/// - operator: a pool's curator under its front name, the owner of the pool's core (`PropAMMShared._curator`).
/// - D: a pool's `governanceDelaySec`, which its operator's loosenings wait (`PropAMMDue.poolDelay`).
/// - listing: what a `poolId` names: one pool's place on one pair (`PropAMMStore.Pool`), its first on the pool's
/// hook pair (`reservePool`), each further one on another pair of its tokens (`reserveListing` in the launch,
/// `addListing` after it). One pool may own several listings, so `swapSender`'s `poolId` and `PoolFill.poolId`
/// name the listing, not the pool. A pair holds any number of listings, one kind of pair on every build: each
/// fill names its listing.
/// - desk: an operator's price service for its own listings, with four keys: cold, stop, word and pusher
/// (`PropAMMLandingDesk.openDesk`).
/// - cell: the contract that holds what a desk lands (`PropAMMDeskCell`), a CREATE2 child of the front
/// (`PropAMMShared._cellOf`).
/// - ticket: a cell's slot 0: the landing's stamp and version, the desk's epoch, stopped bit and floor, the desk
/// books' indexes and latch counts, and the registry mark a copy of a builder lane sets (`PropAMMWords`).
/// - standing word: the pool word a cell keeps for a listing, at the listing's word index (`PropAMMWords`).
/// - price source: a contract anyone registers under a global id (`registerSource`), its entry written once and
/// never edited; a listing's operator binds one and a backup (`setSource`), and the listing's record keeps the
/// live one's hot copy, the one word a fill reads for it (`PropAMMWords`, P2).
/// - print: a vendor's signed price of a pair's two legs, read through a price source (`IPriceCheck`).
/// - carried print: a print a ticket fill on a PRINT listing brings in its calldata (`fillQuote`'s `pull`),
/// checked by the listing's source where it takes one (`PythProSource`; a stored price lane takes none) and kept
/// by nothing.
/// - kept print: a print already on chain, which a fill reads with an empty update (`PrintLaneSource`, or a
/// stored price lane).
/// - lease: a listing's one-day leave for its price source to honour a trust it caches, in bits 200-231 of its
/// record's word 2; renewed by anyone while the source vouches for its cache, cut by a new binding, a
/// darkening or `cutLease`; builder builds only (`PropAMMAdminColdBuilder.refreshLease`). No Pyth source
/// caches a trust, so the lease changes no fill on one.
/// - carry: a standing word's fill in the block after its landing, a named fill of a PRINT or WORD listing, which
/// the listing and the word must each allow, never on an asset-module pair; builder builds only
/// (`PropAMMWords.carry`, `PropAMMRegistryFront._deskFresh`). It has nothing to do with a carried print.
/// - builder build: the family on Ethereum (`LANE_KIND` 0) and BNB Chain (2), where builders sell a block's
/// placement and a desk lands for one block (`PropAMMRegistryFront`, `PropAMMLandingRegistry`).
/// - storage build: the family on Base, Arbitrum One, Robinhood and HyperEVM (`LANE_KIND` 1), where what lands
/// stands until a later push replaces it (`PropAMMBaseFront`, `PropAMMLandingStorage`).
/// - builder lane: a builder build's landing through the front's registry: Ethereum's priority-update registry, or
/// on BNB Chain a `PropAMMDeskLaneAdapter` given at `initialize` or installed by the protocol owner through the
/// registry's path. Each desk points its cell at that registry (`PropAMMAdminColdBuilder.setDeskLanding`).
/// - named door: the entries that name a listing and fill its standing word: `quoteFrom`, `quoteFillableFrom`,
/// `swapSender` and `swapExactInPaid` (`PropAMMFront`). A named fill is a fill of a standing word, there or on
/// the credit path (`PoolFill`'s scope 0).
/// - ticket door: the entries that quote and fill a guarded quote: `quoteFirm` and `fillQuote`
/// (`PropAMMLandingDesk`).
/// - router door and listing door: periphery contracts that serve `IPropAMM` over the named door, the first for
/// routers that name no listing, the second for one listing (`PropAMMRouterDoor`, `PropAMMListingDoor`).
/// - board: a side's maker-signed ladder, its depth words, plus the front's memory of the fills against it, the
/// side's board word (`PropAMMWords.board`).
/// - guarded quote: the `FirmQuote` struct, a quote signed for the ticket door that names the ticket state it was
/// priced at, so a move of that state voids or reprices it (`PropAMMLandingDesk.fillQuote`).
/// - cheap lane: a fill the front prices and the pool settles from tracked custody
/// (`IFLAMMLane.fillFromFront`).
/// - credit path: the pool's own swap through the swap hook, the front as the swap hook of its pair
/// (`quotePair`, `fillPair`).
/// - credit route: a front fill sent to that swap, by the listing's credit mode (`PropAMMFront._creditSwap`).
/// - price lane: a vendor's prints posted and stored on chain, which a storage build's fills read (`IPriceLane`).
/// - price fence: a listing's bound on a fill's price, by its fence kind and the side's `fenceBidPpm` or
/// `fenceAskPpm`. PRINT: the band (`PropAMMShared._band`) widens the side's fence B with the print's pair
/// confidence c to f = min(max(B, c x confMul / 10), ceilPpm), and the pool buys at most f over the print and
/// sells at most f under it; a named fill clamps each level there (`PropAMMFront._fence`) and refuses where
/// the maker's first unconsumed level lies past min(2f, ceilPpm), a ticket fill past f is refused (`Refused`),
/// and a print with c past that refusal distance or at the ceiling refuses either fill (`WidePull`).
/// WORD: a ticket fill never crosses the desk's standing signed word: the pool pays at most its ask and sells at
/// no less than its bid (`CrossesWord`); a named fill's levels fill as signed. NONE: no bound. SESSION: PRINT's
/// while the listing's print is fresh; once its kept print is stale long enough (`SessionSettings`), WORD's
/// and, around that stale print, PRINT's band again with the closed phase's own fence. It is unrelated
/// to core's venue fence, which takes a venue or a token's custody out of the pool book (`IFLAMMFence`).
interface IPropAMMFrontTypes {
/// @notice A listing's own settings, chosen by its operator. Packed into word 1 of the listing's record
/// (`PropAMMStore.Pool`) in declaration order, bits 0-191 and 232-239 (192-223 the listing's desk; 224
/// reserved; 225-226 the credit mode; 227-231 the desk binding's scopes: ANY, the fence kind, the carry
/// life; 232-239 the confidence multiplier; 240-255 the taker tip cap, `setTipCap`). The fences and the
/// ceiling are ppm, each a multiple of 10 and at most 655,350, stored / 10 (one unit 0.1 bp); the fences at
/// most the ceiling. Every 24-bit amount is an 18-bit
/// mantissa (low bits) and a 6-bit exponent of 10, in the listing pair's quote-token base units. The
/// minimum fill is never zero; on a listing bound to a desk as PRINT it is at least its sources' floor: the
/// greater of its primary's and its backup's, each the millionths of a whole quote token its registrant
/// set (`PropAMMShared._srcFloor`).
struct Settings {
uint32 fenceBidPpm; // the price fence B, ppm, where the pool buys base
uint32 fenceAskPpm; // the price fence B, ppm, where the pool sells base
uint32 ceilPpm; // the listing's ceiling R, ppm, both sides: the most its band's fence and refusal reach
uint16 maxAgeMs; // pull-price maximum age, at most the chain's ceiling (inert on a listing that reads no price)
uint24 rateCeilBid; // operator ceiling on the bid bucket's rate, per second
uint24 rateCeilAsk; // the same on the ask bucket
uint24 burstCeilBid; // operator ceiling on the bid bucket's burst
uint24 burstCeilAsk; // the same on the ask bucket
uint24 minFill; // minimum fill notional, on the quote leg
uint8 splitDepth; // last rung quoteFillableFrom may report, at most 10; 0 = all
uint8 confMul; // k, tenths, at most 30: the band's fence follows k x the print's confidence (0: fixed at B)
}
/// @notice A SESSION listing's closed-phase settings (`setSession`), its operator's, packed into word 13 of the
/// listing's record (`PropAMMWords`, session word). A listing bound SESSION fills as a PRINT listing while
/// its print is fresh; once its kept print's older leg is at least `closedAfterMs` old on the age clock it
/// is in its closed phase, and between the two it refuses (`StalePull`). In the closed phase a fill needs
/// the desk's signed word, as a WORD listing's, and besides: each level inside the band around the stale
/// print P (scaled by an asset-module pair's multiplier), the pool buying at most f(t) over P and selling
/// at most f(t) under it, f(t) = min(offCeilPpm, offBasePpm + offWidenPpm x sqrt(t)) for a print t seconds
/// old, on an asset-module pair held to the module's fence ceiling too (a stock's class ceiling outside
/// the regular session); the filled side's skew of the word at least `offMinSkewPpm`; and the side's
/// bucket holding at most `offMaxNotional`, so no fill's quote leg passes it. All zero, as on every listing
/// before its first `setSession`, is no closed phase: the listing fills as PRINT alone.
struct SessionSettings {
uint32 closedAfterMs; // whole seconds, 60,000 to 21,600,000; 0: no closed phase
uint32 offBasePpm; // the band at the print's time, ppm, a multiple of 10, at most `offCeilPpm`
uint32 offCeilPpm; // the band's ceiling, ppm, a multiple of 10, at most 655,350
uint16 offMinSkewPpm; // the least skew of the filled side's word, ppm
uint16 offWidenPpm; // the band's widening, ppm per square root of a second
uint24 offMaxNotional; // the bucket's ceiling in the closed phase: a 24-bit amount, quote-token base units
}
/// @notice What the launcher registers with a listing at its reservation, every field the operator's choice (no
/// default stands in for one): the maker key, the settings, the credit mode and the price source and its
/// backup, or none.
struct PoolInit {
uint8 makerKeyType; // epoch 1: 0 EOA, the only type taken (1 P-256 is reserved)
address makerKey; // an EOA
Settings settings;
uint8 creditMode; // `PropAMMWords.CREDIT_*`, 0-3
uint32 source; // the listing's price source, a registered id (`registerSource`); 0 none, so it is unpriced
uint32 backup; // the source it reads once its source is darkened (`darkenSource`), 0 none
}
/// @notice A pool's cheap lane past its hook pair at birth (`IFLAMMLane.initLaneTokens`, in the launch's own
/// transaction, where nothing waits D): the ordered pairs past the hook pair the cheap lane may settle (the
/// pool's `hookPairs` layout, within the pairs the pool's listings price), each later token's outflow caps
/// (`tokenCaps[t - 2]`: rate in bits 0-23, burst in 24-47), the Router's drawn-token limit and whether the
/// pool's credit law is custody-blind for life (`custodyBlind`: outside strict mode the cheap lane pays
/// custody with no debt-free proof and the pool draws only through a refill, while its listings sit on any
/// pair and bind as PRINT or WORD, never NONE, `bindListing`), sent by `confirmPool` right after the cheap
/// lane's birth on every pool (all zero, no caps entry, for a pool of two tokens).
struct LaneTokens {
uint256 lanePairs; // the ordered pairs past the hook pair, in the pool's `hookPairs` layout
uint48[] tokenCaps; // each later token's outflow caps, `tokenCaps[t - 2]`
uint8 maxDrawnTokens; // the Router's drawn-token limit
bool custodyBlind; // the pool's credit law, for life
}
/// @notice A listing as a router door reads it (`doorView`), cold: its pair, its place in its pool, its status,
/// key epoch, desk binding and settings, its sides' last fills, its desk's cell as a fill reads it and its
/// depth words. The one-side form (`doorView(listing, bid)`, a door's screen) leaves the tokens, the last
/// fills and the other side's depth zero.
struct DoorView {
uint256 pairWord; // the pair word (`PropAMMWords`): bit 8 set where the base is token0, the units
address token0;
address token1;
address pool;
uint8 baseIndex; // the listing's tokens in its pool: base 0 and quote 1 on the pool's hook pair
uint8 quoteIndex;
uint8 flags; // P0 bits 192-199: [0] live | [1] reserved, set by nothing (`PropAMMWords.F_PAUSED`) | [2] frozen
// | [3] maker paused | [7] own asset module
uint32 keyEpoch; // P0 bits 200-231: its words carry the low 8 bits (a depth word at bits 4-11)
uint32 desk; // 0 unbound
uint8 wordIndex; // the listing's standing word in its desk's cell
// ANY firm quotes bind on no build of this deployment, so bit 0 reads 0
uint8 scopes; // [0] ANY | [1-2] the fence kind (0 PRINT, 1 WORD, 2 NONE, 3 SESSION) | [3-4] the carry life
// the listing's own fences, ppm: an asset-module pair's fill holds each to its module's cap
uint32 fenceBidPpm;
uint32 fenceAskPpm;
uint16 tipCap; // as stored: a 12-bit mantissa and a 4-bit exponent of 10, wei per gas; 0 off
uint8 confMul; // the listing's confidence multiplier, tenths (P1 bits 232-239)
uint8 creditMode; // `PropAMMWords.CREDIT_*`
uint48 bidFillMs; // each side's last fill on the front's clock, ms: its board word's time, the go-live
uint48 askFillMs; // before the side's first fill
uint256 ticket; // the desk's cell: its ticket and the listing's standing word as a fill reads them; zeros
uint256 word; // unbound, or where the cell does not answer
uint256[4] depth; // the depth words: bid 0, bid 1, ask 0, ask 1, a word 1 only where its word 0 marks it
}
// ---------------------------------------------------------------- fills
/// @notice The front's one log of a fill, once per pool leg, on every fill path.
/// @dev The pair's id and the side name the tokens: the pair's base (its `PairAdded` word, bit 8) is the input on
/// a bid (`feeAge` bit 255 set) and the output on an ask. The fields past the amounts:
/// - `pullPrice36`: the price the protocol's spread fee is measured against: the print the fill was fenced to;
/// on a WORD or NONE listing, which reads no price, and in a SESSION listing's closed phase, whose print is
/// stale, its desk word's mid, or zero where there is none, so the fill measures no edge.
/// - `feeAge`: [0-191] the spread fee | [192-239] the quote's age | [240-254] 0 | [255] the side, 1 a bid
/// (the taker sells the pair's base), 0 an ask (`PropAMMWords.feeAge`). The fee is under 2^150 and the age
/// under 2^48 on every path, so neither reaches the field above it.
/// - the spread fee (`feeAge` bits 0-191): the protocol's part in base units of the listing pair's quote token
/// (token 1 on the hook pair) on every path, a credit-path fee the pool accrues in the base token valued at
/// that price, rounded down. On the cheap lane the part is what the pool booked: its spread fee, or the
/// pair's notional floor where that is more, so a fill that measures no edge still logs the floor. On the
/// credit path it is the front's part only, its edge against that price: the pool's own `Swap` event
/// carries the whole part it books, the floor included.
/// - the quote's age (`feeAge` bits 192-239): the maker's quote age at the fill, ms on the front's age clock:
/// the word's age on a named fill, now less the quote's signed time on a ticket fill.
/// - `recipient`: the account paid: the caller's recipient on the cheap lane (`swapSender`, `swapExactInPaid`,
/// `fillQuote`), the pool itself on the credit path (`fillPair`), whose own `Swap` log names the account its
/// swap paid, a credit-routed `swapSender`'s or `fillQuote`'s recipient among them.
/// - `boardTag`: names every signed input of the fill, as the next three bullets lay out.
/// - `boardTag` on every fill: [48-63] the listing's key epoch, low 16 bits | [64-78] the landed version |
/// [79] 0 | [228-243] the print's age at the fill, ms, after the clamp (a fresh print's only, else 0) |
/// [244] 1 | [245-246] the scope, 0 named, 1 TICKET, 2 ANY | [247-248] the listing's fence kind (0 PRINT,
/// 1 WORD, 2 NONE, 3 SESSION) | [249] the ticket's
/// registry mark | [250] carried: on a named fill the word was carried (landed the block before), on a
/// ticket fill the taker carried a print (so a PRINT ticket fill with bit 250 clear read the kept print),
/// always 0 on a WORD or NONE ticket fill | [251-252] the role of the source whose kept print the fill read,
/// 1 the listing's primary, 2 its backup, by which an indexer ties a print's post to the fills it serves (a
/// builder ties them by the state a fill reads), mapping the role to an id through the listing's word 10
/// and its `SettingsSet` (kind 34) and `SourceDarkened` logs: 0 on a WORD or NONE fill and on a ticket fill
/// that carried its print; in a SESSION listing's closed phase the role of the source whose stale print
/// anchored the band | [253] the fill was a SESSION listing's closed phase: priced by the desk's signed word
/// inside the band around its stale kept print, the age at 228-243 reading 0 | [254] 0 | [255] 0.
/// - `boardTag` on a named fill: [0-47] the pool word's maker time | [80-127] the side's depth nonce |
/// [128-175] the controls' nonce | [176-215] the side's fill memory the fill started from, board units
/// (after a new depth nonce or a refill, zero) | [216-226] the side's fill sequence before the fill | [227]
/// the pool word's refill applied. Within an epoch a maker time, a depth nonce and a controls nonce each
/// name one signed word, whose contents the post's calldata or the maker's own archive carry.
/// - `boardTag` on a ticket fill: [0-47] signed at, ms | [80-87] the replay index | [88-103] the reprice, in
/// 1e-5 of the output | [104-151] the landed latch counts | [152-183] the desk | [184-227] 0.
event PoolFill(
uint32 indexed pairId,
uint24 indexed poolId,
uint256 amountIn,
uint256 amountOut,
uint256 pullPrice36,
uint256 feeAge,
uint256 boardTag,
address recipient
);
// ---------------------------------------------------------------- maker posts
/// @notice A side's depth words posted (`postDepth`): `nonceMs` their nonce, ms.
event DepthPosted(uint24 indexed poolId, bool bid, uint64 nonceMs);
/// @notice A listing's controls word posted (`postControls`): `nonceMs` the stored word's nonce, ms, which a late
/// post that moves only the self-pause logs again. It carries the nonce alone, and the stored word can
/// differ from the posted one (a pause carried or added, the pause state's nonce at bits 208-255): read the
/// stored word for what stands.
event ControlsPosted(uint24 indexed poolId, uint64 nonceMs);
// ---------------------------------------------------------------- dark states
/// @notice A listing's status flags (P0 bits 192-199, as `DoorView.flags`) after a pause, freeze or clear, and who
/// set them.
event PoolStatus(uint24 indexed poolId, uint8 flags, address by);
/// @notice Every fill paused: by the protocol guardian (`pauseAll`), or by a new registry's install
/// (`executeRegistry`, `by` the front itself).
event AllPaused(address by);
/// @notice The protocol owner lifted the pause on every fill (`unpauseAll`).
event AllUnpaused();
// ---------------------------------------------------------------- keys
/// @notice A listing's maker key set under key epoch `epoch`: at its reservation, by `setMakerKey`, or at a binding
/// to a desk (`bindListing`).
event MakerKeySet(uint24 indexed poolId, uint32 epoch, uint8 keyType, address key);
// ---------------------------------------------------------------- pairs, pools and settings
/// @notice A pair added (`addPair`): `cfg` is its pair word (`PropAMMWords`).
event PairAdded(uint32 indexed pairId, address indexed token0, address indexed token1, uint256 cfg);
/// @notice A plain pair retired (`retirePair`): its tokens' pair is none until `addPair` builds it anew under a new
/// id; the retired pair's record stays, and its listings fill no more.
event PairRetired(uint32 indexed pairId);
/// @notice An asset-module pair's module: bound at `addPair` (`listing` 0) or removed for good (`module` zero), or
/// a listing's own one applied (`setAssetModule`), never one the listing used before. Pair 0, which never
/// exists, logs the protocol's own module, the one later pairs read (`setProtocolAssetModule`).
event AssetModuleSet(uint32 indexed pairId, uint24 indexed listing, address module);
/// @notice `token` listed as a quote asset of rank `rank`, 0 delisted (`setQuoteAsset`; at `initialize` the build's
/// `QUOTE0` and `QUOTE1`): read only by the pairs added after it.
event QuoteAssetSet(address indexed token, uint256 rank);
/// @notice A listing's birth: reserved for `pool` on the pair (`reservePool`, `reserveListing`), or a further
/// listing applied (`addListing`). It is not live before `PoolRegistered`.
event PoolReserved(uint32 indexed pairId, uint24 indexed poolId, address pool);
/// @notice A listing gone live on its pair, its board words written: every path to a live listing logs it.
event PoolRegistered(uint32 indexed pairId, uint24 indexed poolId, address pool);
/// @notice A live listing retired (`retirePool`) by `by`, its operator or the protocol owner.
event PoolRetired(uint24 indexed poolId, address by);
/// @notice The protocol owner delisted a further listing (`retirePool`): its pool takes no listing on the pair
/// until the protocol owner relists it (`relistListing`). Logged beside `PoolRetired` where the protocol
/// owner retires a live listing, and alone where it marks a listing its operator retired first.
event ListingDelisted(uint24 indexed poolId, address by);
/// @notice The protocol owner relisted a further listing it had delisted (`relistListing`): its pool may take a
/// listing on the pair again.
event ListingRelisted(uint24 indexed poolId, address by);
/// @notice A retirement's resync of the pool (`IFLAMMLane.syncListings`) failed; the retirement stands, and anyone
/// may resync the pool.
event ListingResyncFailed(uint24 indexed poolId, address pool);
/// @notice A listing's change of `kind` applied: 0 its settings word, 11 its credit mode, 34 its price source and
/// backup, 35 its taker tip cap, 36 its own asset module (`AssetModuleSet` too). A listing's reservation
/// logs its birth values the same way: kinds 0, 11 and 34. A further listing (kind 33, kept on the pool's
/// first listing) logs its apply as that birth (`PoolReserved`), and a weakening of a desk binding (kind
/// 38) and an accepted offer of a listing to a desk (kind 39) as `ListingBound`, none under its own kind.
event SettingsSet(uint24 indexed poolId, uint8 kind, uint256 value);
/// @notice A listing's loosening scheduled, replacing any the kind had: `value`, of `kind` (`SettingsSet`), which
/// the identical call applies from `dueAt`, unix seconds. `changeId` hashes the listing and the kind. Kind
/// 38's value is the weakened binding in the clear: [0-31] the desk | [32-39] the scopes | [40-47] the word
/// index | [48-207] the maker key as named, or zero for the key of the day. Kind 33's is a hash: the
/// launcher's `ListingDeskScheduled` names its desk.
event ChangeScheduled(bytes32 indexed changeId, uint24 indexed poolId, uint8 kind, uint256 value, uint64 dueAt);
/// @notice A scheduled change dropped: cancelled (`cancel`), or by an at-once change of its kind.
event ChangeCancelled(bytes32 indexed changeId, address by);
// ---------------------------------------------------------------- protocol configuration (the timelock's setters
// log through the timelock's own events)
/// @notice A scheduled registry installed (`executeRegistry`), every fill paused with it (`AllPaused`).
event RegistrySet(address registry);
/// @notice A registry scheduled (`scheduleRegistry`), due at `dueAt`, unix seconds.
event RegistryScheduled(address registry, uint64 dueAt);
/// @notice The scheduled registry dropped (`cancelRegistry`).
event RegistryCancelled(address by);
/// @notice A price source registered under global id `id` (`registerSource`) by `registrant`, anyone: its contract
/// (a builder build's pull check, the CREATE3 child of the front at salt `bytes32(id)`; a storage build's
/// stored price lane) and the `cfg` it passed (its slots, floor and window). Its entry is never edited.
event SourceRegistered(uint32 indexed id, address indexed source, address indexed registrant, uint256 cfg);
/// @notice A listing's live source darkened at once by `by`, its operator or its pool's guardian
/// (`darkenSource`): it reads its backup `live` from now on, or none (`live` 0: a PRINT fill finds no
/// source, `SourceDark`), and its lease is cut either way. `setSource` binds again. Logged again when the
/// pool's guardian holds a listing its operator darkened (`P2_HELD`), `live` the backup it still reads, and
/// nothing else moves, its lease included.
event SourceDarkened(uint24 indexed listing, uint32 live, address by);
/// @notice The front's code frozen for good (`freezeCode`): no upgrade runs again.
event CodeFrozen();
/// @notice A listing's lease set to run until `until` (`refreshLease(uint24)`) or cut (`until` 0: `cutLease`), or
/// with `listing` 0 every lease cut (`until` 0) or that cut lifted (`until` 2^32 - 1). A darkening
/// (`SourceDarkened`) cuts a listing's lease too, logged by its own event.
event LeaseSet(uint24 indexed listing, uint32 until, address by);
/// @notice ERC-1967's event, which explorers and tooling read.
event Upgraded(address indexed implementation);
// ---------------------------------------------------------------- desks
/// @notice A desk opened for its cold key, the operator that will bind its own listings to it: its cell (the
/// desk's address at the builders), its first pusher, its word key (zero for none) and its stop key. The
/// cold key is the opening's caller, but for the front's first desk, whose opener may name another: only
/// there does the event not prove the cold key made the opening.
event DeskOpened(
uint32 indexed desk, address indexed coldKey, address cell, address pusher, address wordKey, address stopKey
);
/// @notice A desk stopped by its cold key or its stop key, under its new epoch: nothing it landed fills while it
/// stays stopped. On a storage build, where a word carries the epoch's low 8 bits and a revive may share
/// the stop's block, 256 stop and revive pairs inside a word's life wake what it landed (`deskStop`).
event DeskStopped(uint32 indexed desk, uint32 epoch, address by);
/// @notice A desk's pusher named by its cold key, under its current epoch (a revive after a stop, or a rotation).
event DeskRevived(uint32 indexed desk, uint32 epoch, address pusher);
/// @notice A revive in the block of the desk's last stop, which changes nothing: the desk stays stopped.
event DeskReviveSkipped(uint32 indexed desk, address pusher);
/// @notice A desk's key set by its cold key: `which` 1 its word key, 2 its stop key.
event DeskKeySet(uint32 indexed desk, uint8 which, address key);
/// @notice The registry a desk's cell lands through (zero: its own push only).
event DeskLanding(uint32 indexed desk, address registry);
/// @notice A listing bound to `desk` with `scopes` ([0] ANY | [1-2] fence kind | [3-4] carry life) and its word in
/// the desk's cell, or unbound (desk 0), under the listing's new key epoch: nothing signed under an earlier
/// one fills or posts again, and its ANY list starts empty. A binding at the listing's birth
/// (`bindAtBirth`) keeps its first key epoch and its maker key.
event ListingBound(uint24 indexed listing, uint32 indexed desk, uint8 scopes, uint8 wordIndex, uint32 keyEpoch);
/// @notice A listing offered by its pool's operator to `desk`, whose cold key may accept exactly these terms
/// (`acceptListing`) from `dueAt`, unix seconds, within the execution window: the offer's own second, or
/// for a weakening the pool's delay D on, logged `ChangeScheduled` (kind 39) too. `makerKey` is the next
/// key epoch's key as named, zero for the key of the day. It replaces the listing's earlier offer.
event ListingOffered(
uint24 indexed listing, uint32 indexed desk, uint8 scopes, uint8 wordIndex, address makerKey, uint64 dueAt
);
/// @notice A listing offered by its pool's operator to whichever desk `coldKey` opens or has opened
/// (`offerListingToKey`): `ListingOffered`'s offer, the desk named by that key's accept alone. It replaces
/// the listing's earlier offer, of either form.
event ListingOfferedToKey(
uint24 indexed listing, address indexed coldKey, uint8 scopes, uint8 wordIndex, address makerKey, uint64 dueAt
);
/// @notice A listing's offer accepted by the desk's cold key: the binding itself is logged `ListingBound`, under
/// its new key epoch (`MakerKeySet`).
event ListingOfferAccepted(uint24 indexed listing, uint32 indexed desk);
/// @notice A taker listed for the desk's ANY quotes on a listing with its heartbeat (1-256 blocks), or removed (0),
/// under the listing's key epoch.
event AnyTakerSet(uint24 indexed listing, uint32 indexed desk, address taker, uint16 heartbeat, uint32 keyEpoch);
// ---------------------------------------------------------------- errors: pair and listing
/// @notice The tokens make no pair this front added, or are not the pair a quote names.
error UnsupportedPair();
/// @notice Every fill is paused (`pauseAll`, or a new registry's install) until the protocol owner lifts it.
error FrontPaused();
/// @notice The listing is not in the state the call needs: for a fill, live on the fill's pair; for an admin call,
/// reserved, not confirmed yet or retired as the entry asks.
error NotLive();
/// @notice A retirement's resync of the pool ran short of the gas it was given (`retirePool`): the call reverts,
/// so its limit rises, where a resync the pool refuses is logged and the retirement stands.
error ResyncOutOfGas();
/// @dev 5 a guarded quote's kind, reserved bits, mode or desk book out of range; 9 reserved; a guarded quote's 10
/// side, 11 extra targets, 12 replay index, 14 and 15 fields an ANY quote leaves clear, 16 amounts
/// (`fillQuote`).
error BadShape(uint8 reason);
// ---------------------------------------------------------------- errors: pull price
/// @notice The print is too old: past its source's window or the listing's `maxAgeMs` on the age clock.
error StalePull();
/// @notice The print is stamped past the clock plus `PULL_LEAD_MS`, or past a source's own lead where it is posted.
error FuturePull();
/// @notice A carried print its source's parse refused (`PythProCheck.BadPull`, the same selector, passed on), whose
/// check the gas cap starved, or that answered another size, a price of 0 or one out of bounds; or any
/// print carried on a WORD or NONE ticket fill.
error BadPull();
/// @notice Kept declared, and raised by nothing here now: a print its vendor's verifier does not pass reverts with
/// that verifier's own error, passed on (`PythProCheck`).
error BadPullSigner();
/// @notice A PRINT listing's print is too wide for its band (`PropAMMShared._band`): its pair confidence past the
/// band's refusal distance, or at or past the listing's ceiling (held to an asset module's). A refusal of
/// the block's state, on either door.
error WidePull();
// ---------------------------------------------------------------- errors: words
/// @notice A word or a guarded quote carries another key epoch or desk epoch than the current one (a ticket fill
/// reads controls never posted this way too).
error WrongEpoch();
/// @notice The listing's controls were never posted (a named fill), or a posted word has another version or sets a
/// reserved field (`postControls`).
error BadVersion();
/// @notice The pool word is past its life on the age clock, or it or a guarded quote is stamped before the
/// controls' nonce.
error AnchorExpired();
/// @notice The side's depth is missing or past its expiry, or `postDepth` posts a word already past it.
error DepthExpired();
/// @notice `postDepth`: the word's full depth is over 2^40 - 1 board units.
error DepthTooLarge();
/// @notice A post's nonce lies past the clock plus `MAX_LEAD_MS`, or `postDepth` posts a malformed word or one
/// whose nonce is not above the stored one.
error NonMonotone();
/// @notice A word's maker time lies past the clock plus `MAX_LEAD_MS`, or a guarded quote's signed time at or past
/// it.
error FutureStamp();
/// @notice A post or a guarded quote is not signed by its key (a guarded quote's signature is 64 bytes), or
/// `pauseMaker` comes from an account other than the epoch's maker key.
error BadSignature();
// ---------------------------------------------------------------- errors: fill
/// @notice A swap past its deadline (unix seconds, inclusive), a guarded quote outside its target and extra
/// targets, or an ANY quote past its age limit.
error Expired();
/// @notice The listing is paused: by its maker key (`pauseMaker`), or by the self-pause in its controls.
error PoolPaused();
/// @notice The listing is frozen: it neither fills nor takes a post (`postDepth`, `postControls`).
error PoolFrozen();
/// @notice On side `bid`, the maker's first unconsumed level lies past the band's refusal distance around the
/// print, or a ticket fill's price past the band's fence.
error Refused(bool bid);
/// @notice Reserved: nothing raises it. A listing that reads no price and whose word gives no mid fills, measuring
/// no edge.
error NoReference();
/// @notice The listing's asset module refused the quote or fill: its nonzero verdict, or 255 for a revert, its gas
/// cap, an answer of any other size than three words, a multiplier of zero or at least 2^96, or no module
/// (its pair's removed). The block's state.
error AssetRefused(uint8 code);
/// @notice The front's lock is held: a fill is running, and this call re-enters it.
error Locked();
/// @notice The listing fills less than the whole input: its depth, its bucket or the pool's room falls short, the
/// pool's own swap on the credit route failed, used less or paid with no call back to the front, or a paid
/// entry met a listing with a credit mode.
error NotEnoughDepth();
/// @notice A builder build's fill could not log its `Swapped` at its listing's desk contract: the contract
/// refused the call. The fill reverts whole. A call left too little gas reverts `GasShort` instead.
error SwapLogFailed();
/// @notice The fill misses the listing's minimum fill (`Settings.minFill`).
error BelowMinimum();
/// @notice The output is under the caller's minimum.
error Slippage();
/// @notice The transaction's tip (`tx.gasprice` above `block.basefee`) is above the listing's taker tip cap
/// (`setTipCap`): the taker's own choice, so a quote run at its gas price reproduces it.
error TipCapped();
/// @notice The call's gas starved a call the front makes on the plan, which failed or refused with under 1/8 of the
/// gas it began with left: the pool's own preview or swap on the credit route (or a capped venue read
/// under it began short of its budget, `ReadStarved`), the pool's cheap-lane state, the asset module or a
/// PRINT listing's kept print, on either door. The caller's limit, never the block's
/// state, so a quote reverts with it rather than answer 0. Raise the limit. A starved read of the desk's
/// cell is not among these: it is `NoTicket`, and a quote answers 0.
error GasShort();
// ---------------------------------------------------------------- errors: desks
/// @notice The guarded quote was filled already: a race between takers where it names no taker (a state refusal),
/// its own taker's replay where it names one.
error QuoteUsed();
/// @notice The desk's cell gives no ticket for this fill: the cell's read failed or starved, the desk is stopped, a
/// TICKET quote finds none landed in this block (on a storage build, none standing), or an ANY quote finds
/// the desk silent past the taker's heartbeat.
error NoTicket();
/// @notice An ANY quote in a block where the desk's ticket landed: the desk's TICKET quotes govern there.
error TicketLanded();
/// @notice The quote's generation is under the desk floor or too far above it, its latch count moved, or (reprice
/// modes 1 and 2) the desk book's index moved past 2^14 ticks either way or past the quote's cap against
/// the quote; or the mode-2 reprice to the landed desk book cut the output to zero (a request of one unit)
/// or a bid's under the listing's minimum fill it met before. A refusal of the block's state, at its step:
/// ahead of the steps after it, the caller's own included (`BelowMinimum`, a carried print's `BadPull`).
error Voided();
/// @notice The listing is bound to no desk.
error Unbound();
/// @notice The listing's binding or the desk's ANY list does not open this door for this quote.
error ScopeRefused();
/// @notice The listing's price source gives no print: none live, or its kept print missing, refused or out of
/// bounds, or a stored price lane with no usable price. A carried print's refusal is the caller's own.
error SourceDark();
/// @notice The listing's standing word does not serve this fill: missing, of another kind or desk epoch, unsigned,
/// reference only (the named door), out of bounds, older than its carry allows, or on a storage build past
/// its standing life.
error NoWord();
/// @notice A ticket fill on a WORD listing crosses the desk's signed word standing now.
error CrossesWord();
// ---------------------------------------------------------------- errors: roles and changes
/// @notice The caller lacks the role the call needs: the owner (the timelock), the protocol owner, the launcher,
/// the pool's operator or guardian, the protocol guardian, a desk's cold or stop key, or the listing's
/// asset module (`assetFacts`); or a guarded quote's named taker is not the account filling it, or an ANY
/// quote names none.
error Unauthorized();
/// @notice A step not open yet: a scheduled registry before its due time, a desk on a front never initialized, or
/// a pair (`addPair`) while the protocol's asset module has no code yet. A listing's scheduled change
/// never raises it: a call before its due time schedules the change again.
error NotDue();
/// @notice A due registry change not executed within its execution window: schedule it again, or cancel it.
error Lapsed();
/// @notice A binding to a desk and word index that another live listing holds (`bindListing`, `bindAtBirth`,
/// `acceptListing`): one listing a pair slot, until that listing is unbound, rebound elsewhere or retired.
error PairSlotTaken();
/// @notice Settings that break a rule: a price fence or ceiling off the 10 ppm step or past 655,350 ppm, a price
/// fence past the ceiling, a confidence multiplier past 30, an age past the chain's ceiling, a zero rate or
/// burst ceiling, a split depth over 10, or a minimum fill zero, past 2^128 - 1 or, on a PRINT listing,
/// under its sources' floor (`setSource`, `setSettings`).
error OutsideCeiling();
/// @notice Nothing is scheduled for the call to cancel or execute.
error NotPending();
/// @notice An argument or a state the entry's rules refuse.
error BadConfig();
/// @notice `confirmPool`: the pool's core is not a `DelayedAuthority` (1), the authority's delay is under the
/// pool's D (2), a guardian change is already scheduled on it (3), or an owner change is (4); a lapsed one
/// reads as none.
error AuthorityRefused(uint8 reason);
/// @notice `upgradeToAndCall` outside the proxy, or `proxiableUUID` through it, which only the implementation
/// answers.
error NotProxy();
/// @notice A named implementation or launcher does not carry the named code hash or fails `initialize`'s launcher
/// rule (the launcher is fixed at `initialize`; only an upgrade changes it), or an upgrade's new code answers another slot, guardian or cell code hash (`upgradeToAndCall`).
error CodehashMismatch();
}
src/propamm/libraries/PropAMMClock.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The chain's millisecond clock for words, ages and buckets, shared by the hot implementation and the landing
/// part so both measure time one way.
/// @dev The modes:
/// - Mode 0: the seal time, `block.timestamp` x 1000 (Ethereum; Base before its millisecond blocks; Arbitrum One,
/// Robinhood and HyperEVM, whose blocks share whole seconds).
/// - Mode 1: the BaseTime predeploy's `timestampMs()`.
/// - Mode 2: milliseconds from the block number (`ms0` at block `block0`, 200 ms a block) where they agree with
/// the block's seconds, BaseTime otherwise.
/// - Mode 3: the millisecond timestamp precompile at 0x70 (BNB Chain's BEP-706, from its Jenner upgrade), which
/// ignores its input and answers the block header's milliseconds. Before the precompile exists the call answers
/// nothing and the clock reads the seal time, so a mode-3 build turns exact at that upgrade with no change of
/// its own. Until then its first read in a transaction pays a cold account access; a precompile is warm.
///
/// A millisecond reading that disagrees with `block.timestamp`'s second, or that cannot be read, falls back to the
/// seal time, the start of the block's second: once blocks run faster than one a second, that reads up to a second
/// early, so ages read young, the unsafe side, which the age ceilings must absorb, and a print stamped later in
/// the second waits for the next.
///
/// The clock's anchor (`block0`, `ms0`) is one block's own: a block off reads 200 ms early in four blocks of five,
/// so ages read young, the unsafe side. On Base it is the first millisecond block. Base after its millisecond
/// blocks therefore runs mode 2 on an exact anchor, which the Base build checks at construction
/// (`PropAMMBaseFront`): modes 1 and 2 only where BaseTime answers, their anchor on its reading, and mode 0 only
/// where it does not. Ethereum's build takes mode 0 alone (0x70 holds nothing there), BNB Chain's mode 0 or
/// mode 3.
library PropAMMClock {
/// @notice A build's maker-time windows and clock, as the hot implementation and the landing part answer them in
/// one call (`clock()`): seven words, in this order.
struct Timing {
uint256 maxLeadMs; // how far past the clock a maker time may lie, ms
uint256 maxTtlMs; // the cap on a pool word's life, ms
uint256 pullLeadMs; // how far after the clock a print's feed time may lie, ms
uint256 ageSlackMs; // what the age clock adds to a seal reading, ms
uint256 clockMode; // the clock's mode, below
uint256 clockBlock; // the block mode 2 counts from
uint256 clockMs; // that block's milliseconds
}
/// @dev The BaseTime predeploy, whose `timestampMs()` answers the block's milliseconds.
address internal constant BASE_TIME = 0x4200000000000000000000000000000000000030;
/// @dev BEP-706's millisecond timestamp precompile: any input, one word.
address internal constant MS_PRECOMPILE = 0x0000000000000000000000000000000000000070;
/// @dev Clock mode 0: the seal time.
uint256 internal constant SEAL = 0;
/// @dev Clock mode 1: BaseTime.
uint256 internal constant BASE_TIME_MS = 1;
/// @dev Clock mode 2: milliseconds from the block number.
uint256 internal constant BLOCKS = 2;
/// @dev Clock mode 3: the millisecond timestamp precompile.
uint256 internal constant PRECOMPILE_MS = 3;
/// @dev Milliseconds per block in mode 2.
uint256 internal constant BLOCK_MS = 200;
/// @dev The clock, ms ({read}).
function nowMs(uint256 mode, uint256 block0, uint256 ms0) internal view returns (uint256 ms) {
(ms,) = read(mode, block0, ms0);
}
/// @dev The clock, and whether it read the block's own milliseconds (`exact`) rather than the seal time, the start
/// of the block's second (mode 0, or another mode's fallback): where a build's blocks share whole seconds, a
/// seal reading lies up to a second before the block runs, which the build's age slack covers.
function read(uint256 mode, uint256 block0, uint256 ms0) internal view returns (uint256 ms, bool exact) {
if (mode != SEAL) {
if (mode == BLOCKS && block.number >= block0) {
ms = ms0 + (block.number - block0) * BLOCK_MS;
if (ms / 1000 == block.timestamp) return (ms, true);
}
address source = mode == PRECOMPILE_MS ? MS_PRECOMPILE : BASE_TIME;
bool ok;
assembly ("memory-safe") {
// timestampMs(), which the precompile ignores
mstore(0, shl(224, 0x5745a677))
// Yul evaluates arguments right to left: the call first, in its own statement
let success := staticcall(gas(), source, 0, 4, 0, 0x20)
ok := and(success, gt(returndatasize(), 31))
ms := mload(0)
}
if (ok && ms / 1000 == block.timestamp) return (ms, true);
}
return (block.timestamp * 1000, false);
}
}
src/propamm/libraries/PropAMMLaneLib.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 {PPM as ONE_PPM} from "src/libraries/Constants.sol";
/// @notice The cheap lane's shared arithmetic, compiled into the front and the pool alike so both sides of a fill
/// compute it one way: the protocol's spread fee (measured against the fill's fee price, rounded toward the
/// pool's LPs) and the 24-bit amounts of the cheap lane's config word and the front's settings and
/// controls.
library PropAMMLaneLib {
/// @dev Parts per million, the rate's unit.
uint256 internal constant PPM = ONE_PPM;
/// @notice The protocol's spread fee on a fill, in the pair's quote token's base units: `ratePpm` of the fill's
/// edge against `p36` (the fee price in the price36 scale: the print, or a WORD or NONE listing's word's
/// mid), floored at zero, rounded down. A bid (`poolAssetIn`: the pool buys the base, the pool asset on the
/// hook pair): edge = ⌊amountIn × P / 1e36⌋ − amountOut. An ask (the pool sells it): edge =
/// amountIn − ⌈amountOut × P / 1e36⌉. A fill with no fee price (`p36` zero) accrues nothing: P = 0 would
/// read the whole ask input as edge.
function spreadFee(bool poolAssetIn, uint256 amountIn, uint256 amountOut, uint256 p36, uint256 ratePpm)
internal
pure
returns (uint256)
{
if (p36 == 0 || ratePpm == 0) return 0;
uint256 edge;
if (poolAssetIn) {
uint256 value = Math.mulDiv(amountIn, p36, 1e36);
if (value <= amountOut) return 0;
edge = value - amountOut;
} else {
uint256 cost = Math.mulDiv(amountOut, p36, 1e36, Math.Rounding.Up);
if (amountIn <= cost) return 0;
edge = amountIn - cost;
}
return Math.mulDiv(edge, ratePpm, PPM);
}
/// @notice A 24-bit amount: an 18-bit mantissa (low bits) times 10 to a 6-bit exponent.
function amount24(uint256 v) internal pure returns (uint256 r) {
assembly ("memory-safe") {
r := mul(and(v, 0x3ffff), exp(10, and(shr(18, v), 0x3f)))
}
}
}
src/propamm/libraries/PropAMMRegistryRule.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {CHANGE_WINDOW_SEC} from "src/libraries/Constants.sol";
/// @notice The registry rule, one per `LANE_KIND`, and the registry path's clock: what the admin module's `initialize`
/// and the builder builds' cold admin part (`PropAMMAdminColdBuilder`: `scheduleRegistry`, `executeRegistry`)
/// both apply, from this one copy, so a registry the build refuses at birth is refused on its path too.
library PropAMMRegistryRule {
/// @dev The registry's own path (48 h).
uint256 internal constant REGISTRY_DELAY = 172_800;
/// @dev A due change applies for 7 days after it is due, then lapses: the registry's path and a listing's changes.
uint256 internal constant EXECUTION_WINDOW_SEC = CHANGE_WINDOW_SEC;
/// @dev A probe's gas: a registry's getters are reads, and an account whose code halts on a probe's selector (a
/// desk cell takes calldata byte 0 as its op, so 0x0260ee36 reads as its op 0x02) burns no more than this.
uint256 internal constant PROBE_GAS = 30_000;
/// @dev Whether a build of `LANE_KIND` `kind` takes `registry`. Kind 0, the Flashbots registry, whose writes keep
/// each builder lane to the block it lands in: its `MAX_UPDATE_AGE` (0x0260ee36) and `MAX_UPDATE_LEAD_TIME`
/// (0xb278d9b0) both answer zero, so no builder lane is written for another block's time and the front's own
/// windows decide every age.
/// Kind 2, BNB Chain's: a `PropAMMDeskLaneAdapter` over the relayer's registry v2, which answers the
/// builder-lane read a desk contract makes of a registry (`getState(uint256,uint32,uint32)`), where registry
/// v2 itself does not: an account answering `LANE_TYPEHASH()` (0x33f0746b) with the adapter's own type hash
/// (the adapter's constructor refuses a registry with no code). So registry v2 named directly is refused, as
/// a desk contract pointed at it would read nothing, and so is a desk contract. A guard against a
/// misconfiguration behind the registry's 48 h path, never a security boundary. Every probe runs under
/// `PROBE_GAS`. False for an account that does not answer so, and for any other kind.
function ok(address registry, uint256 kind) internal view returns (bool r) {
if (kind == 0) {
assembly ("memory-safe") {
mstore(0, shl(224, 0x0260ee36))
// Yul evaluates arguments right to left: each call first, in its own statement
let a := staticcall(PROBE_GAS, registry, 0, 4, 0, 0x20)
r := and(a, and(eq(returndatasize(), 0x20), iszero(mload(0))))
mstore(0, shl(224, 0xb278d9b0))
let b := staticcall(PROBE_GAS, registry, 0, 4, 0, 0x20)
r := and(r, and(b, and(eq(returndatasize(), 0x20), iszero(mload(0)))))
}
} else if (kind == 2) {
assembly ("memory-safe") {
mstore(0, shl(224, 0x33f0746b)) // LANE_TYPEHASH()
// Yul evaluates arguments right to left: the call first, in its own statement
let a := staticcall(PROBE_GAS, registry, 0, 4, 0, 0x20)
r := and(
a,
and(
eq(returndatasize(), 0x20),
eq(mload(0), 0xa4b52682f94dba563c0b23ca311afeb94a85c38c899a7e6c0fe0307231e1c300)
)
)
}
}
}
}
src/propamm/libraries/PropAMMStore.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The front's storage: one ERC-7201 namespace (`propamm.front`) that the hot implementation, the landing
/// part and the admin module share. Append only; the published formulas below are frozen with the layout,
/// because off-chain code (state overrides, Base validity predicates, monitoring, the lens through
/// `extSloads`) reads raw slots.
/// @dev The published formulas:
/// - the namespace base `BASE`, each field of `Layout` at `BASE + n` with `n` the slot its comment gives
/// (`relayKeys` takes slots 5 and 6; slot 7 is reserved);
/// - a listing's record at `keccak256(abi.encode(uint256(poolId), BASE + POOLS_INDEX))`, its word `w` at that slot
/// plus `w` (the `Pool` struct's field order);
/// - a pair record at `keccak256(abi.encode(uint256(pairId), BASE + PAIRS_INDEX))`: `cfg`, `token0`, `token1`,
/// `asset`;
/// - a price source's entry at `keccak256(abi.encode(uint256(id), BASE + SOURCES_INDEX))`, `id` its global id;
/// - a pair's `pairIdOf` word at `keccak256(abi.encode(keccak256(abi.encodePacked(token0, token1)), BASE + 16))`,
/// the pair id in its low 32 bits, an asset-module pair's `asset` word above them and the pair word's facts
/// from bit 196 (`PropAMMWords`, a pair's `pairIdOf` word), on every build. This layout suits a fresh front: a
/// word written by a build without the facts copy reads as an empty pair word, so an in-place upgrade from such
/// a build must back-fill every pair first;
/// - a listing's replay word at `keccak256(abi.encode(listing << 8 | target % 16, BASE + RING_INDEX))`, the target
/// a block, or a unix second on a storage build;
/// - a desk's record at `keccak256(abi.encode(uint256(desk), BASE + DESKS_INDEX))`, its word `w` at that slot plus
/// `w` (the `Desk` struct's field order);
/// - an ANY taker's word at `keccak256(abi.encode(taker, keccak256(abi.encode(keyEpoch << 56 | desk << 24 |
/// listing, BASE + ANY_INDEX))))`, the nested mapping's formula.
///
/// Every hot word carries a nonzero version from its first write, so no fill writes a zero slot. Reserved fields
/// stay declared, each marked below (relay keys, the Data Streams checker, the pool template, the operator list,
/// the feed registry, P-256 and session keys, the unused slots, record word 12), so every index above holds.
///
/// A pool id names a listing: one pool's place on one pair, with its own record, maker key and epoch, settings,
/// depth, controls, board state and word. A pool's first listing is its hook pair's (`poolIdOf`, low
/// 24 bits); a pool may hold further listings, one per further pair (`listingOf`, keyed by `listingKey`), whose P0
/// bits 248-255 carry the pair's token indices in the pool, and then `poolIdOf` bit 255 (`LISTINGS_FLAG`) is set:
/// readers mask a pool id to 24 bits.
library PropAMMStore {
/// @dev keccak256(abi.encode(uint256(keccak256("propamm.front")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant BASE = 0xca023b73b2185d1ba92ba3c09f7870c56c9bdadd91407b68ebb408947da60b00;
/// @dev `Layout.sources`' slot offset from `BASE`.
uint256 internal constant SOURCES_INDEX = 15;
/// @dev `Layout.pairs`' slot offset from `BASE`.
uint256 internal constant PAIRS_INDEX = 17;
/// @dev `Layout.pools`' slot offset from `BASE`.
uint256 internal constant POOLS_INDEX = 18;
/// @dev `Layout.replayRing`'s slot offset from `BASE`.
uint256 internal constant RING_INDEX = 42;
/// @dev `Layout.desks`' slot offset from `BASE`.
uint256 internal constant DESKS_INDEX = 43;
/// @dev `Layout.anyTakers`' slot offset from `BASE`.
uint256 internal constant ANY_INDEX = 45;
// Transient: the full-word reentrancy lock at `BASE`.
/// @dev Transient: the pool whose own swap a fill is calling (its credit route), bits 0-159, and the listing that
/// fill's plan named, from bit 160: the pool's one `fillPair` call back, which the front admits under that
/// fill's lock, fills that listing.
bytes32 internal constant CREDIT_SLOT = bytes32(uint256(BASE) + 1);
// Transient: that fill's plan, carried to the pool's call back in the six words after `CREDIT_SLOT`
// (`PropAMMFront._carry`), written with it and cleared as the call back reads them, so no other call finds them:
// [+1] the request's key, keccak256(tokenIn, tokenOut, amountIn); [+2] the planned output (bits 0-135), the word's
// age, ms (136-183), the pair (184-215), the side (216: a bid) and a guarded quote's mark (217: the plan is the
// ticket door's, `PropAMMFront._carryFirm`, filled as carried or not at all); [+3] the fee price; [+4] the side's
// board word after the fill; [+5] `PoolFill`'s board tag; [+6] the word's anchor. A guarded quote's plan carries
// no anchor (its fee price is reported): [+6] holds what an asset-module pair's module was told before the input's
// pull, for the ask after it, the print before the multiplier (bits 0-199) and the maker time (200-247), zero on
// any other pair; and on an asset-module pair one word more, [+7] the base's record.
/// @dev A pair record (`PAIRS_INDEX`).
struct Pair {
uint256 cfg; // the hot configuration word (PropAMMWords, pair word)
address token0; // the lower token address
address token1; // the higher token address
// an asset-module pair's module (0-159) and its base's family (160-163), bound at `addPair` for good where the
// protocol's asset module claims the base (`familyOf`); zero on any other pair, and on one whose module the
// protocol owner removed (`removeAssetModule`). On every build the pair's `pairIdOf` word carries a copy for
// the fills, which the same two calls write
uint256 asset;
}
/// @dev A listing's record (`POOLS_INDEX`); field order is the published word offset.
struct Pool {
uint256 p0; // 0: status (pool, pair id, flags, key epoch, word index, listing token indices)
// 1: Settings (0-191 and the confidence multiplier, 232-239), the desk binding, the credit mode, the tip cap
uint256 p1;
// 2: the live source's hot copy (`PropAMMWords`, P2), the one word a fill reads for its source: on a builder
// build its id and the listing's lease, on a storage build its price lane and two slots; its window, and
// whether the listing reads its backup or is dark. Zero while the listing has no source
uint256 price;
uint256 depthBid0; // 3
uint256 depthBid1; // 4
uint256 depthAsk0; // 5
uint256 depthAsk1; // 6
uint256 controls; // 7
uint256 boardBid; // 8
uint256 boardAsk; // 9
// 10: the bound source ids (`setSource`): the primary (0-31) and the backup (32-63, 0 none), the rest 0; zero
// while the listing has no source, exactly where word 2 is. Read on cold paths alone
uint256 sourceIds;
uint256 stockPolicy; // 11: the listing's own asset module (0-159), read while P0's `F_ASSET` is set
// 12: the copy of the listing's word its asset module keeps (`IAssetFront.setAssetWord`), written only by the
// module the listing resolves to; the named-door fill runs the stock rules on it for a listing of its pair's
// module (`PropAMMStockRules`); zero until that module first writes it
uint256 stockState;
// 13: a SESSION listing's closed-phase settings (`PropAMMWords`, session word; `setSession`), appended to the
// record: no earlier build wrote the slot, so it reads zero, no closed phase, on every listing made before it.
// Read only where a SESSION listing's kept print is stale
uint256 session;
}
/// @dev A desk's record (`DESKS_INDEX`), never transferred: word 0 [0-159] its cold key, the operator that opened
/// it | [160-190] its epoch | [192] stopped | [193-224] the block of its last stop; word 1 its stop key, never
/// zero; word 2 its word key, a mirror of its cell's slot 3 (zero for none), which the binding reads.
struct Desk {
uint256 w0;
address stopKey;
address wordKey;
}
/// @dev A per-token feed record, reserved: `Layout.feeds` is never written.
struct FeedRecord {
uint256 w; // reserved
bytes32 dsFeedId; // reserved: the high-security tier
bytes32 dsSuccessorId; // reserved
}
/// @dev The front's storage at `BASE`: each field's comment opens with its slot's offset.
struct Layout {
address owner; // 0: the front's timelock, the protocol owner acting after its delay (`owner()`)
address safe; // 1: the protocol owner's instant key, a multisig (`instantOwner()`)
address protocolGuardian; // 2: the protocol guardian, who stops but never loosens (`protocolGuardian()`)
// 3: the launcher, the one caller of `reservePool`, `confirmPool`, `reserveListing`, `confirmListing`,
// `addListing` and `bindAtBirth`
address launcher;
// 4: the registry (0-159; zero on a storage build) | paused all (160) | every lease cut (161) | reserved, 0
// (162) | desks may open (163: set at `initialize` and never cleared, so it reads 1 from the front's birth)
uint256 g0;
address[2] relayKeys; // 5, 6 (reserved: relay co-signing)
address reserved7a; // 7 (reserved: unused; no vendor's state sits in the front)
uint48 reserved7b; // 7 (reserved: unused)
address dataStreamsChecker; // 8 (reserved: the high-security tier)
bytes32 poolCodehash; // 9 (reserved: the pool template pin)
address familyPriceFeed; // 10 (reserved)
// 11: next pair id (0-31) | next pool id (32-55; it stops at 2^24 - 1, short of bit 56) | the last desk id
// given (56-87) | the last source id given (88-119, `registerSource`) | code frozen for good (254) |
// initialized (255)
uint256 ids;
uint256 pendingRegistry; // 12: registry (0-159) | due at, unix s (160-223)
mapping(address => bool) curatorAllowed; // 13 (reserved: the launcher keeps no operator list)
mapping(address => FeedRecord) feeds; // 14 (reserved: a per-token feed registry; feeds sit in the pair word)
// 15: the price sources, keyed by a global id (1 to 2^32 - 1, given in order, the last in `ids`; 0 is never
// written), each registered by anyone (`registerSource`), written once and never edited (`PropAMMWords`, source
// entry): [0-159] the source contract (a builder build's pull check, the CREATE3 child of the front at salt
// `bytes32(id)`; a storage build's stored price lane) | [160-191] a stored price lane's base and quote slots |
// [192-223] the floor, millionths of a quote token | [240-243] the window | [246] an equity base slot | [254] a stored
// price lane. A listing binds one and a backup (`setSource`, its record's words 2 and 10)
mapping(uint256 => uint256) sources;
// 16: keccak256(abi.encodePacked(token0, token1)) => pair id (0-31) | an asset-module pair's `asset` word
// (32-195: its module and its base's family; 0 on any other pair, and once removed) | the pair word's facts
// (196-251, `PropAMMWords.entryFacts`) | 0 (252-255), on every build, written by `addPair` and
// `removeAssetModule` alone and cleared whole by `retirePair`. Readers of the id mask it, and readers of the
// asset word mask it to its 164 bits. This layout suits a fresh front: a word written by a build without the
// facts copy reads as an empty pair word, so an in-place upgrade from such a build must back-fill every pair
// first
mapping(bytes32 => uint256) pairIdOf;
mapping(uint256 => Pair) pairs; // 17
mapping(uint256 => Pool) pools; // 18
// 19: the slot map, `(desk << 8) | word index` => the listing last bound to that desk at that word index
// (0 for none). It is read against the listing it names (`PropAMMShared._slotTaken`), so it is never cleared
mapping(uint256 => uint256) slotListing;
// 20: the pool's first listing (0-23) | the block its launch reserved it, the one it went live (24-71,
// `PropAMMDue.born`) | has held a further listing (255)
mapping(address => uint256) poolIdOf;
mapping(uint256 => uint256) makerKeys; // 21: (poolId << 32 | epoch) => key type (160-167) | key
mapping(uint256 => bytes32[2]) p256Keys; // 22 (reserved: P-256 keys)
mapping(uint256 => mapping(address => uint256)) sessionKeys; // 23 (reserved: session keys)
// 24: change id (keccak256(abi.encode(poolId, kind))) => the scheduled value's tag (0-191: keccak256 of the
// value, top 192 bits) | due at, unix s (192-255)
mapping(bytes32 => uint256) pending;
// 25: `listingKey(pool, pairId)` => the pool's further listing on that pair, live or reserved, or a retired one
// the protocol owner delisted (kept until its `relistListing`)
mapping(uint256 => uint256) listingOf;
// 26: the protocol's asset module, set at `initialize` for good (zero for none): `addPair` asks it which bases
// it claims (`familyOf`), refuses a quote it claims and adds no pair while it has no code
address assetModule;
mapping(address => mapping(address => bool)) pairHookOk; // 27 (reserved: unused; pair hooks are the operator's)
uint256[14] reserved28; // 28-41 (reserved, never written)
// 42: the ticket door's replay words, a ring of 16 targets a listing (blocks, or unix seconds on a storage
// build): (listing << 8 | target % 16) => [0-63] the target + 1 | [64-255] one bit a replay index 0-191, so a
// listing fills at most 192 guarded quotes a target
mapping(uint256 => uint256) replayRing;
mapping(uint256 => Desk) desks; // 43: the desks, by id (assigned in order from 1, `ids` bits 56-87)
uint256 reserved44; // 44 (reserved, never written)
// 45: the ANY takers' words, by keyEpoch << 56 | desk << 24 | listing, then by taker: [0-15] the taker's
// heartbeat H (1-256), 0 unlisted, under the listing's full key epoch at its listing, so a new key epoch
// empties the list
mapping(uint256 => mapping(address => uint256)) anyTakers;
// 46: the chain's quote assets, by token (`uint160`): its rank, 1 the first; 0 none. `addPair` reads it alone,
// so a change rules only the pairs added after it (`setQuoteAsset`)
mapping(uint256 => uint256) quoteRank;
}
/// @dev `poolIdOf` bit 255: set when the pool first reserves a listing on a further pair and never cleared, a hint
/// to read `listingOf` (whose entries an operator's retirement clears), not a count of listings held.
uint256 internal constant LISTINGS_FLAG = 1 << 255;
/// @dev `listingOf`'s key: uint160(pool) << 32 | pairId.
function listingKey(address pool, uint256 pairId) internal pure returns (uint256) {
return (uint256(uint160(pool)) << 32) | pairId;
}
/// @dev The front's storage, in the namespace at `BASE`.
function state() internal pure returns (Layout storage $) {
assembly ("memory-safe") {
$.slot := BASE
}
}
// ---------------------------------------------------------------- transient
/// @dev Whether a fill holds the front's lock.
function locked() internal view returns (bool l) {
assembly ("memory-safe") {
l := iszero(iszero(tload(BASE)))
}
}
/// @dev Takes the front's lock, reverting `Locked` where a fill holds it.
function lock() internal {
assembly ("memory-safe") {
if tload(BASE) {
mstore(0, 0x0f2e5b6c) // Locked()
revert(0x1c, 4)
}
tstore(BASE, 1)
}
}
/// @dev Releases the front's lock.
function unlock() internal {
assembly ("memory-safe") {
tstore(BASE, 0)
}
}
}
src/propamm/libraries/PropAMMWords.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {PropAMMLaneLib} from "src/propamm/libraries/PropAMMLaneLib.sol";
import {PPM} from "src/libraries/Constants.sol";
/// @notice The front's word formats, LSB first. Maker-signed words (pool word, depth, controls) freeze with the maker
/// format; the front's own words (pair word, listing status, board word) freeze with the storage layout. Every
/// word carries a nonzero version. Reserved fields stay in the formats.
/// @dev A side's board is its maker-signed ladder, the two depth words, plus the front's memory of the fills against
/// that ladder, the side's board word: the maker signs the first, and the front alone writes the second. A new
/// depth nonce or a word's refill restarts the memory. A board unit is 10^`boardExp` base units of the side's
/// input token: the fill memory counts in it, and a rung's size in 10^`dExp` of it.
library PropAMMWords {
uint256 internal constant M8 = 0xff;
uint256 internal constant M16 = 0xffff;
uint256 internal constant M20 = 0xfffff;
uint256 internal constant M24 = 0xffffff;
uint256 internal constant M32 = 0xffffffff;
uint256 internal constant M40 = 0xffffffffff;
uint256 internal constant M48 = 0xffffffffffff;
uint256 internal constant M64 = 0xffffffffffffffff;
uint256 internal constant M80 = 0xffffffffffffffffffff;
uint256 internal constant M96 = 0xffffffffffffffffffffffff;
uint256 internal constant M160 = (1 << 160) - 1;
// ---------------------------------------------------------------- pool word (maker-signed)
/// @dev [0-7] kind and version | [8-71] price mantissa | [72-119] maker time ms | [120-135] life s |
/// [136-151] bid skew ppm | [152-167] ask skew ppm | [168-199] max block, the last valid block, inclusive (0
/// none; no fill reads it, as a desk's cell writes these bits itself) | [200-207] key epoch, low 8 bits |
/// [208-231] the listing's pool id | [232-255] refill with acknowledgement: [232] bid, [233] ask, [234-244]
/// bid fill sequence, [245-255] ask fill sequence (each the low 11 bits of the side's board sequence). A word
/// refills a side once (`refills`): a maker stamps a refill word at the later of its own clock and the side's
/// last fill time plus 1 ms, and 1 ms later again where its time's low 9 bits match the side board's bits
/// 247-255.
uint256 internal constant KIND_QUOTE = 0x01;
function kind(uint256 w) internal pure returns (uint256) {
return w & M8;
}
function mantissa(uint256 w) internal pure returns (uint256) {
return (w >> 8) & M64;
}
function makerTs(uint256 w) internal pure returns (uint256) {
return (w >> 72) & M48;
}
function ttl(uint256 w) internal pure returns (uint256) {
return (w >> 120) & M16;
}
function skew(uint256 w, bool bid) internal pure returns (uint256) {
return (w >> (bid ? 136 : 152)) & M16;
}
function epoch8(uint256 w) internal pure returns (uint256) {
return (w >> 200) & M8;
}
function poolId(uint256 w) internal pure returns (uint256) {
return (w >> 208) & M24;
}
/// @dev Whether the word asks to refill `bid`'s side, and the 11-bit fill sequence it acknowledges.
function refill(uint256 w, bool bid) internal pure returns (bool on, uint256 ack) {
if (bid) return (((w >> 232) & 1) != 0, (w >> 234) & 0x7ff);
return (((w >> 233) & 1) != 0, (w >> 245) & 0x7ff);
}
/// @dev Whether pool word `w` refills `bid`'s side, whose board word is `b`: it asks it and acknowledges the side's
/// sequence, it was signed after the side's last fill (strictly: every fill of a block shares one clock), and
/// it is not the word that refilled the side last (its maker time's low 9 bits against board bits 247-255,
/// which the refilling fill writes), so a word stamped ahead of the fill clock still refills once only.
function refills(uint256 w, bool bid, uint256 b) internal pure returns (bool) {
(bool on, uint256 ack) = refill(w, bid);
uint256 ts = makerTs(w);
return on && ack == bSeq(b) && ts > bTime(b) && ts & 0x1ff != b >> 247;
}
// ---------------------------------------------------------------- depth (maker-signed)
/// @dev Word 0: [0-3] version | [4-11] key epoch | [12-59] nonce ms | [60-91] expires at s | [92-111] drift
/// ppm/s | [112-117] size exponent | [118] word 1 present | [119] 0 | [120-227] rungs 0-2 | [228-255] 0.
/// Word 1: rungs 3-9 in [0-251] | version in [252-255]. A rung: cumulative size (16, low) | offset ppm (20).
function dVersion(uint256 d) internal pure returns (uint256) {
return d & 0xf;
}
function dEpoch8(uint256 d) internal pure returns (uint256) {
return (d >> 4) & M8;
}
function dNonce(uint256 d) internal pure returns (uint256) {
return (d >> 12) & M48;
}
function dExpires(uint256 d) internal pure returns (uint256) {
return (d >> 60) & M32;
}
function dDrift(uint256 d) internal pure returns (uint256) {
return (d >> 92) & M20;
}
function dExp(uint256 d) internal pure returns (uint256) {
return (d >> 112) & 0x3f;
}
function dHasW1(uint256 d) internal pure returns (bool) {
return ((d >> 118) & 1) != 0;
}
/// @dev Rung `j` (0-9) of a side: its 36 bits.
function rung(uint256 w0, uint256 w1, uint256 j) internal pure returns (uint256) {
return j < 3 ? (w0 >> (120 + 36 * j)) & 0xfffffffff : (w1 >> (36 * (j - 3))) & 0xfffffffff;
}
// ---------------------------------------------------------------- controls (maker-signed)
/// @dev [0-7] version | [8-15] key epoch | [16-63] nonce ms | [64-71] flags (bit 0 self-pause, bit 2 refill with
/// acknowledgement allowed, bit 3 resume: lifts a standing self-pause, `postControls`; bit 1, the session
/// gate, reserved) | [72-76] session mask (reserved, 0) | [77-79] 0 | [80-103] bid rate cap | [104-127] ask
/// rate cap | [128-135] burst s | [136-155] widening ppm/sqrt(s) | [156-175] premium ppm | [176-191] premium
/// window ms | [192-207] widening grace ms | [208-255] zero in a posted word (a multiplier fingerprint's,
/// reserved); in the stored word the nonce its self-pause state stands on (`postControls`: while paused the
/// highest pause's, while live the highest resume's or 1 for none in the epoch; zero only in a word stored
/// before that rule, read as the standing post's nonce while paused, one over it while live), which no fill
/// reads.
uint256 internal constant CTL_SELF_PAUSE = 1 << 64;
uint256 internal constant CTL_REFILL = 1 << 66;
uint256 internal constant CTL_RESUME = 1 << 67;
uint256 internal constant CTL_FLAGS_KNOWN = 0xd;
/// @dev Bits 0-207: the posted fields, below the stored pause state's nonce.
uint256 internal constant CTL_LOW = (1 << 208) - 1;
function cNonce(uint256 c) internal pure returns (uint256) {
return (c >> 16) & M48;
}
function cRate(uint256 c, bool bid) internal pure returns (uint256) {
return PropAMMLaneLib.amount24((c >> (bid ? 80 : 104)) & M24);
}
function cBurstSec(uint256 c) internal pure returns (uint256) {
return (c >> 128) & M8;
}
function cWiden(uint256 c) internal pure returns (uint256) {
return (c >> 136) & M20;
}
function cPremium(uint256 c) internal pure returns (uint256) {
return (c >> 156) & M20;
}
function cPremiumWindow(uint256 c) internal pure returns (uint256) {
return (c >> 176) & M16;
}
function cGrace(uint256 c) internal pure returns (uint256) {
return (c >> 192) & M16;
}
// ---------------------------------------------------------------- board state (the front's own)
/// @dev [0-3] version | [4-51] depth tag | [52-91] filled, board units | [92-187] bucket level, quote base units
/// | [188-235] bucket time ms | [236-246] fill sequence (11 bits, wraps) | [247-255] the low 9 bits of the
/// maker time of the pool word that refilled the side last (0 before its first refill).
function board(uint256 tag, uint256 filled, uint256 level, uint256 timeMs, uint256 seq, uint256 refilledBy)
internal
pure
returns (uint256)
{
return 1 | (tag << 4) | (filled << 52) | (level << 92) | (timeMs << 188) | ((seq & 0x7ff) << 236)
| (refilledBy << 247);
}
function bTag(uint256 b) internal pure returns (uint256) {
return (b >> 4) & M48;
}
function bFilled(uint256 b) internal pure returns (uint256) {
return (b >> 52) & M40;
}
function bLevel(uint256 b) internal pure returns (uint256) {
return (b >> 92) & M96;
}
function bTime(uint256 b) internal pure returns (uint256) {
return (b >> 188) & M48;
}
function bSeq(uint256 b) internal pure returns (uint256) {
return (b >> 236) & 0x7ff;
}
// ---------------------------------------------------------------- pair word (the front's own)
/// @dev [0-7] version | [8] base is token0 | [9] high-security (reserved, 0) | [10] the quote is a listed quote
/// asset as the list stood at `addPair` (`PAIR_QUOTE_ASSET`) | [11-13] reserved, 0 | [14] paused (reserved) |
/// [15] an asset-module pair (`PAIR_ASSET`) | [16-23] reserved, 1 | [24-31] reserved, 1 | [32-95] reserved,
/// 0 | [96-103] price-unit exponent u, 24 + quote decimals - base decimals, so the cross's scale k is 12 |
/// [104-111] reserved, 0 | [112-119] bid board exponent, base decimals - 6 | [120-127] ask board exponent,
/// quote decimals - 2 where bit 10 is set, else quote decimals - 6, each at least 0 | [128-175] reserved, 0 |
/// [176-183] base decimals | [184-191] quote decimals | [192-255] reserved, 0. `addPair` derives every field
/// from the two tokens and the lists as they stand, so a pair's facts are the same whoever adds it: the quote
/// is the listed quote asset where one token is one, the lower rank where both are, else the token the asset
/// module does not claim (token1 where it claims neither). A price source and a lease are each
/// listing's own (record words 2 and 10), never the pair's. Every pair is of one kind: any number of
/// listings, each reached by its id, and no list or count of them. The word is written once and is the
/// record; the pair's `pairIdOf` word carries a copy of its facts, which fills and quotes read (`entryFacts`).
uint256 internal constant PAIR_BASE_IS_T0 = 1 << 8;
/// @dev The pair's quote was a listed quote asset at `addPair` (`quoteRank`), which sets the ask board's exponent.
uint256 internal constant PAIR_QUOTE_ASSET = 1 << 10;
/// @dev An asset-module pair: the protocol's asset module claimed its base at `addPair` (`familyOf`), and every
/// quote and fill of it asks the module.
uint256 internal constant PAIR_ASSET = 1 << 15;
function unitExp(uint256 p) internal pure returns (uint256) {
return (p >> 96) & M8;
}
/// @dev The board unit exponent of the side whose input it counts: the base token's on a bid, the quote's on an
/// ask.
function boardExp(uint256 p, bool bid) internal pure returns (uint256) {
return (p >> (bid ? 112 : 120)) & M8;
}
function decBase(uint256 p) internal pure returns (uint256) {
return (p >> 176) & M8;
}
function decQuote(uint256 p) internal pure returns (uint256) {
return (p >> 184) & M8;
}
/// @dev k = 36 + decQuote - decBase - u: the cross's scale, P̂ = pa * 10^k / pb (12 on each pair `addPair` writes).
function crossExp(uint256 p) internal pure returns (uint256) {
return 36 + decQuote(p) - decBase(p) - unitExp(p);
}
// ---------------------------------------------------------------- a pair's `pairIdOf` word (the front's own)
/// @dev [0-31] the pair id | [32-195] an asset-module pair's asset word (`PropAMMStore.Pair.asset`), 0 on any
/// other pair | [196-251] the pair word's facts, the copy every fill and quote reads in place of the pair
/// word: its bits 0-15 (version and flags) at 196-211, 96-103 (u) at 212-219, 112-127 (the board exponents)
/// at 220-235 and 176-191 (the decimals) at 236-251 | [252-255] 0. Every other pair-word bit is a constant
/// of `addPair`'s (`PAIR_FIXED` set, the rest 0), so the copy gives the word back whole (`entryWord`).
/// `addPair` writes the copy with the pair word, `removeAssetModule` writes it again, and nothing else
/// writes either; a retired pair's word is cleared whole (`retirePair`).
uint256 internal constant ENTRY_FACTS = 196;
/// @dev The pair-word bits `addPair` sets outside the copy: reserved bits 16 and 24.
uint256 internal constant PAIR_FIXED = (1 << 16) | (1 << 24);
/// @dev The asset word a `pairIdOf` word `e` carries (bits 32-195).
function entryAsset(uint256 e) internal pure returns (uint256) {
return (e >> 32) & ((uint256(1) << 164) - 1);
}
/// @dev Pair word `p`'s facts, at their place in the pair's `pairIdOf` word.
function entryFacts(uint256 p) internal pure returns (uint256) {
return ((p & M16) | (((p >> 96) & M8) << 16) | (((p >> 112) & M16) << 24) | (((p >> 176) & M16) << 40))
<< ENTRY_FACTS;
}
/// @dev The pair word whose facts the `pairIdOf` word `e` copies.
function entryWord(uint256 e) internal pure returns (uint256) {
uint256 f = e >> ENTRY_FACTS;
return (f & M16) | PAIR_FIXED | (((f >> 16) & M8) << 96) | (((f >> 24) & M16) << 112)
| (((f >> 40) & M16) << 176);
}
// ---------------------------------------------------------------- listing status P0 (the front's own)
/// @dev [0-159] the pool | [160-191] pair id | [192-199] flags | [200-231] key epoch | [232-239] the listing's word
/// index: its standing word in its desk's cell (0 at reservation; written by the desk binding alone) |
/// [240-247] reserved, 0 (a listing's sources sit in its record's words 2 and 10) | [248-255] the listing's
/// token indices in its pool, base (248-251) and quote (252-255); 0 on the pool's hook pair (base token 0, the
/// pool asset; quote token 1). The cheap lane hands the pool this byte as its pair bits. Flag bits: 192
/// (`F_LIVE`) set while the listing is live, 193 to 195 the three below, 196-198 reserved, 199 (`F_ASSET`) set
/// while an asset-module listing asks its own module (word 11 of the listing's record) in place of its pair's.
uint256 internal constant F_LIVE = 1 << 192;
/// @dev Reserved: nothing sets it. A fill reads it through `F_DARK`, and `unpause` clears it.
uint256 internal constant F_PAUSED = 1 << 193;
/// @dev The listing is frozen (`freeze`): its pool's guardian or its operator lifts it (`unfreeze`).
uint256 internal constant F_FROZEN = 1 << 194;
/// @dev The maker key paused the listing (`pauseMaker`); only the operator's `unpause` lifts it.
uint256 internal constant F_MAKER_PAUSED = 1 << 195;
/// @dev Every flag that darkens a listing at fill.
uint256 internal constant F_DARK = F_PAUSED | F_FROZEN | F_MAKER_PAUSED;
/// @dev The listing asks its own asset module (`setAssetModule`), not its pair's.
uint256 internal constant F_ASSET = 1 << 199;
function sPairId(uint256 s) internal pure returns (uint256) {
return (s >> 160) & M32;
}
function sEpoch(uint256 s) internal pure returns (uint256) {
return (s >> 200) & M32;
}
/// @dev The listing's token indices, P0's top byte: base (low 4 bits) and quote (high 4 bits); 0 on the hook pair.
function sIndices(uint256 s) internal pure returns (uint256) {
return s >> 248;
}
/// @dev The listing's word index, P0 bits 232-239: the standing word its desk's cell keeps for it (slot 16 +
/// index).
function sWordIndex(uint256 s) internal pure returns (uint256) {
return (s >> 232) & M8;
}
// ---------------------------------------------------------------- settings P1
/// @dev `Settings` packed in declaration order: fences (0, 16) and the ceiling (32), each ppm / 10 (one unit 0.1
/// bp, at most 65,535 units, 655,350 ppm), max age (48), rate ceilings (64, 88), burst ceilings (112, 136),
/// minimum fill (160), split depth (184), the confidence multiplier (232); [192-223] the listing's desk, a
/// uint32 (0 unbound) | [224] reserved | [225-226] the credit mode (`CREDIT_*`) | [227] ANY allowed |
/// [228-229] the fence kind (`FENCE_*`) | [230] the carry life L in blocks, 0 or 1 | [231] tied (`tied`:
/// beside PRINT and no carry life alone; any other use refused) | [232-239] the confidence multiplier k, tenths, at most 30 | [240-255] the taker tip cap: a
/// 12-bit mantissa (240-251) and a 4-bit exponent of 10 (252-255), wei per gas, 0 off. Zero is safe in every
/// field: a zeroed fence kind reads PRINT, the most fenced; a zeroed cap is off; desk 0 is unbound. The
/// admin's setters write their own bits and keep the rest; the desk bits (192-223, 227-231 and P0's word
/// index) are the desk binding's alone.
uint256 internal constant SETTINGS_BITS = ((1 << 192) - 1) | (M8 << 232);
uint256 internal constant DESK_SHIFT = 192;
uint256 internal constant CREDIT_SHIFT = 225;
uint256 internal constant ANY_SHIFT = 227;
uint256 internal constant FENCE_SHIFT = 228;
uint256 internal constant CARRY_SHIFT = 230;
uint256 internal constant CONF_MUL_SHIFT = 232;
uint256 internal constant TIP_SHIFT = 240;
/// @dev The fence kinds (P1 bits 228-229): the vendor print (0, a kept print or one the taker carries), the
/// landed word signed by the desk's word key (1), none (2, caps alone on the ticket door), or the session
/// kind (3): the print while it is fresh, and the signed word inside a band around the listing's last kept
/// print once that print is stale long enough (the listing's closed phase, `off`). A binding ranks them PRINT,
/// SESSION, WORD, NONE, the most fenced first (`fenceRank`), which is not their numbers' order.
uint256 internal constant FENCE_PRINT = 0;
uint256 internal constant FENCE_WORD = 1;
uint256 internal constant FENCE_NONE = 2;
uint256 internal constant FENCE_SESSION = 3;
/// @dev The fence kinds' ranks, two bits a kind at twice its number: PRINT 0, WORD 2, NONE 3, SESSION 1.
uint256 internal constant FENCE_RANKS = 0x78;
/// @dev The rank of the fence kind in binding scopes `scopes` (bits 1-2): 0 the most fenced.
function fenceRank(uint256 scopes) internal pure returns (uint256) {
return (FENCE_RANKS >> (scopes & 6)) & 3;
}
/// @dev Whether fence kind `k` reads a print: PRINT, and SESSION.
function printed(uint256 k) internal pure returns (bool) {
return k % 3 == 0;
}
/// @dev The listing's desk, P1 bits 192-223: 0 unbound.
function desk(uint256 s) internal pure returns (uint256) {
return (s >> DESK_SHIFT) & M32;
}
/// @dev Whether the listing's desk may fill ANY quotes there (P1 bit 227).
function anyOn(uint256 s) internal pure returns (bool) {
return (s >> ANY_SHIFT) & 1 != 0;
}
/// @dev The listing's fence kind, P1 bits 228-229 (`FENCE_*`).
function fenceKind(uint256 s) internal pure returns (uint256) {
return (s >> FENCE_SHIFT) & 3;
}
/// @dev The listing's carry life L in blocks, P1 bits 230-231: whether a word of the listing's own may still fill a
/// named fill in the block after its landing (L 1, and the word's own carry life nonzero); never later, so
/// the binding refuses more and the named door reads more as one.
function carry(uint256 s) internal pure returns (uint256) {
return (s >> CARRY_SHIFT) & 3;
}
/// @dev A tied listing's scopes, P1 bits 228-231 read as one number: the fence kind PRINT, no carry life, and the
/// binding's scope bit 4 (P1 bit 231, the carry life's high bit, which no carry life sets: a life is 0 or 1).
/// Only a PRINT listing of a storage build binds it (`bindListing`), where nothing reads a carry life.
uint256 internal constant TIED_SCOPES = 8;
/// @dev `PoolFill.boardTag` bit 254, and the plan's desk tag's: the fill was a tied listing's named fill, priced
/// from its print.
uint256 internal constant TAG_TIED = 1 << 254;
/// @dev Whether the listing is tied: its named fills walk its desk's ladder from the listing's print, where every
/// other listing's walk from its desk's word, and its word fences them (`PropAMMFront._evaluate`). Bit 231
/// beside any other fence kind or a carry life is not a tied listing's.
function tied(uint256 s) internal pure returns (bool) {
return (s >> FENCE_SHIFT) & 15 == TIED_SCOPES;
}
/// @dev The listing's taker tip cap, P1 bits 240-255, as stored: 0 off.
function tipCap(uint256 s) internal pure returns (uint256) {
return s >> TIP_SHIFT;
}
/// @dev A tip cap's value, wei per gas: its 12-bit mantissa times 10 to its 4-bit exponent.
function tipWei(uint256 c) internal pure returns (uint256) {
return (c & 0xfff) * pow10((c >> 12) & 15);
}
// ---------------------------------------------------------------- the desk's words (its cell's storage)
/// @dev The ticket, a cell's slot 0: [0-31] stamp, the block number's low 32 bits when the cell wrote it (on a
/// storage build the low 32 bits of its push's maker time, never 0) | [32-62] desk epoch | [63] stopped |
/// [64-127] the desk word: [64-111] twelve 4-bit latch counts, desk book b and side s at 64 + 4(2b + s) (s 1
/// for the pool's bid) | [112-126] version, 15 bits | [127] the registry mark, set on a copy of a builder
/// lane | [128-223] six 16-bit desk book indexes, book 0 lowest | [224-255] the desk floor. What the books,
/// indexes, latches and floor mean: `PropAMMLandingDesk.FirmQuote`.
function tStamp(uint256 t) internal pure returns (uint256) {
return t & M32;
}
function tEpoch(uint256 t) internal pure returns (uint256) {
return (t >> 32) & 0x7fffffff;
}
function tStopped(uint256 t) internal pure returns (bool) {
return (t >> 63) & 1 != 0;
}
/// @dev Desk book `b`'s latch count for one side, the pool's bid where `bid`.
function tLatch(uint256 t, uint256 b, bool bid) internal pure returns (uint256) {
return (t >> (64 + 8 * b + (bid ? 4 : 0))) & 15;
}
function tVersion(uint256 t) internal pure returns (uint256) {
return (t >> 112) & 0x7fff;
}
/// @dev Desk book `b`'s landed index.
function tIndex(uint256 t, uint256 b) internal pure returns (uint256) {
return (t >> (128 + 16 * b)) & M16;
}
function tFloor(uint256 t) internal pure returns (uint256) {
return t >> 224;
}
/// @dev A standing word as a cell's read answers it (index 0-7: its slot 16 + i; 8 and up: an entry of a packed
/// group, expanded, whose life is at most 511 s), in the pool word's format but for: [0-3] kind (1 quote, 2
/// off) | [4-7] the word's carry: 0 none; any nonzero value lets it fill only in the block after its landing
/// (the front reads no more) | [168-199] its write stamp (the cell's): the low 32 bits of the block the cell
/// wrote it in (builder) or that block's unix second (storage), never its maker time, which freshness reads
/// from bits 72-119 | [200-207] the desk epoch's low 8 bits (the cell's) | [208] signed by the desk's word key
/// (the cell's) | [209] reference only (the named door refuses it) | [210-224] the version of the landing
/// that wrote it (the cell's): at a packed index on both families, at 0-7 on a storage build (reserved, as
/// pushed, at 0-7 on a builder build) | [225-231] reserved, 0, ignored. The front reshapes it into a pool
/// word for the walk: bits 4-7 and 168-231 cleared, the listing's key epoch at 200-207 and the listing at
/// 208-231.
function wKind(uint256 w) internal pure returns (uint256) {
return w & 15;
}
function wCarry(uint256 w) internal pure returns (uint256) {
return (w >> 4) & 15;
}
function wStamp(uint256 w) internal pure returns (uint256) {
return (w >> 168) & M32;
}
function wSigned(uint256 w) internal pure returns (bool) {
return (w >> 208) & 1 != 0;
}
function wRefOnly(uint256 w) internal pure returns (bool) {
return (w >> 209) & 1 != 0;
}
/// @dev A storage build's standing word: the version of the push that wrote it.
function wVersion(uint256 w) internal pure returns (uint256) {
return (w >> 210) & 0x7fff;
}
// ---------------------------------------------------------------- the ticket door's quote (kind 1)
/// @dev `FirmQuote.terms`: [0-23] listing | [24] bid (the taker sells base) | [25] partial fills | [26] the taker
/// is `tx.origin` (TICKET only) | [27-31] 0 | [32-39] listing key epoch, low 8 bits | [40-87] signed at, ms |
/// [88-119] target, a block (a unix second on a storage build) | [120-127] extra targets K | [128-135] desk
/// epoch, low 8 bits | [136-143] replay index | [144-147] kind 1 | [148-179] generation | [180-183] 0 | [184]
/// TICKET (else ANY) | [185-187] desk book | [188-203] the book's index it was priced at | [204-211] cap, 0.1
/// bp ticks | [212-214] reprice mode | [215-218] the side's latch count at signing | [219] skip the latch |
/// [220-255] 0. What the desk fields mean, and how a move of the ticket voids or reprices the quote:
/// `PropAMMLandingDesk.FirmQuote`.
function qSigned(uint256 t) internal pure returns (uint256) {
return (t >> 40) & M48;
}
function qTarget(uint256 t) internal pure returns (uint256) {
return (t >> 88) & M32;
}
function qExtra(uint256 t) internal pure returns (uint256) {
return (t >> 120) & M8;
}
function qReplay(uint256 t) internal pure returns (uint256) {
return (t >> 136) & M8;
}
function qGeneration(uint256 t) internal pure returns (uint256) {
return (t >> 148) & M32;
}
function qTicket(uint256 t) internal pure returns (bool) {
return (t >> 184) & 1 != 0;
}
function qBook(uint256 t) internal pure returns (uint256) {
return (t >> 185) & 7;
}
function qMode(uint256 t) internal pure returns (uint256) {
return (t >> 212) & 7;
}
/// @dev The credit modes, each looser than the one before: the front fills from custody alone (0);
/// where custody cuts a fill short it routes it to the pool's own swap if no pair of the pool may borrow the
/// output token (1), or whether or not one may (2); it routes every fill to the pool's own swap (3).
uint256 internal constant CREDIT_CHEAP = 0;
uint256 internal constant CREDIT_SUPPLY = 1;
uint256 internal constant CREDIT_BORROW = 2;
uint256 internal constant CREDIT_ALWAYS = 3;
/// @dev The listing's confidence multiplier, P1 bits 232-239: tenths.
function confMul(uint256 s) internal pure returns (uint256) {
return (s >> CONF_MUL_SHIFT) & M8;
}
function creditMode(uint256 s) internal pure returns (uint256) {
return (s >> CREDIT_SHIFT) & 3;
}
/// @dev The side's price fence B, ppm (its field x 10).
function fence(uint256 s, bool bid) internal pure returns (uint256) {
return ((s >> (bid ? 0 : 16)) & M16) * 10;
}
/// @dev The listing's ceiling R, ppm (its field x 10): the most its band's fence and refusal reach.
function ceil(uint256 s) internal pure returns (uint256) {
return ((s >> 32) & M16) * 10;
}
function maxAgeMs(uint256 s) internal pure returns (uint256) {
return (s >> 48) & M16;
}
function rateCeil(uint256 s, bool bid) internal pure returns (uint256) {
return PropAMMLaneLib.amount24((s >> (bid ? 64 : 88)) & M24);
}
function burstCeil(uint256 s, bool bid) internal pure returns (uint256) {
return PropAMMLaneLib.amount24((s >> (bid ? 112 : 136)) & M24);
}
function minFill(uint256 s) internal pure returns (uint256) {
return PropAMMLaneLib.amount24((s >> 160) & M24);
}
function splitDepth(uint256 s) internal pure returns (uint256) {
return (s >> 184) & M8;
}
// ---------------------------------------------------------------- P2, record word 2 (`price`, the front's own)
// The live source's hot copy, which a fill reads alone for its source (`PropAMMShared._srcOf`); zero while the
// listing has no source. A builder build: [0-31] the live source's id, its pull check the CREATE3 child of the
// front at salt `bytes32(id)` | [32-199] reserved, 0 | [200-231] the listing's lease, unix s: until then its source
// may honour its cached trust (`refreshLease`; a new binding starts with none) | [232-235] reserved, 0. A storage
// build: [0-159] the live source's stored price lane | [160-175] its base slot | [176-191] its quote slot |
// [192-235] reserved, 0. Both: [236-239] and [240-243] the live source's window, 500 ms steps, its high and its
// low four bits (`win`) | [244] `P2_ON_BACKUP` | [245] `P2_DARK` | [246] `P2_HELD` | [247] `E_GUARD`, the live
// source's, as its entry holds it | [248-255] reserved, 0. Word 10 (`sourceIds`)
// names the bound ids: [0-31] the primary | [32-63] the backup (0 none) | [64-255] reserved, 0; zero exactly where
// this word is.
/// @dev The listing reads its backup: its primary was darkened (`darkenSource`).
uint256 internal constant P2_ON_BACKUP = 1 << 244;
/// @dev The listing reads no source: darkened with no backup to fall to, every other bit 0 but `P2_HELD`, so a
/// PRINT fill finds none (`SourceDark`).
uint256 internal constant P2_DARK = 1 << 245;
/// @dev Beside `P2_ON_BACKUP` or `P2_DARK` alone: the pool's guardian made the darken, or held it after its
/// operator's (`darkenSource`), so the operator re-lights the binding the listing stands on only after the
/// pool's delay D (`setSource`); a promote of the backup clears it.
uint256 internal constant P2_HELD = 1 << 246;
// ---------------------------------------------------------------- session word, record word 13 (the front's own)
// A SESSION listing's closed-phase settings (`setSession`), zero for none: [0-15] `closedAfter`, s: the listing is
// in its closed phase once its kept print's older leg is at least this old on the age clock (60 to 21,600; 0, no
// closed phase) | [16-31] `offBase`, the band's start, 0.1 bp | [32-47] `offCeil`, the band's ceiling, 0.1 bp |
// [48-63] `offMinSkew`, the least skew of the filled side's word, ppm | [64-79] `offWiden`, the band's widening,
// ppm per sqrt(s) | [80-103] `offMaxNotional`, the most quote-leg notional a side's bucket holds in the closed
// phase, a 24-bit amount as the settings' | [104-255] 0. Bits 32-63 sit where P1 keeps its ceiling and its max age,
// so `off` copies them in place.
uint256 internal constant SESSION_BITS = (1 << 104) - 1;
/// @dev `closedAfter`'s bounds, s: a poster's brief lag never opens the closed phase, and a print six hours stale
/// always may.
uint256 internal constant CLOSED_AFTER_MIN = 60;
uint256 internal constant CLOSED_AFTER_MAX = 21_600;
/// @dev `PoolFill.boardTag` bit 253, and the plan's desk tag's: the fill was a SESSION listing's closed phase.
uint256 internal constant TAG_CLOSED = 1 << 253;
/// @dev A SESSION listing's settings in its closed phase, zero where it is in none: P1 `s1` of a listing bound
/// SESSION, its session word `ss` (nonzero `closedAfter`) and its kept print's age `ageMs`, at least
/// `closedAfter`. Both doors then run P1's own rules on the answer, which is `s1` but for:
/// - both fences (bits 0-31): the band f(t) = min(offCeil, offBase + offWiden x sqrt(t)), 0.1 bp, rounded
/// down, t the print's age in whole seconds (at most 2^24 - 1) and its root taken to 1/256;
/// - the ceiling (32-47): `offCeil`;
/// - the max age (48-63): `offMinSkew`, which each door reads there in the closed phase, where no age is
/// held to the max age;
/// - each burst ceiling (112-135, 136-159): `offMaxNotional` where that is lower.
function off(uint256 s1, uint256 ss, uint256 ageMs) internal pure returns (uint256 o) {
// every field is masked to 16 or 24 bits and t to 24: no product comes near 2^256
unchecked {
uint256 t = ss & M16;
if (fenceKind(s1) != FENCE_SESSION || t == 0 || ageMs < t * 1000) return 0;
t = ageMs / 1000;
if (t > M24) t = M24;
// floor(sqrt(t x 2^16)) by Newton's steps from 2^20, above the root for t under 2^24
uint256 x = t << 16;
uint256 z = 1 << 20;
for (uint256 y = (z + x / z) >> 1; y < z; y = (z + x / z) >> 1) {
z = y;
}
uint256 f = ((ss >> 16) & M16) + ((((ss >> 64) & M16) * z) >> 8) / 10;
uint256 c = (ss >> 32) & M16;
if (f > c) f = c;
o = (s1 & ~M64) | f | (f << 16) | (ss & (M32 << 32));
uint256 cap = (ss >> 80) & M24;
for (uint256 sh = 112; sh < 160; sh += 24) {
if (PropAMMLaneLib.amount24(cap) < PropAMMLaneLib.amount24((o >> sh) & M24)) {
o = (o & ~(M24 << sh)) | (cap << sh);
}
}
}
}
// ---------------------------------------------------------------- source entry (the front's own)
// `PropAMMStore.Layout.sources`, keyed by a global id (1 to 2^32 - 1, given in order by `registerSource` to
// anyone), written once and never edited; `sources[0]` is never written. A builder build: [0-159] the pull check,
// the CREATE3 child of the front at salt `bytes32(id)` | [160-191] reserved, 0. A storage build: [0-159] the stored
// price lane | [160-175] the base slot (1-65,535) | [176-191] the quote slot (1-65,535, never the base's). Both:
// [192-223] the floor, millionths of a whole quote token (0 none) | [224-235] reserved, 0 | [236-239] and [240-243] the
// window (1-255, at most the build's age ceiling), 500 ms steps, its high and its low four bits (`win`) | [244-245]
// reserved, 0 | [246] `E_EQUITY` | [247] `E_GUARD` | [248-253] reserved, 0 | [254] `E_LANE` | [255] reserved, 0.
/// @dev A storage build's source whose base slot is an equity feed (its lane's `jumpsOf` nonzero): an asset-module
/// pair's listing binds only such a source, and any other listing never one.
uint256 internal constant E_EQUITY = 1 << 246;
/// @dev A storage build's guarded source (`registerSource` cfg bit 96): a fill reading it asks its lane for the
/// fill's side over the prints the lane holds (check flags bit 2, `PropAMMShared._srcOf`), so a print a post
/// replaced within the lane's hold still prices that side; a fill on any other source reads the kept print
/// alone. Copied into a listing's P2 with its window (`PropAMMAdmin._live`). A tied listing binds only
/// guarded sources.
uint256 internal constant E_GUARD = 1 << 247;
/// @dev A stored price lane's entry: set on every storage build's entry, on no builder build's.
uint256 internal constant E_LANE = 1 << 254;
/// @dev A source's window in its entry and in a listing's P2, bits 236-243: the low four bits at 240-243, where every
/// entry written under a 4-bit window holds its whole window, and the high four at 236-239, zero there.
uint256 internal constant WIN_BITS = uint256(0xff) << 236;
/// @dev Window `w` (1-255, 500 ms steps) at its bits (`WIN_BITS`).
function winBits(uint256 w) internal pure returns (uint256) {
return ((w & 15) << 240) | ((w >> 4) << 236);
}
/// @dev The window, 500 ms steps, of an entry or a P2 word `x` (`WIN_BITS`).
function win(uint256 x) internal pure returns (uint256) {
return ((x >> 240) & 15) | ((x >> 232) & 0xf0);
}
/// @dev The source's floor, millionths of a whole quote token: a PRINT listing reading it fills at least that much
/// (`PropAMMShared._srcFloor`), on any pair; 0 none.
function eFloor(uint256 e) internal pure returns (uint256) {
return (e >> 192) & M32;
}
// ---------------------------------------------------------------- a fill's log
/// @dev `PoolFill`'s `feeAge`: [0-191] the spread fee | [192-239] the quote's age, ms | [240-254] 0 | [255] the
/// side, 1 a bid (the taker sells the pair's base). The fee is under 2^150 and the age under 2^48 on every
/// path, so neither reaches the field above it.
function feeAge(uint256 fee, uint256 ageMs, bool bid) internal pure returns (uint256) {
return fee | (ageMs << 192) | (bid ? uint256(1) << 255 : 0);
}
// ---------------------------------------------------------------- amounts
/// @dev 10^e for e at most 77 (callers pass at most 63), by the EXP opcode.
function pow10(uint256 e) internal pure returns (uint256 r) {
assembly ("memory-safe") {
r := exp(10, e)
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"runs": 100,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.