Verified contractExactUNLICENSED
PropAMMListingDoors
Address0x39ed9993449c96503f6a629ccd2bb5f132d7cc93
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.35
- Same code
Only this contract
Details
- Compiler
- solc 0.8.35+commit.47b9dedd
- Language
- solidity
- Optimization
- Yes, 100 runs
- EVM version
- cancun
- Via IR
- yes
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,480,640
- Creation transaction
- 0x843c5ce707…2964b269fc
- Libraries
- src/core/mm/MMRouterLib.sol:MMRouterLib0x95b3…48ef2csrc/core/flamm/FLAMMLane.sol:FLAMMLane0x5d81…90de37src/core/flamm/FLAMMRoute.sol:FLAMMRoute0xb1ff…7fb0fesrc/periphery/FLAMMMaxima.sol:FLAMMMaxima0x6854…90a91bsrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0xf55c…49cf45src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x0be7…5ecc47src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xa5db…72803esrc/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0x2795…4cfb77src/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0x3a05…434368src/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x70ca…60bee4src/core/mm/CTokenMarketLib.sol:CTokenMarketLib0x60e4…314010src/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0x0b10…1ce950src/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x634d…298fcdsrc/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0x5dc3…aa7e91src/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0x9dbb…798f1asrc/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0x6b2b…518935src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0x99de…929869src/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0xe4be…cfac2esrc/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0x93ab…262861src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x6abb…60ea7esrc/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0x3858…f91f06src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0x4551…33b301src/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xb852…b71005src/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x6a6a…798659src/hooks/everlong/LeverageLib.sol:LeverageLib0x8039…16d055src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0xaa54…b56417src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0x3bc5…2055ddsrc/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xf6d5…9dfeef
10 files
- src/periphery/door/PropAMMListingDoor.solmain19.34 KB
- lib/openzeppelin-contracts-compat/contracts/utils/math/Math.sol12.51 KB
- src/libraries/Constants.sol2.11 KB
- src/libraries/SafeTransferLib.sol5.11 KB
- src/periphery/door/IPropAMMDoorFront.sol7.05 KB
- src/periphery/door/PropAMMDoorScreen.sol17.6 KB
- src/propamm/interfaces/IPropAMM.sol4.12 KB
- src/propamm/libraries/PropAMMClock.sol5.26 KB
- src/propamm/libraries/PropAMMLaneLib.sol2.31 KB
- src/propamm/libraries/PropAMMWords.sol38.16 KB
src/periphery/door/PropAMMListingDoor.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {IPropAMM, IPropAMMFillable} from "src/propamm/interfaces/IPropAMM.sol";
import {PropAMMWords as W} from "src/propamm/libraries/PropAMMWords.sol";
import {SafeTransferLib} from "src/libraries/SafeTransferLib.sol";
import {IPropAMMDoorFront} from "src/periphery/door/IPropAMMDoorFront.sol";
import {PropAMMDoorScreen as S} from "src/periphery/door/PropAMMDoorScreen.sol";
import {PropAMMClock} from "src/propamm/libraries/PropAMMClock.sol";
/// @notice What a listing door reads of its factory while it is created.
interface IPropAMMListingDoors {
/// @notice The door being created: its front and its listing (zero outside a creation).
function parameters() external view returns (address front, uint24 listing);
}
/// @notice One listing's own IPropAMM door, for routers that pick a listing themselves: every entry forwards to the
/// front's named door (`quoteFrom` and `quoteFillableFrom` with the call's own tip and this door as taker,
/// `swapSender` with the listing, or its paid entry, `swapExactInPaid`, where the input reaches the pool
/// directly), so any listing is reachable, a credit route included, and its quote is the
/// front's: its fill at the taker's gas price. Created by `PropAMMListingDoors` at the CREATE2 address of the
/// listing id.
/// @dev The door's rules:
/// - A credit route's quote: on a listing whose pool's credit mode sends the fill to the pool's own swap, the
/// quote is the pool's own preview (`IFLAMM.previewSwap`), so it equals the fill as far as the pool's preview
/// equals its swap, which settles what the preview projects (venue accrual, crossings, cover releases).
/// - It has no storage: its front, listing and pair are immutables, and it holds a standing grant of both tokens
/// to the front, set at its creation (`approveFront` renews it), since the front's `swapSender` pulls from it
/// on a listing the front names no pool for.
/// - Clock: `isActive` screens on the front's word bounds and its clock (mode, anchor and age slack) as they
/// stood when the door was created: a copy, never read again. A front upgrade that changes any of them leaves
/// every door opened before it screening on the old ones. Its quotes and fills are the front's and stay exact,
/// but its `isActive` can then answer otherwise than the front fills (a door that kept the seal clock where the
/// front moved to an exact one reads a word out up to the old age slack early). The door cannot be replaced
/// where it stands: its CREATE2 address is its factory's and its listing's, and the factory answers the door
/// that stands. So a front upgrade that changes the clock needs a new factory and new doors, opened once the
/// upgrade has run, as it needs a new router door and a new credit door, which copy the clock the same way.
/// - Custody: the door holds tokens only inside a swap. Where the front names the listing's pool (`payPoolOf`:
/// a listing with no credit mode) the input reaches that pool before the front's paid entry fills it, whose
/// pool's own input check proves the payment, in the same call: the push entry pays on what the caller sent
/// it, the pull entry takes it from the caller straight to the pool, and the paid entry (`swapPaid`) fills
/// what its caller paid the pool itself. On any other listing the push entry spends what the caller sent it,
/// and the pull entry takes it into the door, which the front pulls it from at once; the paid entry refuses.
/// Tokens left in the door outside a swap are anyone's to swap.
contract PropAMMListingDoor is IPropAMM, IPropAMMFillable {
/// @notice The front this door forwards to.
address public immutable FRONT;
/// @notice The one listing it fills.
uint24 public immutable LISTING;
/// @notice The lower address of the listing's pair.
address public immutable TOKEN0;
/// @notice The higher address of the listing's pair.
address public immutable TOKEN1;
/// @notice The pair's base token.
address public immutable BASE;
/// @dev Whether the front is a builder build rather than a storage build.
bool internal immutable REGISTRY;
/// @dev The front's word bounds, ms, and its clock (mode, anchor block and milliseconds, age slack), copied from
/// the front at creation: `isActive` screens as the front did then, and a front upgrade that changes any of
/// them needs new doors from a new factory (`Clock`).
uint256 internal immutable MAX_TTL_MS;
uint256 internal immutable MAX_LEAD_MS;
uint256 internal immutable CLOCK_MODE;
uint256 internal immutable CLOCK_BLOCK;
uint256 internal immutable CLOCK_MS;
uint256 internal immutable AGE_SLACK_MS;
/// @notice The tokens are not the listing's pair.
error UnsupportedPair();
/// @notice At creation, a listing the front does not know.
error UnknownListing();
/// @notice The listing refuses the amount for the block's state.
error NoFill();
/// @notice Reads the front and the listing from the creating factory (`IPropAMMListingDoors.parameters`), then the
/// pair and the front's rules, and sets both standing grants.
constructor() {
(address front, uint24 listing) = IPropAMMListingDoors(msg.sender).parameters();
IPropAMMDoorFront f = IPropAMMDoorFront(front);
// the listing's pair and its base, read once: a listing never changes pair
IPropAMMDoorFront.DoorView memory v = f.doorView(listing);
(address t0, address t1) = (v.token0, v.token1);
if (v.pool == address(0) || t0 == address(0)) revert UnknownListing();
FRONT = front;
LISTING = listing;
TOKEN0 = t0;
TOKEN1 = t1;
BASE = v.pairWord & W.PAIR_BASE_IS_T0 != 0 ? t0 : t1;
REGISTRY = f.LANE_KIND() != 1;
PropAMMClock.Timing memory c = f.clock();
MAX_TTL_MS = c.maxTtlMs;
MAX_LEAD_MS = c.maxLeadMs;
CLOCK_MODE = c.clockMode;
CLOCK_BLOCK = c.clockBlock;
CLOCK_MS = c.clockMs;
AGE_SLACK_MS = c.ageSlackMs;
SafeTransferLib.safeApprove(t0, front, type(uint256).max);
SafeTransferLib.safeApprove(t1, front, type(uint256).max);
}
/// @inheritdoc IPropAMM
/// @dev The listing's `quoteFrom`, reverting where the listing does not fill `amountIn` now, as IPropAMM asks of an
/// inactive venue: `NoFill` for a refusal of the block's state, the swap's own revert for the caller's,
/// `UnsupportedPair` for another pair.
function quote(address tokenIn, address tokenOut, uint256 amountIn) external view returns (uint256 amountOut) {
_pair(tokenIn, tokenOut);
amountOut = IPropAMMDoorFront(FRONT).quoteFrom(tokenIn, tokenOut, amountIn, LISTING, _tip(), address(this));
if (amountOut == 0) revert NoFill();
}
/// @inheritdoc IPropAMM
/// @dev Push payment: the caller sent `amountIn` to this door first. On a listing the front names a pool for
/// (`payPoolOf`), the door transfers `amountIn` on to that pool and the front's paid entry
/// (`swapExactInPaid`) fills it; on any other listing the front's `swapSender` pulls it from the door under the
/// standing grant. The two fill at the same output and refuse alike, a fee-on-transfer input included: the
/// door, sent `amountIn` less the fee, holds too little for either move, and where it holds enough, either
/// move reaches the pool short of the fee, which the pool's input check refuses unless its untracked balance
/// covers the fee. The paid entry refuses a credit mode set after the view (`NotEnoughDepth`), as `swapFrom`'s
/// does.
function swap(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minAmountOut,
address recipient,
uint256 deadline
) external returns (uint256 amountOut) {
_pair(tokenIn, tokenOut);
address pool = IPropAMMDoorFront(FRONT).payPoolOf(LISTING);
if (pool == address(0)) return _swap(tokenIn, tokenOut, amountIn, minAmountOut, recipient, deadline);
SafeTransferLib.safeTransfer(tokenIn, pool, amountIn);
return _paid(tokenIn, tokenOut, amountIn, minAmountOut, recipient, deadline);
}
/// @notice The paid entry: the caller sent `amountIn` of `tokenIn` to the listing's pool (the front's
/// `payPoolOf(LISTING)`) earlier in the same transaction, and the front's paid entry (`swapExactInPaid`)
/// fills it, with `Swapped` as on the other entries (the door's on a storage build, the listing's desk's
/// on a builder build). The door moves no token and needs no grant of the
/// caller's, and on a listing the front names a pool for it pays what `swapFrom` pays for the same state.
/// @dev The front's paid entry's rules hold unchanged: the pool's own input check proves the payment (its balance
/// of `tokenIn` at least its tracked custody plus `amountIn`, else `CustodyMismatch`), so any untracked
/// `tokenIn` the pool already holds (a donation, an overpayment, a payment an earlier transaction stranded)
/// counts toward it, and the next paid fill there, through this entry or the front's own, takes it at the
/// maker's price: a payer sends and calls in one transaction, with no call between. `Swapped` names the caller
/// as its sender (on a builder build the desk's names this door, the front's caller), which the check does
/// not prove paid. A listing with a credit mode refuses
/// (`NotEnoughDepth`), the front naming no pool for it; a fee-on-transfer input fills only where the pool's
/// untracked balance covers the fee, which the fill spends; `UnsupportedPair` for another pair.
/// A caller pays and calls in one frame that reverts together, names the exact amount paid, and reads
/// `payPoolOf(LISTING)` in the same transaction. The entry gives no refund: a payment left at the pool, short
/// of the call or over the amount named, is the next caller's to fill.
function swapPaid(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minAmountOut,
address recipient,
uint256 deadline
) external returns (uint256 amountOut) {
_pair(tokenIn, tokenOut);
return _paid(tokenIn, tokenOut, amountIn, minAmountOut, recipient, deadline);
}
/// @notice The allowance entry (`amountIn` the third word): pulls `amountIn` from the caller, then fills as `swap`.
/// On a listing the front names a pool for (`payPoolOf`), the input moves once, from the caller to that
/// pool, and the front's paid entry (`swapExactInPaid`) fills it: the two entries plan alike and fill at
/// the same output, but for a fee-on-transfer input, which the pull through this door refuses and the paid
/// entry fills where the pool's untracked balance covers the fee, spending it, as every paid entry does.
/// The paid entry refuses a credit mode set after the view (`NotEnoughDepth`), which only the listing's
/// operator can set, and within this call only from inside the input token's own transfer.
function swapFrom(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minAmountOut,
address recipient,
uint256 deadline
) external returns (uint256 amountOut) {
_pair(tokenIn, tokenOut);
address pool = IPropAMMDoorFront(FRONT).payPoolOf(LISTING);
if (pool == address(0)) {
SafeTransferLib.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);
return _swap(tokenIn, tokenOut, amountIn, minAmountOut, recipient, deadline);
}
SafeTransferLib.safeTransferFrom(tokenIn, msg.sender, pool, amountIn);
return _paid(tokenIn, tokenOut, amountIn, minAmountOut, recipient, deadline);
}
/// @inheritdoc IPropAMM
/// @dev Whether the listing passes the door's screen now on that side (`PropAMMDoorScreen.screen`: live, its word,
/// depth and ticket standing, fresh by its build family's rule on the front's clock), for its own pair: the
/// state every fill needs. A listing holds no sizes, so an amount it cannot fill (past its ladder, under its
/// minimum) still reverts its `quote`.
function isActive(address tokenIn, address tokenOut) external view returns (bool) {
if (!_trades(tokenIn, tokenOut)) return false;
bool bid = tokenIn == BASE;
S.Read memory r = S.read(IPropAMMDoorFront(FRONT).doorView(LISTING, bid), bid);
(uint256 nowMs, uint256 ageNow) = S.clock(CLOCK_MODE, CLOCK_BLOCK, CLOCK_MS, AGE_SLACK_MS);
return S.screen(r, S.Rules(REGISTRY, 0, MAX_TTL_MS, MAX_LEAD_MS, 0, nowMs, ageNow)) == S.LIVE;
}
/// @inheritdoc IPropAMM
function getPairs() external view returns (TokenPair[] memory pairs) {
pairs = new TokenPair[](1);
pairs[0] = TokenPair(TOKEN0, TOKEN1);
}
/// @inheritdoc IPropAMMFillable
/// @dev The listing's `quoteFillableFrom` at the call's own tip, this door the taker: the prefix of `amountIn` the
/// listing fills now, and exactly what a swap of that prefix through this door pays. Every refusal reverts
/// with the front's error, the block's state's included, as the front's own answer does; `UnsupportedPair`
/// for another pair.
function quoteFillable(address tokenIn, address tokenOut, uint256 amountIn)
external
view
returns (uint256 fillableAmountIn, uint256 amountOut)
{
_pair(tokenIn, tokenOut);
return IPropAMMDoorFront(FRONT).quoteFillableFrom(tokenIn, tokenOut, amountIn, LISTING, _tip(), address(this));
}
/// @notice ERC-165: ERC-165 itself, IPropAMM and IPropAMMFillable.
function supportsInterface(bytes4 id) external pure returns (bool) {
return id == 0x01ffc9a7 || id == 0xf723370b || id == 0x7ae84825;
}
/// @notice Renews both standing grants to the front, from zero.
function approveFront() external {
SafeTransferLib.safeApprove(TOKEN0, FRONT, 0);
SafeTransferLib.safeApprove(TOKEN0, FRONT, type(uint256).max);
SafeTransferLib.safeApprove(TOKEN1, FRONT, 0);
SafeTransferLib.safeApprove(TOKEN1, FRONT, type(uint256).max);
}
/// @dev Whether the two tokens are the listing's pair, either way round.
function _trades(address tokenIn, address tokenOut) internal view returns (bool) {
return (tokenIn == TOKEN0 && tokenOut == TOKEN1) || (tokenIn == TOKEN1 && tokenOut == TOKEN0);
}
/// @dev {_trades}, or `UnsupportedPair`.
function _pair(address tokenIn, address tokenOut) internal view {
if (!_trades(tokenIn, tokenOut)) revert UnsupportedPair();
}
/// @dev The call's own tip, wei a gas above the base fee.
function _tip() internal view returns (uint256) {
return tx.gasprice > block.basefee ? tx.gasprice - block.basefee : 0;
}
/// @dev The listing's named fill, and on a storage build its `Swapped`: on a builder build the front has the
/// listing's desk log it, this door its sender, and the door logs none ({_swapped}).
function _swap(address tIn, address tOut, uint256 x, uint256 minOut, address to, uint256 deadline)
internal
returns (uint256 out)
{
out = IPropAMMDoorFront(FRONT).swapSender(tIn, tOut, x, minOut, to, deadline, LISTING);
_swapped(tIn, tOut, x, out, to);
}
/// @dev The listing's paid fill, its input already at the pool, and its `Swapped` as the named fill's.
function _paid(address tIn, address tOut, uint256 x, uint256 minOut, address to, uint256 deadline)
internal
returns (uint256 out)
{
out = IPropAMMDoorFront(FRONT).swapExactInPaid(tIn, tOut, x, minOut, to, deadline, LISTING);
_swapped(tIn, tOut, x, out, to);
}
/// @dev A fill's `Swapped`, on a storage build alone (`REGISTRY`, the front's build family, read at creation):
/// a builder build's front has the listing's desk contract log the fill's one `Swapped`, so the builder
/// that places the desk's update finds it at the desk, and a second one here would count the fill twice.
function _swapped(address tIn, address tOut, uint256 x, uint256 out, address to) internal {
if (!REGISTRY) emit Swapped(msg.sender, tIn, tOut, x, out, to);
}
}
/// @notice Creates each listing's door, once, at the CREATE2 address of the listing id under one creation code, so
/// anyone derives a listing's door from this factory's address and the id alone (`doorOf`). Anyone may create
/// one; it is ownerless and holds no state but the transient parameters of the door being created.
contract PropAMMListingDoors is IPropAMMListingDoors {
/// @notice The front every door it creates forwards to.
address public immutable FRONT;
/// @notice The doors' creation code hash.
bytes32 public immutable DOOR_CODEHASH;
/// @dev The transient slot of the door being created: its listing, and bit 24 set so a listing of id 0 reads too.
uint256 internal constant PARAM_SLOT = 0x1e9c2b1f6f2c0b7b9d6f0c4d0f4b8a3c2d5e7f9a0b1c3d5e7f9a1b3c5d7e9f00;
/// @notice `listing`'s door created at `door`.
event ListingDoorOpened(uint24 indexed listing, address door);
/// @param front The front every door forwards to.
constructor(address front) {
FRONT = front;
DOOR_CODEHASH = keccak256(type(PropAMMListingDoor).creationCode);
}
/// @notice The door of `listing`, created where it does not exist yet (its listing must exist on the front).
function open(uint24 listing) external returns (address door) {
door = doorOf(listing);
if (door.code.length != 0) return door;
uint256 slot = PARAM_SLOT;
assembly ("memory-safe") {
tstore(slot, or(listing, shl(24, 1)))
}
door = address(new PropAMMListingDoor{salt: bytes32(uint256(listing))}());
assembly ("memory-safe") {
tstore(slot, 0)
}
emit ListingDoorOpened(listing, door);
}
/// @notice `listing`'s door address, created or not.
function doorOf(uint24 listing) public view returns (address) {
return address(
uint160(
uint256(
keccak256(abi.encodePacked(bytes1(0xff), address(this), bytes32(uint256(listing)), DOOR_CODEHASH))
)
)
);
}
/// @notice The door being created: this front and its listing (zero outside `open`).
function parameters() external view returns (address front, uint24 listing) {
uint256 slot = PARAM_SLOT;
uint256 v;
assembly ("memory-safe") {
v := tload(slot)
}
if (v != 0) (front, listing) = (FRONT, uint24(v));
}
}
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);
}
}
}
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/SafeTransferLib.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The token calls of the pool, the Router, the venue kinds, the PropAMM contracts and the periphery:
/// OpenZeppelin 4.8's `SafeERC20.safeTransfer`, `safeTransferFrom` and `safeApprove`, with its calls, verdicts
/// and revert data, built in scratch memory. The pool and the Router both import it, so the Router compiles no
/// pool source and no pool edit reaches its token calls.
/// @dev Scratch memory is the memory at the free-memory pointer, which no function here moves: nothing it writes
/// outlives the call.
library SafeTransferLib {
/// @notice OpenZeppelin 4.8's `SafeERC20.safeTransfer`: the same call, verdict and revert data (see
/// {_callOptionalReturn}), built in scratch memory.
function safeTransfer(address token, address to, uint256 amount) internal {
uint256 m;
assembly ("memory-safe") {
m := mload(0x40)
mstore(m, shl(224, 0xa9059cbb)) // transfer(address,uint256)
mstore(add(m, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(m, 36), amount)
}
_callOptionalReturn(token, m, 68);
}
/// @notice OpenZeppelin 4.8's `SafeERC20.safeTransferFrom`: the same call, verdict and revert data (see
/// {_callOptionalReturn}), built in scratch memory.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
uint256 m;
assembly ("memory-safe") {
m := mload(0x40)
mstore(m, shl(224, 0x23b872dd)) // transferFrom(address,address,uint256)
mstore(add(m, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(m, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(m, 68), amount)
}
_callOptionalReturn(token, m, 100);
}
/// @dev The `len` bytes of call data at `m` sent to `token` as OpenZeppelin 4.8's `SafeERC20._callOptionalReturn`
/// sends them (`Address.functionCall`: all gas, no value), with its verdicts: a failed call bubbles its revert
/// data, or reverts "SafeERC20: low-level call failed" with none; an empty success needs code at `token`
/// ("Address: call to non-contract"); returned data must open with a bool (else an empty revert, as
/// `abi.decode` gives) that is true ("SafeERC20: ERC20 operation did not succeed"). A success copies no return
/// data but that first word.
function _callOptionalReturn(address token, uint256 m, uint256 len) private {
assembly ("memory-safe") {
// `Error(string)` with the `n`-byte message `w0 ++ w1`, at `p`
function fail(p, n, w0, w1) {
mstore(p, shl(224, 0x08c379a0))
mstore(add(p, 4), 0x20)
mstore(add(p, 36), n)
mstore(add(p, 68), w0)
mstore(add(p, 100), w1)
revert(p, add(68, mul(0x20, div(add(n, 31), 32))))
}
let ok := call(gas(), token, 0, m, len, 0, 0)
let rds := returndatasize()
if iszero(ok) {
if rds {
returndatacopy(m, 0, rds)
revert(m, rds)
}
fail(m, 32, "SafeERC20: low-level call failed", 0)
}
switch rds
case 0 {
if iszero(extcodesize(token)) { fail(m, 29, "Address: call to non-contract", 0) }
}
default {
if lt(rds, 32) { revert(0, 0) }
returndatacopy(m, 0, 32)
let v := mload(m)
if gt(v, 1) { revert(0, 0) }
if iszero(v) { fail(m, 42, "SafeERC20: ERC20 operation did n", "ot succeed") }
}
}
}
/// @notice OpenZeppelin 4.8's `SafeERC20.safeApprove` without its read of the standing allowance: the same call,
/// verdict and revert data (see {_callOptionalReturn}), built in scratch memory. Its callers never grant
/// over a standing grant: a leg's grant is pulled in full or cleared within the call, and a door's standing
/// grant to its front is made once, from zero, each renewal clearing it first. (The Aave kind's standing
/// grant takes its own route, `AaveV3ReadsLib`, once per token, from zero.) A token that refuses a grant
/// over a nonzero one (Ethereum's USDT; BNB Chain's does not) needs that: every grant there is made from
/// zero.
function safeApprove(address token, address spender, uint256 amount) internal {
uint256 m;
assembly ("memory-safe") {
m := mload(0x40)
mstore(m, shl(224, 0x095ea7b3)) // approve(address,uint256)
mstore(add(m, 4), and(spender, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(m, 36), amount)
}
_callOptionalReturn(token, m, 68);
}
}
src/periphery/door/IPropAMMDoorFront.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 The front's entries the router door and the listing doors call, and nothing else: one cold read of a listing
/// (`doorView`, the landing part's), the named door (`quoteFrom` and `quoteFillableFrom` with a tip and a
/// taker, `swapSender` and `swapExactInPaid` with a listing, and `payPoolOf`, the pool a paid fill pays), the
/// build's kind, word bounds and clock.
interface IPropAMMDoorFront {
/// @notice A listing as a router door reads it, field for field the front's own `DoorView`: its pair (word and
/// tokens), its place in its pool, its status flags (P0 bits 192-199: [0] live | [1] reserved, set by
/// nothing (`PropAMMWords.F_PAUSED`) | [2] frozen | [3] maker paused | [7] own asset module) and key epoch,
/// its desk binding (desk, word index, scopes: [0] ANY | [1-2] the fence kind | [3-4] the carry life), its
/// price fences (ppm), taker tip cap (as stored: `PropAMMWords.tipWei` reads it), confidence multiplier
/// (tenths) and credit mode, each side's last fill (on the front's clock, ms: its board
/// word's time, the go-live before the side's first fill), its desk's ticket and standing word as a fill
/// reads them (zeros where unbound or where the cell does not answer; the word's bits 168-199 its write
/// stamp: the landing block on a builder build, that block's unix second on a storage build), and its four
/// depth words (bid 0, bid 1, ask 0, ask 1; a word 1 only where its word 0 marks it).
struct DoorView {
uint256 pairWord;
address token0;
address token1;
address pool;
uint8 baseIndex;
uint8 quoteIndex;
uint8 flags;
uint32 keyEpoch;
uint32 desk;
uint8 wordIndex;
uint8 scopes;
uint32 fenceBidPpm;
uint32 fenceAskPpm;
uint16 tipCap;
uint8 confMul;
uint8 creditMode;
uint48 bidFillMs;
uint48 askFillMs;
uint256 ticket;
uint256 word;
uint256[4] depth;
}
/// @notice `listing` read cold; zeros for a listing never reserved. Takes no lock and never reverts.
function doorView(uint24 listing) external view returns (DoorView memory);
/// @notice `doorView` for a screen of one side (`bid`: the taker sells the base): the tokens, the last fills and
/// the other side's depth left zero.
function doorView(uint24 listing, bool bid) external view returns (DoorView memory);
/// @notice Exactly what `swapSender` with `listing`, called by `taker` in a transaction tipping `tip` wei a gas
/// above the base fee, pays now: zero for a refusal of the block's state, the swap's own revert for the
/// caller's.
/// @param amountIn The input, in `tokenIn` base units.
/// @param tip The taker's tip, wei per gas above the base fee.
/// @param taker The caller the swap will have.
/// @return The output, in `tokenOut` base units.
function quoteFrom(address tokenIn, address tokenOut, uint256 amountIn, uint24 listing, uint256 tip, address taker)
external
view
returns (uint256);
/// @notice How much of `amountIn` `listing` fills now through `swapSender` called by `taker` in a transaction
/// tipping `tip`, and exactly what that fill pays: the front's own prefix. Every refusal reverts with its
/// error, the block's state's included.
/// @param amountIn The input asked for, in `tokenIn` base units.
/// @param tip The taker's tip, wei per gas above the base fee.
/// @param taker The caller the swap will have.
/// @return fillableAmountIn The prefix of `amountIn` the listing fills, in `tokenIn` base units.
/// @return amountOut What that prefix pays, in `tokenOut` base units.
function quoteFillableFrom(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint24 listing,
uint256 tip,
address taker
) external view returns (uint256 fillableAmountIn, uint256 amountOut);
/// @notice The named fill of `listing` with its input already paid: `amountIn` sent to the listing's pool earlier
/// in the transaction, which the pool's input check proves. A listing with a credit mode refuses
/// (`NotEnoughDepth`).
/// @param amountIn The input already paid, in `tokenIn` base units.
/// @param minAmountOut The least output, in `tokenOut` base units.
/// @param deadline Unix seconds on every build, inclusive.
/// @return The output, in `tokenOut` base units.
function swapExactInPaid(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minAmountOut,
address recipient,
uint256 deadline,
uint24 listing
) external returns (uint256);
/// @notice The pool a door pays a fill's input to before `swapExactInPaid`: `listing`'s pool where the listing has
/// no credit mode, so the paid entry takes its fills; zero for any other listing and for one never
/// reserved. A plain read of the listing's record, which takes no lock and never reverts. The paid entry
/// refuses a credit mode set after the answer, which only the listing's operator can set, and within a
/// door's call only from inside the input token's own transfer. A fee-on-transfer
/// input is refused on the paid entry unless the pool's untracked balance covers the fee, which the fill
/// then spends.
function payPoolOf(uint24 listing) external view returns (address pool);
/// @notice The named fill of `listing`, pulling `amountIn` from the caller.
/// @param amountIn The input pulled, in `tokenIn` base units.
/// @param minAmountOut The least output, in `tokenOut` base units.
/// @param deadline Unix seconds on every build, inclusive.
/// @return The output, in `tokenOut` base units.
function swapSender(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minAmountOut,
address recipient,
uint256 deadline,
uint24 listing
) external returns (uint256);
/// @notice The build's kind: 0 Ethereum's builder build, 1 a storage build, 2 BNB Chain's builder build.
function LANE_KIND() external view returns (uint256);
/// @notice The build's maker-time windows and clock, in one answer: the lead a maker time may take on the clock,
/// a pool word's life cap, the pull lead and the age slack the age clock adds to a seal reading, ms, then
/// the clock's mode, and the block and its milliseconds the clock counts from in mode 2.
function clock() external view returns (PropAMMClock.Timing memory);
}
src/periphery/door/PropAMMDoorScreen.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {IPropAMMDoorFront} from "src/periphery/door/IPropAMMDoorFront.sol";
import {PropAMMWords as W} from "src/propamm/libraries/PropAMMWords.sol";
import {PropAMMClock} from "src/propamm/libraries/PropAMMClock.sol";
import {PPM, CAP_128} from "src/libraries/Constants.sol";
/// @notice What a door makes of one listing's `doorView`, pure but for the block's number and time and the front's
/// clock: whether the door takes it at all (its eligibility), whether its word can fill now (its screen), and
/// an upper bound on what it pays for an amount (its bound), each a reading of the front's own rules on the
/// words the front reads, on the front's own clock and age clock (`PropAMMClock`, the front's mode and anchor,
/// its age slack).
/// @dev The screen and the bound:
/// - Screen: a listing is dark where its named fill refuses every amount for the block's state: the listing frozen
/// or maker-paused (the reserved pause bit reads dark too), its desk stopped, its standing word missing, of
/// another kind or desk epoch, unsigned on a WORD or NONE listing (a PRINT listing, and a SESSION one, which
/// fills an unsigned word as a PRINT one while its print is fresh, take it), out of bounds, not fresh by its
/// build family's rule, past its life or ahead of the clock, or its side's depth word expired or of another key
/// epoch.
/// - The build family's rule is the front's `_deskFresh`: on a builder build a word fills in its landing block, or
/// carried one block later on a listing and a word that both take carry, never on a NONE listing; on a storage
/// build a word stands only while it is its ticket's own push's and the listing's taker tip cap is on, for its
/// own life. Either way the front's `maxTtlMs` caps a word's life.
/// - Fading: on a storage build a word or depth that ran out less than the grace ago is fading: it fills nothing,
/// and a claim made then does not go pending against it but notes the size it holds (a claim's note, one a size
/// and side, apart from a dark sighting's), so a desk's refresh gap is no eviction; a claim that finds the
/// size's champion fading 30 to 60 s after that note counts it dark, whoever held the size at the note. Only its
/// lapse, 60 s after it was written, ends that note: no screen, fill, confirm, release or eviction does. So a
/// champion kept fading for good, one of its word and depth always out, holds a size only until the confirm of
/// that claim, which takes a size from a champion fading or dark then and prices a live one, whichever listing
/// of its operator holds the size by then. A word that ran out before the second it was written was never live
/// and is dark at once.
/// - What it leaves out: the screen reads nothing past the listing's words: not an asset module's verdict (the
/// front asks one at every quote of an asset pair), its controls (version, epoch, self-pause, maker nonce) or
/// its price's age. A listing one of them refuses screens live and quotes zero, and a claim against it wins.
/// - Bound: the side's ladder walked from its first rung (no fill memory) at each rung's offset plus the word's
/// skew alone (no drift, age widening or premium), unclamped by any price fence, with no bucket or custody
/// bound. The front's walk starts at its fill memory, adds a discount of at least the skew to every rung and
/// clamps each level to the price fence; rung offsets never fall
/// along a ladder (the post rule), so each unit of input the front fills pays at most what the same unit pays
/// here. An amount past the ladder's whole depth bounds to zero: the front cannot fill it whole either. A tied
/// listing's named fills walk from its print instead, which the word does not bound: its bound is `CAP_128`
/// wherever its ladder takes the amount whole.
library PropAMMDoorScreen {
using W for uint256;
/// @dev A listing's standing for a door, as `status` answers it and `DoorFill` logs it.
uint8 internal constant INELIGIBLE = 0;
uint8 internal constant DARK = 1;
uint8 internal constant FADING = 2;
uint8 internal constant LIVE = 3;
/// @dev The front's bound on an anchor, the word's mantissa times the pair's price unit: at or above it the word is
/// refused where it enters, and the screen reads it dark.
uint256 internal constant PRICE_BOUND = 1 << 200;
/// @dev The front's fixed point on an ask level, and 1e36 x 2^96: its rate is that over its price, rounded down.
uint256 internal constant ASK_SCALE = 1 << 96;
uint256 internal constant ASK_NUMERATOR = 1e36 << 96;
/// @dev The exponents the bound's arithmetic relies on: a pair's price unit (the front's `addPair` writes at most
/// 48), its board units (at most 12 for a base, 16 for a quote) and a depth post's sizes (`postDepth`, at most
/// 30). The front never writes more; the screen holds a listing to them as defence against a front upgrade
/// before its code freezes (`freezeCode`).
uint256 internal constant MAX_UNIT_EXP = 58;
uint256 internal constant MAX_BOARD_EXP = 16;
uint256 internal constant MAX_DEPTH_EXP = 30;
/// @dev `doorView`'s status flags: live, then the three that darken a listing: reserved, frozen, maker-paused.
uint256 internal constant F_LIVE = 1;
uint256 internal constant F_DARK = 14;
/// @dev The gas a door gives one `quoteFrom` of a listing: at least 5/4 of the heaviest quote of a listing on a
/// shipped source (the kept-print source, the price store's reader, a storage build's stored price lane),
/// every account cold, which a test pins. The front reads a PRINT listing's source inside its quote under its
/// own, larger cap (`SOURCE_GAS`), so without this one a listing whose source burns that cap would cost every
/// pick that prices it the whole of it. A gas repricing that lifts an honest quote near this cap needs a new
/// door.
uint256 internal constant QUOTE_GAS = 150_000;
/// @dev The gas a quote of an asset-module pair's listing gets on top: the front's cap on the module's answer
/// (`PropAMMAsset.GAS`), which the pair's module may use whole.
uint256 internal constant QUOTE_ASSET_GAS = 100_000;
/// @dev What a call costs its caller before the callee runs (a cold account, the call's own memory), rounded up.
uint256 internal constant CALL_OVERHEAD = 3_000;
/// @notice The fields of a `doorView` a door reads, one side's depth words picked.
struct Read {
uint256 pair; // the pair word
address pool; // the listing's pool, where a paid fill's input goes
uint256 flags; // P0 bits 192-199 ({IPropAMMDoorFront.DoorView})
uint256 keyEpoch; // the listing's key epoch; a depth word carries its low 8 bits
uint256 desk; // the desk it is bound to, 0 unbound
uint256 scopes; // [0] ANY | [1-2] the fence kind | [3-4] the carry life, blocks
uint256 tipCap; // the taker tip cap as stored (`PropAMMWords.tipWei`), 0 off
uint256 confMul; // the listing's confidence multiplier, tenths
uint256 credit; // the credit mode (`PropAMMWords.CREDIT_*`)
uint256 fillMs; // the side's last fill, on the front's clock, ms; zero on a one-side `doorView`
uint256 ticket; // the desk's ticket, zero where unbound or where the cell does not answer
uint256 word; // the desk's standing word for the listing, as a fill reads it
uint256 d0; // the side's depth words
uint256 d1; // word 1, zero where word 0 does not mark it
}
/// @notice A build's reading rules: its family, the door's reference tip, the front's word bounds, the storage
/// grace, and the front's clock and age clock now, ms (`clock`).
struct Rules {
bool registry;
uint256 tipRef;
uint256 maxTtlMs;
uint256 maxLeadMs;
uint256 graceMs;
uint256 nowMs;
uint256 ageNow;
}
/// @notice The front's clock and age clock now, as its `_clock` reads them: the clock of `mode` from the anchor
/// (`block0`, `ms0`), and the age clock `ageSlackMs` later on a seal reading.
function clock(uint256 mode, uint256 block0, uint256 ms0, uint256 ageSlackMs)
internal
view
returns (uint256 nowMs, uint256 ageNow)
{
bool exact;
(nowMs, exact) = PropAMMClock.read(mode, block0, ms0);
ageNow = exact ? nowMs : nowMs + ageSlackMs;
}
/// @notice The front's one starvation rule (`PropAMMShared._starved`) on a door's own call into it: a call begun
/// with `g` gas left that failed with `left` after it was starved by the caller's limit where `left` is
/// under g / 8, and is its listing's refusal otherwise, a front `GasShort` among them.
function starved(uint256 g, uint256 left) internal pure returns (bool) {
return left < g / 8;
}
/// @notice The gas one `quoteFrom` of a listing gets: `QUOTE_GAS`, and the module's on top where its pair is an
/// asset-module pair (`asset`).
function quoteGas(bool asset) internal pure returns (uint256) {
return asset ? QUOTE_GAS + QUOTE_ASSET_GAS : QUOTE_GAS;
}
/// @notice Whether a call begun with `g` gas left gets a cap of `cap` whole: all but the 1/64 a call keeps back
/// covers the cap and the call's own overhead. A capped call that fails so is its listing's refusal,
/// whatever it left; one given less is held to `starved`.
function capped(uint256 g, uint256 cap) internal pure returns (bool) {
return g - g / 64 >= cap + CALL_OVERHEAD;
}
/// @notice One side (`bid`: the taker sells the base) of a `doorView`.
function read(IPropAMMDoorFront.DoorView memory v, bool bid) internal pure returns (Read memory r) {
r.pair = v.pairWord;
r.pool = v.pool;
r.flags = v.flags;
r.keyEpoch = v.keyEpoch;
r.desk = v.desk;
r.scopes = v.scopes;
r.tipCap = v.tipCap;
r.confMul = v.confMul;
r.credit = v.creditMode;
r.fillMs = bid ? v.bidFillMs : v.askFillMs;
r.ticket = v.ticket;
r.word = v.word;
(r.d0, r.d1) = bid ? (v.depth[0], v.depth[1]) : (v.depth[2], v.depth[3]);
}
/// @notice Whether the door takes the listing: live, bound to a desk, its standing word not reference only, credit
/// mode 0, and a taker tip cap of none or at least `tipRef`, so its quote is its fill for any taker at any
/// tip it admits.
function eligible(Read memory r, uint256 tipRef) internal pure returns (bool) {
if (r.flags & F_LIVE == 0 || r.desk == 0 || r.credit != 0 || r.word.wRefOnly()) {
return false;
}
return r.tipCap == 0 || W.tipWei(r.tipCap) >= tipRef;
}
/// @notice The listing's standing for the door: `INELIGIBLE`, or its screen (`DARK`, `FADING`, `LIVE`).
function status(Read memory r, Rules memory rules) internal view returns (uint8) {
if (!eligible(r, rules.tipRef)) return INELIGIBLE;
return screen(r, rules);
}
/// @notice The screen alone, for any listing: `DARK`, `FADING` (a storage build's recent run-out) or `LIVE`.
function screen(Read memory r, Rules memory rules) internal view returns (uint8) {
unchecked {
uint256 w = r.word;
uint256 t = r.ticket;
uint256 pw = r.pair;
if (r.flags & F_LIVE == 0 || r.flags & F_DARK != 0 || r.desk == 0 || t.tStopped()) return DARK;
uint256 ue = pw.unitExp();
uint256 m = w.mantissa();
// the word as the front prices it (its skews are 16-bit fields, under 1e6 as the front needs them)
if (
w.wKind() != W.KIND_QUOTE || w.wRefOnly() || w.epoch8() != t.tEpoch() & W.M8 || m == 0
|| ue > MAX_UNIT_EXP || m >= PRICE_BOUND / W.pow10(ue)
) return DARK;
uint256 fence = (r.scopes >> 1) & 3;
// the signed-word rule is a WORD or NONE listing's: a SESSION listing fills an unsigned word as a PRINT
// one while its print is fresh, and one whose print is stale screens live and refuses at its quote
if ((fence == W.FENCE_WORD || fence == W.FENCE_NONE) && !w.wSigned()) return DARK;
uint256 life = w.ttl();
if (rules.registry) {
// a word older than its landing block fills only carried: one block later at most, the listing's carry
// life and the word's own both on, the listing fenced to a price
uint256 age = (block.number - w.wStamp()) & W.M32;
if (age != 0 && (age > 1 || (r.scopes >> 3) & 3 == 0 || w.wCarry() == 0 || fence == W.FENCE_NONE)) {
return DARK;
}
} else {
// a word stands while its ticket's push wrote it and the tip cap is on
if (w.wVersion() != t.tVersion() || r.tipCap == 0) return DARK;
}
uint256 d0 = r.d0;
if (
d0.dVersion() != 1 || d0.dEpoch8() != r.keyEpoch & W.M8 || d0.dExp() > MAX_DEPTH_EXP
|| pw.boardExp(true) > MAX_BOARD_EXP || pw.boardExp(false) > MAX_BOARD_EXP
) return DARK;
uint256 ts = w.makerTs();
if (ts > rules.nowMs + rules.maxLeadMs) return DARK;
life *= 1000;
if (life > rules.maxTtlMs) life = rules.maxTtlMs;
// the word's end on the age clock and the depth's, ms: past either the listing fills nothing
uint256 end = ts + life;
uint256 dEnd = d0.dExpires() * 1000;
bool wordOut = rules.ageNow > end;
bool depthOut = block.timestamp >= d0.dExpires();
if (!wordOut && !depthOut) return LIVE;
if (rules.registry) return DARK;
// a storage build: a word that ran out before its write was never live; else dark only once the earlier
// run-out is the grace old
if (wordOut && end < w.wStamp() * 1000) return DARK;
uint256 since = wordOut && (!depthOut || end < dEnd) ? end : dEnd;
return rules.ageNow >= since + rules.graceMs ? DARK : FADING;
}
}
/// @notice An upper bound on what the listing pays for `x` of the side's input (`bid`: the taker sells the base),
/// `CAP_128` where the ladder holds more than the front ever pays or where the listing is tied
/// (`PropAMMWords.tied`: its fills walk from its print, which its word does not bound, so a door prices it
/// first), zero where it cannot take `x` whole. Read only for a listing the screen passed, whose word and
/// depth bounds it checked.
function bound(Read memory r, bool bid, uint256 x) internal pure returns (uint256) {
// Every product below stays under 2^256: the anchor under 2^200 (the screen), a rung's level price under 2^220
// and its rate under 2^216, each step's input at most a rung's height (a 16-bit size times at most 10^46, the
// screen's exponents), and the accumulated output held under 2^249 (it stops at the front's own output cap,
// 2^128 units).
unchecked {
uint256 a = r.word.mantissa() * W.pow10(r.pair.unitExp());
uint256 sk = r.word.skew(bid);
uint256 d0 = r.d0;
uint256 scale = W.pow10(d0.dExp()) * W.pow10(r.pair.boardExp(bid));
uint256 D = bid ? 1e36 : ASK_SCALE;
uint256 L = (CAP_128 + 1) * D - 1;
uint256 n;
uint256 filled;
uint256 prev;
uint256 w1;
for (uint256 j; j < 10; ++j) {
if (j == 3) {
if (!d0.dHasW1()) break;
w1 = r.d1;
// a present word 1 is never zero (its version): one left unread bounds nothing (defence, as the
// rising-rung check below, against a front upgrade before its code freezes)
if (w1 == 0) return CAP_128;
}
uint256 rg = W.rung(d0, w1, j);
uint256 size = rg & W.M16;
if (size == 0) break;
uint256 h = size * scale;
if (h <= prev) break;
uint256 d = (rg >> 16) + sk;
if (d >= PPM) break;
uint256 q;
if (bid) {
q = a * (PPM - d) / PPM;
} else {
uint256 den = PPM - d;
q = ASK_NUMERATOR / ((a * PPM + den - 1) / den);
}
if (q == 0) break;
uint256 t = h - prev;
if (t > x - filled) t = x - filled;
if (t > (L - n) / q) return CAP_128;
n += t * q;
filled += t;
if (filled == x) {
// a tied listing's print is no rung's anchor here: it ranks first
return (r.scopes >> 1) & 15 == W.TIED_SCOPES ? CAP_128 : n / D;
}
prev = h;
}
return 0;
}
}
}
src/propamm/interfaces/IPropAMM.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
/// @notice The surface routers call on a proprietary AMM (selectors `isActive` 0xae131deb, `getPairs` 0x767eb5ef,
/// `quote` 0xb6466384, `swap` 0x9908fc8b; interface id 0xf723370b). Push payment: the caller transfers
/// `amountIn` before `swap`. It names no listing, so the PropAMM front does not serve it: a periphery door
/// does, over the front's named door (`quoteFrom`, and `swapExactInPaid` or `swapSender`). Amounts are in each
/// token's base units.
interface IPropAMM {
/// @notice A pair, `token0 < token1`.
struct TokenPair {
address token0;
address token1;
}
/// @notice Once per settled fill. Its emitter by the front's build: on a storage build the door called emits it
/// as before; on a builder build the filling listing's desk contract emits it once per settled fill,
/// every one (ANY firm quotes bind on no build of this deployment, so no fill is an ANY one), naming the
/// front's caller (behind a door, that door) its `sender`, and no door emits. A direct pool swap logs
/// before the pool pays, and on router and block doors the log precedes the door's payout to the taker (a
/// later revert rolls it back).
event Swapped(
address indexed sender,
address indexed tokenIn,
address indexed tokenOut,
uint256 amountIn,
uint256 amountOut,
address recipient
);
/// @notice Whether the venue serves the side `tokenIn` to `tokenOut` now. True promises no given amount fills:
/// `quote` answers that.
function isActive(address tokenIn, address tokenOut) external view returns (bool);
/// @notice The pairs the venue trades, on either side or both.
function getPairs() external view returns (TokenPair[] memory);
/// @notice What `swap` of `amountIn` pays in this state, at the caller's gas price. Reverts where the venue does
/// not fill `amountIn` now.
/// @param tokenIn The token the venue takes.
/// @param tokenOut The token it pays.
/// @param amountIn The input.
/// @return amountOut The output, rounded down.
function quote(address tokenIn, address tokenOut, uint256 amountIn) external view returns (uint256 amountOut);
/// @notice Sells `amountIn`, which the caller has already transferred to the venue, and pays `recipient`. Reverts
/// where the venue does not fill the whole input, past `deadline`, or under `minAmountOut`.
/// @param tokenIn The token the venue takes.
/// @param tokenOut The token it pays.
/// @param amountIn The input, already sent.
/// @param minAmountOut The least output the caller takes.
/// @param recipient The account paid.
/// @param deadline The last time the swap fills, unix seconds, inclusive.
/// @return amountOut The output paid.
function swap(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minAmountOut,
address recipient,
uint256 deadline
) external returns (uint256 amountOut);
}
/// @notice How much of an order the venue fills now (selector and interface id 0x7ae84825), advertised through
/// ERC-165. The front's own answer is for one listing (`quoteFillableFrom`).
interface IPropAMMFillable {
/// @notice The part of `amountIn` the venue fills whole now, and what `swap` of it pays. Where it fills none a door
/// answers zeros or passes the refusal on as a revert, as that door says.
/// @param tokenIn The token the venue takes.
/// @param tokenOut The token it pays.
/// @param amountIn The input offered.
/// @return fillableAmountIn The input the venue fills, at most `amountIn`.
/// @return amountOut The output for `fillableAmountIn`.
function quoteFillable(address tokenIn, address tokenOut, uint256 amountIn)
external
view
returns (uint256 fillableAmountIn, uint256 amountOut);
}
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/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"
},
"libraries": {
"src/core/mm/MMRouterLib.sol": {
"MMRouterLib": "0x95b386d242c061ab2551a0d294c94dfe3948ef2c"
},
"src/core/flamm/FLAMMLane.sol": {
"FLAMMLane": "0x5d81d4a7cfd40c3dfe9e009212545608be90de37"
},
"src/core/flamm/FLAMMRoute.sol": {
"FLAMMRoute": "0xb1ffeae12c53f876aa0e495e9c00c829f47fb0fe"
},
"src/periphery/FLAMMMaxima.sol": {
"FLAMMMaxima": "0x68546ce65986354c5394e4bc2f28027ef490a91b"
},
"src/core/flamm/FLAMMLawLib.sol": {
"FLAMMLawLib": "0xf55c5807b6fbe5555443fd6ddbbd52079849cf45"
},
"src/core/flamm/FLAMMOpsLib.sol": {
"FLAMMOpsLib": "0x0be7fdb3d611b05df90a61778a644654735ecc47"
},
"src/core/mm/AaveV3ReadsLib.sol": {
"AaveV3ReadsLib": "0xa5db415d1af2158dd0a4a3c9c1eada277472803e"
},
"src/core/flamm/FLAMMFlowLib.sol": {
"FLAMMFlowLib": "0x27957f4ddf818de39a1c9dba0bf273a5994cfb77"
},
"src/core/flamm/FLAMMGateLib.sol": {
"FLAMMGateLib": "0x3a05779218510235badcbddcdd78732a16434368"
},
"src/core/flamm/FLAMMKeptLib.sol": {
"FLAMMKeptLib": "0x70cace9076ac8dd6a691ced2f9aa62a5c360bee4"
},
"src/core/mm/CTokenMarketLib.sol": {
"CTokenMarketLib": "0x60e4ab6b6ba72325c58924ee7753b14b37314010"
},
"src/core/flamm/FLAMMAdmitLib.sol": {
"FLAMMAdmitLib": "0x0b107b1f0c64f3716554ccc83b53e492e51ce950"
},
"src/core/flamm/FLAMMBlindLib.sol": {
"FLAMMBlindLib": "0x634d5a14c42fb5bec82a7aea32bf636a8d298fcd"
},
"src/core/flamm/FLAMMClaimLib.sol": {
"FLAMMClaimLib": "0x5dc3bb30c60390ce9522b7e3ca315dd334aa7e91"
},
"src/core/flamm/FLAMMFenceLib.sol": {
"FLAMMFenceLib": "0x9dbba0cbd9d7883f4eedd1c8e08780fac4798f1a"
},
"src/core/flamm/FLAMMFloatLib.sol": {
"FLAMMFloatLib": "0x6b2b25ebba12e78afea697b9ac6d2167a6518935"
},
"src/core/flamm/FLAMMQuoteLib.sol": {
"FLAMMQuoteLib": "0x99de54a108c64ebe23ac7766901c199a91929869"
},
"src/core/flamm/FLAMMTopUpLib.sol": {
"FLAMMTopUpLib": "0xe4be161081d1c9aa91951ca347cc99da35cfac2e"
},
"src/core/mm/CTokenRewardsLib.sol": {
"CTokenRewardsLib": "0x93ab647215a9f9f1050302a76506afcbc0262861"
},
"src/core/mm/MMRouterAdminLib.sol": {
"MMRouterAdminLib": "0x6abb06b1e9cba80888992d366913bb9b7760ea7e"
},
"src/core/flamm/FLAMMPolicyLib.sol": {
"FLAMMPolicyLib": "0x3858e2202cebcb6f12f36a596260dd2ed8f91f06"
},
"src/core/flamm/FLAMMSettleLib.sol": {
"FLAMMSettleLib": "0x4551cddb1de95f5452f6a0f836e047e01833b301"
},
"src/core/flamm/FLAMMSharedLib.sol": {
"FLAMMSharedLib": "0xb852d9cbdda85cbed7da0885bca2714ba1b71005"
},
"src/periphery/FLAMMExitMaxima.sol": {
"FLAMMExitMaxima": "0x6a6a3ff1e834dbbf07dee472e07d1ca977798659"
},
"src/hooks/everlong/LeverageLib.sol": {
"LeverageLib": "0x80396f9f894cc3060dfaa7468c4f576e8b16d055"
},
"src/core/flamm/FLAMMMaintainLib.sol": {
"FLAMMMaintainLib": "0xaa5434e13eb54f37c577229efc981cceceb56417"
},
"src/core/flamm/FLAMMPairQuoteLib.sol": {
"FLAMMPairQuoteLib": "0x3bc57bc05cc9dd1fe18106add8ffc060882055dd"
},
"src/hooks/everlong/EverlongOpsLib.sol": {
"EverlongOpsLib": "0xf6d56f4ed6a7c441fd96c53a327026bac19dfeef"
}
},
"optimizer": {
"runs": 100,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.