Verified contractPartialMIT
VaultLib
Address0x8e75a868c17c1e101a26837a2abc7ee6e185b69c
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,475,515
- Creation transaction
- 0xfe50da728b…324fbb6c19
- Libraries
- src/ScanLib.sol:ScanLib0x5d42…4a9e8a
5 files
- src/VaultLib.solmain56.1 KB
- lib/solady/src/utils/FixedPointMathLib.sol55.69 KB
- src/KeeperPolicy.sol2.39 KB
- src/ScanLib.sol4.55 KB
- src/interfaces/External.sol7.73 KB
src/VaultLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {FixedPointMathLib as M} from "solady/utils/FixedPointMathLib.sol";
import {IKeeperPolicy} from "./KeeperPolicy.sol";
import {ScanLib} from "./ScanLib.sol";
import {
IFWAV2,
IFWAView,
IFloorOracle,
IShapePacks,
IShapes,
LISTING_ACTIVE,
LISTING_ALLOCATED,
LISTING_SETTLED,
LISTING_WITHDRAWN
} from "./interfaces/External.sol";
/// @notice What the shared strategy reads from the account it runs in (PackVault or PackManager):
/// ETH it may spend on keeper pay (`freeEth`) and on new exposure (`idleEth`). Each
/// account defines both from its own liabilities; the strategy never sees them otherwise.
interface IAccount {
function freeEth() external view returns (uint256);
function idleEth() external view returns (uint256);
}
/// @notice PackVault's share-price reads, used only for its distribution checkpoint tail.
interface ISyncVault is IAccount {
function accountedNav(uint256 witnessId) external view returns (uint256);
function totalShares() external view returns (uint256);
function highWaterMark() external view returns (uint256);
}
/// @notice Shared strategy core, linked into PackVault and PackManager (with StrategyLib and
/// ScanLib). Runs by DELEGATECALL in the calling account's context, so that account is the
/// FWA depositor and owns every asset; the library holds no state and reads only the
/// storage pointers it is passed. Split into three libraries only for EIP-170 size.
library VaultLib {
uint256 internal constant BPS = 10_000;
uint256 internal constant DEAD_SHARES = 1e15;
uint256 internal constant MIN_DISTRIBUTION = 0.01 ether;
/// @notice PackVault's governed parameters (moved here so library code can read them by
/// storage pointer; EIP-170 size).
struct Params {
uint16 minEdgeBps; // require k >= 1 + minEdge
uint16 bufferBps; // list at cap x (1 - buffer), so a small ask cut does not trigger kicks
uint16 distributionBps; // share of new gains above the high-water mark paid out
uint16 payMarkupBps; // envelope markup on the quoted gas of routine work (V1 pays none)
uint16 keeperShareBps; // optional calls are paid only if pay <= this share of value realized
uint16 allocatedBoundBps; // checkpoint skips when Allocated value exceeds this share of NAV
uint64 packUnitsMask; // bit u set: packs of u x 0.01 ETH may be built and listed
uint64 gasCeiling; // wei per gas, routine work
uint64 essentialCeiling; // wei per gas, redemption and wind-down work (essential budget)
uint64 maxTip; // reimbursed price is at most basefee + this
uint64 workFee; // flat wei per unit of work done: position listed, resolved,
// unlisted, item liquidated, or a checkpoint that priced flows
uint64 routineCap; // keeper budget for strategy work: capacity (wei) and refill per day
uint64 routineRate;
uint64 essentialCap; // keeper budget for redemption and wind-down work
uint64 essentialRate;
uint128 reserve; // ETH kept idle
uint128 tvlCap; // deposits refused above this NAV
}
uint256 internal constant UNIT = 0.01 ether;
/// @notice Everything the shared strategy owns in an account: governed parameters, keeper
/// budgets, the position book, the keeper payment policy and the two operating flags.
struct Strategy {
Params params;
Budget budget;
Book book;
address policy;
bool listingPaused;
bool windingDown;
}
// ---------------------------------------------------------------- bounds and quotes
uint256 internal constant MAX_WORK_FEE = 0.00005 ether; // per unit of work (D55, D56)
uint256 internal constant MAX_MIN_EDGE_BPS = 1_000;
uint256 internal constant MAX_BUFFER_BPS = 2_000;
uint256 internal constant MAX_GAS_CEILING = 50 gwei;
uint256 internal constant MAX_DISTRIBUTION_BPS = 5_000;
uint256 internal constant MAX_PAY_MARKUP_BPS = 1_000; // routine work only (D56, D57)
uint256 internal constant MAX_KEEPER_SHARE_BPS = 5_000;
uint256 internal constant MAX_ALLOCATED_BOUND_BPS = 1_000;
uint256 internal constant MAX_ROUTINE_CAP = 0.3 ether;
uint256 internal constant MAX_ROUTINE_RATE = 0.02 ether;
uint256 internal constant MAX_ESSENTIAL_CAP = 0.1 ether;
uint256 internal constant MAX_ESSENTIAL_RATE = 0.005 ether;
uint256 internal constant MAX_PACK_UNITS = 30; // at most 30 x 0.01 ETH: bounded redemption work
uint256 internal constant MIN_PACK_UNITS = 3; // ShapePacks' minimum pack value, 0.03 ETH
uint256 internal constant REF_UNITS = 6; // the reference recipe: one 0.05 and one 0.01 Shape
/// Purchaser keep incentive. A selected purchaser keeps the pack when it is worth more than the
/// best bid FWA offers (ETH or token bid), after the gas to redeem it, by at least this much.
uint256 internal constant MIN_KEEP_ADVANTAGE = 0.0003 ether;
/// ShapePacks.redeem gas: a pack plus each Shape it holds. Measured on a fork (execution gas):
/// 2 Shapes 157,023, 5 Shapes 245,212, 7 Shapes (the most any allowed size holds) 304,115.
uint256 internal constant Q_PURCHASER_REDEEM_PACK = 100_000;
uint256 internal constant Q_PURCHASER_REDEEM_SHAPE = 30_000;
/// The purchaser's redeem gas is priced at this fixed bound, independent of the keeper's gas
/// ceiling: keeping stays the better choice for any purchaser paying up to 2 gwei.
uint256 internal constant PURCHASER_GAS_PRICE = 2 gwei;
/// Fixed gas quotes from billed receipts (keeper/measure_gas.py, docs/GAS.md). The journal
/// always consumes its full bounded job; only a required checkpoint can pay for a foreign
/// tail. Fee collection has no independently paid entry point. These eligibility rules keep
/// callers from splitting work merely to collect additional bases.
// One checkpoint per interval cannot be split, so it is quoted at measured billed gas.
uint256 internal constant Q_CHECKPOINT = 360_000;
/// Checkpoint proof that booked allocations are still Allocated at FWA (ScanLib), per queue
/// entry examined and per FWA listing read.
uint256 internal constant Q_ALLOCATION_ENTRY = 6_000;
uint256 internal constant Q_ALLOCATION_READ = 30_000;
uint256 internal constant Q_BUILD = 300_000; // call base for build-and-list (one 0.06 pack billed 1,667,619 in all)
// createPack minting straight into the pack (ForkDirectMint: 381k / 534k / 627k gas for 1 / 2 / 3 Shapes)
uint256 internal constant Q_BUILD_PACK = 300_000;
uint256 internal constant Q_BUILD_SHAPE = 130_000;
uint256 internal constant Q_LIST = 280_000;
uint256 internal constant Q_LISTED = 825_000;
uint256 internal constant Q_SYNC = 85_000;
uint256 internal constant Q_REQUIRED_TAIL = 120_000;
uint256 internal constant Q_DISTRIBUTION_PROOF = 80_000;
uint256 internal constant Q_JOURNAL = 22_000; // each completed global acquisition
uint256 internal constant Q_SCAN = 30_000; // each Active position's FWA listing read (scan proof)
uint256 internal constant Q_SELECTED = 180_000; // own selection bookkeeping
uint256 internal constant Q_SYNCED = 120_000; // terminal or recovered return
uint256 internal constant Q_PRUNED = 45_000; // resolved allocation head
uint256 internal constant Q_POSITION_SYNC = Q_JOURNAL + Q_SELECTED + Q_SYNCED + Q_PRUNED;
uint256 internal constant Q_UNLIST = 340_000;
uint256 internal constant Q_UNLISTED = 285_000;
uint256 internal constant Q_LIQUIDATE = 75_000;
uint256 internal constant Q_LIQ_PACK = 80_000; // fixed work per ordinary pack
uint256 internal constant Q_REDEEM_SHAPE = 35_000;
uint256 internal constant Q_RECOVERY_BASE = 100_000;
uint256 internal constant Q_RECOVERY_SHAPE = 35_000;
uint256 internal constant Q_RECOVERY_UNSEAL = 70_000;
uint256 internal constant Q_HARVESTED = 80_000; // per listing with fees claimed
uint256 internal constant Q_CREDIT = 40_000;
uint256 internal constant Q_FUND = 40_000;
/// A bid cycle's quoted gas: select and resolve, relist, and the fee claim that funds it.
uint256 internal constant CYCLE_GAS = Q_POSITION_SYNC + Q_LISTED + Q_HARVESTED;
/// A reference position (0.06 ETH pack + ~0.0648 backing): what request charges are scaled by.
uint256 internal constant POSITION_VALUE = 0.1248 ether;
uint256 internal constant MAX_BATCH = 16;
uint256 internal constant MAX_JOURNAL = 128;
uint256 internal constant MAX_SELECTIONS = 16;
/// Pricing reads at most this many allocation queue entries. The queue from its head holds only
/// allocations newer than the oldest unresolved one, which a checkpoint already requires to be
/// inside FWA's settlement window, so a longer queue waits at most one window for sync.
uint256 internal constant MAX_ALLOCATION_SCAN = 32;
uint256 internal constant MAX_TERMINALS = 16;
uint256 internal constant MAX_PRUNES = 16;
uint256 internal constant MAX_LIST_BATCH = 8;
uint256 internal constant LIST_CALL_GAS = 1_200_000;
uint256 internal constant MAX_REDEEM_SHAPES = 30; // Shapes burned per liquidation call
uint8 internal constant NONE = 0;
uint8 internal constant ACTIVE = 1;
uint8 internal constant ALLOCATED = 2;
uint8 internal constant OWED = 3;
struct Position {
uint256 packId;
uint256 value;
uint256 backing;
uint256 feeDebt;
uint64 allocatedAt;
uint8 state;
}
struct Work { uint256 processed; uint256 own; uint256 resolved; uint256 pruned; uint256 scanned; }
struct BackingTerms {
uint256 k;
uint256 desired;
uint256 cap;
uint256 settlementFee;
uint256 value;
uint256 floor;
uint256 cycleCost;
uint256 build;
bool ok;
}
struct Receipt { uint128 amount; uint16 feeBps; uint8 kind; bool initialized; }
/// @dev Inventory indexes and all financial totals share this single authoritative book.
struct Book {
mapping(uint256 => Position) positions;
mapping(uint256 => uint256) idleValueOf;
mapping(uint256 => uint256) packToListing;
uint256 trackedValue;
uint256 idleValue;
uint256 activeBacking;
uint256 activeCount;
uint256 feeDebtSum;
mapping(uint256 => uint256) countByDebt;
uint256 allocatedValue;
uint256[] allocationQueue;
uint256 allocationHead;
uint64 lastAllocatedAt;
uint256[] open;
mapping(uint256 => uint256) openIndex;
uint256[] idlePacks;
uint256[] recoveryPacks;
mapping(uint256 => bool) recoveryUnsealed;
mapping(uint256 => uint256) idleQuote;
uint256 idleFunding;
mapping(uint256 => uint256) idForBacking;
mapping(uint256 => Receipt) receipts;
uint256 pendingPlusOne;
uint256 reservedCount;
uint64 acquisitionCursor;
bool controlled;
}
event PositionUpdated(uint256 indexed listingId, uint256 packId, uint256 value, uint256 backing, uint256 feeDebt, uint64 allocatedAt, uint8 state);
event InventoryUpdated(uint256 indexed packId, uint256 value);
event RecoveryUpdated(uint256 indexed packId, uint256 value, bool unsealed);
event CashReceipt(uint256 indexed listingId, uint8 outcome, uint256 amount);
event ReceiptConsumed(uint256 indexed listingId);
event JournalProgress(uint64 cursor, uint256 processed, uint256 own);
error Duplicate();
error MissingInventory();
error WrongState();
error InsufficientBacking();
error BadWitness();
error NeedsPrune();
error OutOfOrder();
error InvalidListing();
error InvalidJournal();
error CatchUpFirst();
error PendingReceipts();
error InvalidBacking();
error BadBatch();
error Nothing();
/// @notice One checkpoint's redemption fill. Owed rounds up and a partial fill leaves 2 wei of
/// headroom, so the rounded-up reserve never exceeds the ETH actually freed. `unit` is
/// ETH per locked share x 1e36; holders claim floor(shares x unit) and the reserve
/// (`paid`) rounds the same unit up over the never-understated locked total.
function fill(uint256 locked, uint256 nav, uint256 supply, uint256 liquid)
external
pure
returns (uint256 frac, uint256 filled, uint256 unit, uint256 paid)
{
uint256 owed = M.mulDivUp(locked, nav, supply);
frac = owed <= liquid ? 1e36 : M.mulDiv(liquid > 2 ? liquid - 2 : 0, 1e36, owed);
filled = M.mulDiv(locked, frac, 1e36);
unit = M.mulDiv(frac, nav, supply);
paid = M.mulDivUp(locked, unit, 1e36);
}
error OutOfBounds();
/// Gas a keeper policy's quote may use: enough for arithmetic and reads, not for griefing.
uint256 internal constant POLICY_GAS = 50_000;
uint256 internal constant ORACLE_GAS = 100_000; // floor oracle read; FWA's own oracle uses far less
/// @notice The active keeper policy's proposed pay for verified work, from a bounded-gas
/// staticcall. A revert, out-of-gas or short answer is zero; only the first word of
/// the answer is read, so a policy cannot grief with huge return data.
function offer(
address policy,
uint256 op,
uint256 units,
uint256 gasQ,
bool essential,
uint256 gasCeiling,
uint256 maxTip,
uint256 workFee
) public view returns (uint256 o) {
bytes memory c = abi.encodeCall(IKeeperPolicy.quote, (op, units, gasQ, essential, gasCeiling, maxTip, workFee));
assembly ("memory-safe") {
// Yul evaluates arguments right to left: check returndatasize only after the call.
let ok := staticcall(POLICY_GAS, policy, add(c, 32), mload(c), 0, 32)
if and(ok, gt(returndatasize(), 31)) { o := mload(0) }
}
}
/// @notice A keeper policy must be a contract answering `policyVersion()` with a nonzero value.
function checkPolicy(address policy) external view {
if (policy.code.length == 0) revert OutOfBounds();
try IKeeperPolicy(policy).policyVersion() returns (uint256 v) {
if (v == 0) revert OutOfBounds();
} catch {
revert OutOfBounds();
}
}
// ---------------------------------------------------------------- keeper pay (D56, D57)
/// Keeper budgets: levels as of `at`; each refills at its daily rate up to its cap.
struct Budget {
uint128 routine;
uint128 essential;
uint256 at;
}
event KeeperPaid(address indexed keeper, uint256 amount);
error Payment();
/// @notice The vault's envelope for work: quoted gas at basefee + maxTip, capped at the
/// ceiling, markup on routine work, plus work fees. The most this work may ever pay.
function quote(Params storage p, uint256 gasQ, uint256 units, bool essential) public view returns (uint256 q) {
q = gasQ * M.min(block.basefee + p.maxTip, essential ? p.essentialCeiling : p.gasCeiling);
if (!essential) q = q * (BPS + p.payMarkupBps) / BPS;
q += units * p.workFee;
}
function budgetNow(Params storage p, Budget storage b) public view returns (uint256 r, uint256 e) {
uint256 dt = block.timestamp - b.at;
r = M.min(p.routineCap, b.routine + dt * p.routineRate / 1 days);
e = M.min(p.essentialCap, b.essential + dt * p.essentialRate / 1 days);
}
/// @notice Accrue both budgets to now; caps lowered since only clamp, never refill.
function syncBudget(Params storage p, Budget storage b) external {
(uint256 r, uint256 e) = budgetNow(p, b);
(b.routine, b.essential, b.at) = (uint128(r), uint128(e), block.timestamp);
}
/// @notice Pay the caller for verified work: the least of the policy's offer, the vault's
/// envelope for that work, `cap` (a funding source), free ETH and the budget. Below
/// `minPay` the whole call reverts; with 0 the work is done for whatever is paid.
function pay(
Params storage p,
Budget storage b,
address policy,
uint256 op,
uint256 gasQ,
uint256 units,
bool essential,
uint256 minPay,
uint256 cap,
uint256 free
) external returns (uint256 amount) {
(uint256 r, uint256 e) = budgetNow(p, b);
// A finite `cap` is the request-charge pool: requesters already paid for this work, so it
// is bounded by the pool, not by the holders' budgets.
bool charged = cap != type(uint256).max;
if (charged) (r, e) = (type(uint256).max, type(uint256).max);
uint256 o =
offer(policy, op, units, gasQ, essential, essential ? p.essentialCeiling : p.gasCeiling, p.maxTip, p.workFee);
amount = M.min(M.min(o, M.min(quote(p, gasQ, units, essential), cap)), M.min(free, essential ? e : r));
if (amount < minPay) revert Payment();
if (!charged) {
(b.routine, b.essential, b.at) =
(uint128(essential ? r : r - amount), uint128(essential ? e - amount : e), block.timestamp);
}
if (amount == 0) return 0;
(bool ok,) = msg.sender.call{value: amount}("");
if (!ok) revert Payment();
emit KeeperPaid(msg.sender, amount);
}
// ---------------------------------------------------------------- parameters and charges
/// @notice Bytecode bounds on every parameter.
function checkBounds(Params storage p) external view {
if (
p.minEdgeBps > MAX_MIN_EDGE_BPS || p.bufferBps > MAX_BUFFER_BPS || p.distributionBps > MAX_DISTRIBUTION_BPS
|| p.payMarkupBps > MAX_PAY_MARKUP_BPS || p.workFee > MAX_WORK_FEE || p.keeperShareBps > MAX_KEEPER_SHARE_BPS
|| p.allocatedBoundBps > MAX_ALLOCATED_BOUND_BPS
|| p.gasCeiling > MAX_GAS_CEILING || p.essentialCeiling > MAX_GAS_CEILING || p.maxTip > p.gasCeiling
|| p.routineCap > MAX_ROUTINE_CAP || p.routineRate > MAX_ROUTINE_RATE || p.essentialCap > MAX_ESSENTIAL_CAP
|| p.essentialRate > MAX_ESSENTIAL_RATE
|| p.packUnitsMask >> (MAX_PACK_UNITS + 1) != 0 || p.packUnitsMask & ((1 << MIN_PACK_UNITS) - 1) != 0
) revert OutOfBounds();
}
/// @notice ShapePacks makeup for a pack of `units` x 0.01 ETH, minted straight into the pack:
/// fewest Shapes from the 0.1, 0.05 and 0.01 denominations (index 2, 1, 0 of the nine).
/// Six units are one 0.05 and one 0.01 Shape: two paid primary mints.
function makeup(uint256 units) internal pure returns (uint32[] memory counts, uint256 shapeCount) {
counts = new uint32[](9);
counts[2] = uint32(units / 10);
counts[1] = uint32(units % 10 / 5);
counts[0] = uint32(units % 5);
shapeCount = uint256(counts[0]) + counts[1] + counts[2];
}
function buildGas(uint256 shapeCount) internal pure returns (uint256) {
return Q_BUILD_PACK + shapeCount * Q_BUILD_SHAPE;
}
/// @notice Building one pack of `units` and listing it, at the envelope now, plus its paid
/// primary mint fees (one per Shape).
function buildCost(Params storage p, uint256 units, uint256 mintFee) public view returns (uint256) {
(, uint256 n) = makeup(units);
return quote(p, buildGas(n) + Q_LISTED, 2, false) + n * mintFee;
}
/// @notice A request's checkpoint charge: one checkpoint at its envelope, at cost plus one unit.
function requestCharge(Params storage p) external view returns (uint256) {
return quote(p, Q_CHECKPOINT, 1, true);
}
/// @notice Deployment charge per POSITION_VALUE deposited: building and listing one reference
/// position at its envelope now plus its mint fees, and never less than the most a
/// builder can net over its own gas (markup at the ceiling, the tip it is repaid but
/// need not pay, and the two work fees).
function deployCharge(Params storage p, uint256 mintFee) external view returns (uint256) {
(, uint256 n) = makeup(REF_UNITS);
uint256 g = buildGas(n) + Q_LISTED;
return M.max(quote(p, g, 2, false) + mintFee * n,
g * (p.gasCeiling * p.payMarkupBps + p.maxTip * (BPS + p.payMarkupBps)) / BPS + 2 * p.workFee);
}
/// @notice Unwind charge per POSITION_VALUE redeemed: unlisting and liquidating one position.
function unwindCharge(Params storage p) external view returns (uint256) {
// No essential budget means exit work is unpaid (withdrawers run it): nothing to charge.
if (p.essentialCap == 0) return 0;
(, uint256 n) = makeup(REF_UNITS);
return quote(p, Q_UNLISTED + Q_LIQ_PACK + n * Q_REDEEM_SHAPE, 2, true);
}
/// @notice Backing for a new listing of a pack of `units` x 0.01 ETH, and whether to list.
/// FWA splits each acquisition fee evenly over active listings and selects by 1/B, so a
/// listing expects fees k B before selection. A selected purchaser then keeps the pack
/// (the account gets B (1 - s) back) or takes FWA's best bid, max(ETH, token) x B (the
/// account keeps the pack and loses B). Backing is the largest amount at which keeping
/// still beats the best bid by MIN_KEEP_ADVANTAGE after the gas to redeem the pack, so
/// purchasers keep packs and each keep pays for fresh primary mints. It lists only when
/// both outcomes are profitable after the keeper pay of the cycle (`_profitable`), it
/// is at least P / 0.95 (a keep never loses at FWA's immutable 5% settlement-fee cap),
/// and FWA's oracle cap less the buffer allows it (FWA exempts ShapePacks today).
function edge(Params storage p, IFWAV2 f, address packs, uint256 units, uint256 build)
public
view
returns (uint256 k1e18, uint256 backing, bool ok)
{
BackingTerms memory t = _backingTerms(p, f, packs, units, build);
return (t.k, t.desired, t.ok);
}
function _backingTerms(Params storage p, IFWAV2 f, address packs, uint256 units, uint256 build)
private view returns (BackingTerms memory t)
{
(t.k, t.cap, t.settlementFee) = economics(f, packs);
t.value = units * UNIT;
t.build = build;
t.floor = t.value + t.value / 19 + (t.value % 19 == 0 ? 0 : 1);
uint256 bid = M.max(f.settlementDiscountBps(), f.tokenSettlementDiscountBps());
(, uint256 shapes) = makeup(units);
uint256 margin =
MIN_KEEP_ADVANTAGE + (Q_PURCHASER_REDEEM_PACK + shapes * Q_PURCHASER_REDEEM_SHAPE) * PURCHASER_GAS_PRICE;
if (bid != 0 && t.value > margin) t.desired = (t.value - margin) * BPS / bid / BPS * BPS;
if (t.cap != type(uint256).max) t.desired = M.min(t.desired, t.cap * (BPS - p.bufferBps) / BPS);
t.cycleCost = quote(p, CYCLE_GAS, 2, false);
t.ok = t.cap != 0 && t.k >= 1e18 + uint256(p.minEdgeBps) * 1e14 && t.desired >= t.floor
&& _profitable(t, t.desired, false);
if (!t.ok) t.desired = 0;
}
/// @dev Both outcomes of one selection clear the keeper pay of the cycle: the bid outcome
/// B (k - 1), and the keep outcome B (k - s) - P, which also repays the replacement build
/// when the pack is newly built. Requires k >= 1 (checked before).
function _profitable(BackingTerms memory t, uint256 backing, bool newlyBuilt) private pure returns (bool) {
return backing * (t.k - 1e18) / 1e18 > t.cycleCost
&& backing * (t.k - t.settlementFee * 1e14) / 1e18 >= t.value + t.cycleCost + (newlyBuilt ? t.build : 0);
}
/// @notice Revert before the work when `minPay` already exceeds what could be paid.
function precheck(Params storage p, Budget storage b, uint256 minPay, bool essential, uint256 free)
external
view
{
(uint256 r, uint256 e) = budgetNow(p, b);
if (minPay > M.min(free, essential ? e : r)) revert Payment();
}
function owns(IShapePacks packs, uint256 packId) internal view returns (bool) {
try packs.ownerOf(packId) returns (address o) {
return o == address(this);
} catch {
return false;
}
}
/// @notice Live k (1e18 scale) and FWA's backing cap for `packs` (zero when FWA would refuse
/// a listing). k = (1 + surcharge)(1 - protocolCut)(1 - crownShare).
function economics(IFWAV2 f, address packs) internal view returns (uint256 k1e18, uint256 cap, uint256 s) {
s = f.ownerSettlementFeeBps();
uint256 w = f.totalWeight();
if (w == 0) return (0, 0, s);
// FWA exposes no getter for its surcharge: acquisitionFee = (wbt / w) (1 + surcharge).
uint256 ev = f.weightedBackingTotal() / w;
uint256 oneSur = f.acquisitionFee() * 1e18 / ev; // 1e18 x (1 + surcharge), floors
k1e18 = oneSur * (BPS - f.ownerAcquisitionFeeBps()) / BPS * (BPS - f.topListingShareBps()) / BPS;
if (!f.canDeposit(packs)) return (k1e18, 0, s);
// FWA exempts the collection from its floor cap: no cap applies (D62).
if (f.oracleExemptCollections(packs)) return (k1e18, type(uint256).max, s);
// The oracle ask plus premium when the quote passes FWA's own validity rules.
// A failing or malformed oracle means no cap (nothing new lists); it must not block
// unlisting, wind-down or redemptions. FWA's owner can repoint the oracle to any contract,
// so the read is a raw staticcall: a revert or short return data both mean "no cap".
// Bounded gas and a manual four-word read: a gas-burning oracle or one returning words that
// do not fit their types (which would make abi.decode revert) also means "no cap" (audit S1).
address o = f.floorOracle();
bytes memory c = abi.encodeCall(IFloorOracle.getFloorRange, (packs));
bool ok;
uint256 bid;
uint256 ask;
uint256 observedAt;
uint256 periodUsed;
assembly ("memory-safe") {
let m := mload(0x40) // scratch past the free pointer; not kept
ok := staticcall(ORACLE_GAS, o, add(c, 32), mload(c), m, 128)
if lt(returndatasize(), 128) { ok := 0 }
bid := mload(m)
ask := mload(add(m, 32))
observedAt := mload(add(m, 64))
periodUsed := mload(add(m, 96))
}
if (!ok || observedAt > type(uint48).max || periodUsed > type(uint48).max) return (k1e18, 0, s);
if (bid == 0 || bid >= ask || observedAt == 0 || observedAt > block.timestamp) return (k1e18, 0, s);
if (block.timestamp - observedAt > f.maxOracleAge()) return (k1e18, 0, s);
if (periodUsed < f.minOracleChallengePeriod()) return (k1e18, 0, s);
cap = ask * (BPS + f.oracleCeilingPremiumBps()) / BPS;
}
function _emitPosition(Book storage b, uint256 id) internal {
Position storage p = b.positions[id];
emit PositionUpdated(id, p.packId, p.value, p.backing, p.feeDebt, p.allocatedAt, p.state);
}
function addInventory(Book storage b, uint256 packId, uint256 value) internal {
if (value == 0 || b.idleValueOf[packId] != 0 || b.packToListing[packId] != 0) revert Duplicate();
b.trackedValue += value;
b.idleValue += value;
_toIdle(b, packId, value, 0);
}
function _toIdle(Book storage b, uint256 packId, uint256 value, uint256 backingQuote) private {
if (b.idleValueOf[packId] != 0) revert Duplicate();
b.idleValueOf[packId] = value;
if (value > MAX_PACK_UNITS * UNIT) {
b.recoveryPacks.push(packId);
emit RecoveryUpdated(packId, value, false);
} else {
b.idlePacks.push(packId);
emit InventoryUpdated(packId, value);
}
b.idleQuote[packId] = backingQuote;
b.idleFunding += backingQuote;
}
function list(Book storage b, uint256 id, uint256 packId, uint256 backing, uint256 debt) internal {
if (id == 0 || b.positions[id].value != 0 || b.packToListing[packId] != 0) revert Duplicate();
uint256 value = b.idleValueOf[packId];
if (value == 0) revert MissingInventory();
if (backing < value + value / 19 + (value % 19 == 0 ? 0 : 1)) revert InsufficientBacking();
delete b.idleValueOf[packId];
b.idleValue -= value;
b.idleFunding -= b.idleQuote[packId];
delete b.idleQuote[packId];
if (b.idlePacks[b.idlePacks.length - 1] != packId) revert MissingInventory();
b.idlePacks.pop();
emit InventoryUpdated(packId, 0);
b.positions[id] = Position(packId, value, backing, debt, 0, ACTIVE);
b.packToListing[packId] = id;
b.open.push(id);
b.openIndex[id] = b.open.length;
b.activeBacking += backing;
++b.activeCount;
b.feeDebtSum += debt;
++b.countByDebt[debt];
_emitPosition(b, id);
}
/// @dev Every caller (`_syncJournal`, `ScanLib.rebase`) must move the cursor past this selection's
/// sequence in the same call; completeness of both proofs relies on it.
function select(Book storage b, uint256 id, uint64 at) internal {
Position storage p = b.positions[id];
if (p.state != ACTIVE) revert WrongState();
if (at < b.lastAllocatedAt) revert OutOfOrder();
_removeActive(b, p);
p.state = ALLOCATED;
p.allocatedAt = at;
b.lastAllocatedAt = at;
b.allocatedValue += p.value;
b.allocationQueue.push(id);
_emitPosition(b, id);
}
function keep(Book storage b, uint256 id) internal returns (Position memory p) {
p = b.positions[id];
if (p.state != ALLOCATED) revert WrongState();
b.allocatedValue -= p.value;
b.trackedValue -= p.value;
_retire(b, id, p.packId);
}
function returnPack(Book storage b, uint256 id, bool owned) internal returns (Position memory p) {
Position storage live = b.positions[id];
p = live;
if (p.state == ACTIVE) _removeActive(b, live);
else if (p.state == ALLOCATED) b.allocatedValue -= p.value;
else revert WrongState();
if (owned) {
_retire(b, id, p.packId);
b.idleValue += p.value;
_toIdle(b, p.packId, p.value, p.backing);
} else {
live.state = OWED;
_emitPosition(b, id);
}
}
function claimReturned(Book storage b, uint256 id) internal returns (Position memory p) {
p = b.positions[id];
if (p.state != OWED) revert WrongState();
_retire(b, id, p.packId);
b.idleValue += p.value;
_toIdle(b, p.packId, p.value, p.backing);
}
function redeemInventory(Book storage b, uint256 packId) internal returns (uint256 value) {
value = b.idleValueOf[packId];
if (value == 0 || b.idlePacks[b.idlePacks.length - 1] != packId) revert MissingInventory();
delete b.idleValueOf[packId];
b.idleValue -= value;
b.trackedValue -= value;
b.idleFunding -= b.idleQuote[packId];
delete b.idleQuote[packId];
b.idlePacks.pop();
emit InventoryUpdated(packId, 0);
}
function updateFeeDebt(Book storage b, uint256 id, uint256 debt) internal {
Position storage p = b.positions[id];
if (p.state != ACTIVE) revert WrongState();
uint256 old = p.feeDebt;
if (old == debt) return;
if (debt < old) revert OutOfOrder();
--b.countByDebt[old];
++b.countByDebt[debt];
b.feeDebtSum = b.feeDebtSum - old + debt;
p.feeDebt = debt;
_emitPosition(b, id);
}
function pendingFees(Book storage b, uint256 witnessId, uint256 actualPending) internal view returns (uint256) {
uint256 n = b.activeCount;
if (n == 0) return 0;
Position storage p = b.positions[witnessId];
if (p.state != ACTIVE) revert BadWitness();
uint256 d = p.feeDebt;
if (actualPending == 0) {
if (b.countByDebt[d] + b.countByDebt[d + 1] != n) revert BadWitness();
return 0;
}
uint256 a = d + actualPending;
return n * a + b.countByDebt[a + 1] - b.feeDebtSum;
}
function nav(Book storage b, uint256 freeEth, uint256 credit, uint256 witnessId, uint256 actualPending)
internal view returns (uint256)
{
return freeEth + b.trackedValue + b.activeBacking + credit + pendingFees(b, witnessId, actualPending);
}
function prune(Book storage b, uint256 maxCount) internal returns (uint256 advanced) {
uint256 head = b.allocationHead;
while (advanced < maxCount && head < b.allocationQueue.length) {
if (b.positions[b.allocationQueue[head]].state == ALLOCATED) break;
delete b.allocationQueue[head];
++head;
++advanced;
}
b.allocationHead = head;
}
function oldestAllocation(Book storage b) internal view returns (uint256 id, uint64 at) {
if (b.allocationHead == b.allocationQueue.length) return (0, 0);
id = b.allocationQueue[b.allocationHead];
Position storage p = b.positions[id];
if (p.state != ALLOCATED) revert NeedsPrune();
at = p.allocatedAt;
}
function _removeActive(Book storage b, Position storage p) internal {
b.activeBacking -= p.backing;
--b.activeCount;
b.feeDebtSum -= p.feeDebt;
--b.countByDebt[p.feeDebt];
}
function _retire(Book storage b, uint256 id, uint256 packId) private {
b.positions[id].state = NONE;
delete b.packToListing[packId];
uint256 idx = b.openIndex[id] - 1;
uint256 last = b.open[b.open.length - 1];
b.open[idx] = last;
b.openIndex[last] = idx + 1;
b.open.pop();
delete b.openIndex[id];
_emitPosition(b, id);
}
function listing(IFWAV2 f, uint256 id) internal view returns (IFWAView.Listing memory) {
return IFWAView(address(f)).listings(id);
}
function _validate(IFWAView.Listing memory l, IShapePacks packs, uint256 packId, uint256 backing) private view {
if (l.depositor != address(this) || l.collection != address(packs)
|| l.tokenId != packId || l.value != backing) revert InvalidListing();
}
function admit(Book storage b, IFWAV2 f, IShapePacks packs, uint256 packId, uint256 backing)
public returns (uint256 id)
{
// Backing identifies this listing's cash receipt: two open listings may never share it.
if (b.idForBacking[backing] != 0) revert Duplicate();
_rebaseUnexposed(b, f);
uint256 active = f.activeListingCount();
// FWA's private staging FIFO may activate foreign listings during admission.
// Bound even a reverting attempt, and reject every incidental activation atomically.
try f.listNFT{value: backing, gas: LIST_CALL_GAS}(address(packs), packId) returns (uint256 admitted) {
id = admitted;
} catch {
revert InvalidListing();
}
IFWAView.Listing memory l = listing(f, id);
if (l.status != LISTING_ACTIVE || f.activeListingCount() != active + 1 || f.fwairListing(id)) revert InvalidListing();
_validate(l, packs, packId, backing);
b.receipts[id].initialized = true;
b.idForBacking[backing] = id;
++b.reservedCount;
list(b, id, packId, backing, l.feeDebt);
}
function release(Book storage b, uint256 id, uint256 backing) private {
if (b.idForBacking[backing] != id) revert InvalidListing();
delete b.idForBacking[backing];
--b.reservedCount;
if (b.receipts[id].kind != 0) {
--b.pendingPlusOne;
emit ReceiptConsumed(id);
}
delete b.receipts[id];
}
function syncChanges(Params storage p, Budget storage budget, Book storage b, IFWAV2 f, IShapePacks packs,
uint256[] calldata ids, uint256 checkpointMode, uint256 witnessId)
external returns (uint256 gasQ, uint256 units)
{
bool distributionTail;
(gasQ, units, distributionTail) = _syncChanges(p, b, f, packs, ids, checkpointMode, witnessId);
if (gasQ != 0) gasQ = _fundSync(p, budget, b, f, ids, gasQ, units, distributionTail, witnessId);
}
function _syncChanges(Params storage p, Book storage b, IFWAV2 f, IShapePacks packs,
uint256[] calldata ids, uint256 checkpointMode, uint256 witnessId)
private returns (uint256 gasQ, uint256 units, bool distributionTail)
{
if (ids.length > MAX_TERMINALS) revert BadBatch();
Work memory work;
// No outstanding custody, identifiers or receipts means an unseen selection cannot be ours.
bool unexposed = _unexposed(b);
bool rebased;
if (unexposed) {
rebased = _rebaseUnexposed(b, f);
} else {
// A scan of the vault's own positions replaces the global journal whenever it costs no
// more than the next journal batch (ScanLib.rebase).
(rebased, work.scanned, work.own) = ScanLib.rebase(b, f);
if (!rebased) (work.processed, work.own) = _syncJournal(b, f, packs);
}
for (uint256 i; i < ids.length; ++i) if (_syncTerminal(b, f, packs, ids[i])) ++work.resolved;
work.pruned = prune(b, MAX_PRUNES);
if (work.processed + work.resolved + work.pruned == 0 && !rebased) revert Nothing();
// Rebase is unpaid. Empty-vault head cleanup also cannot consume its bootstrap cash.
if ((unexposed && b.trackedValue == 0) || work.processed + work.scanned + work.resolved + work.pruned == 0) {
return (0, 0, false);
}
bool journalPaid = work.processed == MAX_JOURNAL || work.own + work.resolved != 0;
bool requiredTail;
uint256 tailBase = Q_REQUIRED_TAIL;
if (!journalPaid && work.processed + work.scanned != 0 && checkpointMode != 0) {
journalPaid = f.isPurchaseBlackout() && f.unsettledAcquisitionCount() == 0;
if (journalPaid && checkpointMode == 2) {
tailBase += Q_DISTRIBUTION_PROOF;
journalPaid = _distributionTail(p, b, f, witnessId,
tailBase + work.processed * Q_JOURNAL + work.scanned * Q_SCAN + work.pruned * Q_PRUNED);
}
requiredTail = journalPaid;
}
if (!journalPaid && work.own + work.resolved + work.pruned == 0) return (0, 0, false);
// A scan is paid only when it applied an own selection or is the required checkpoint proof:
// splitting a cycle's terminal work into later calls cannot earn a second scan.
gasQ = (requiredTail ? tailBase : Q_SYNC) + (journalPaid ? work.processed * Q_JOURNAL : 0)
+ (work.own != 0 || requiredTail ? work.scanned * Q_SCAN : 0) + work.own * Q_SELECTED
+ work.resolved * Q_SYNCED + work.pruned * Q_PRUNED;
units = work.resolved;
distributionTail = requiredTail && checkpointMode == 2;
}
/// @dev Terminal proceeds arrive first. Only real paid work may sweep economical credit or
/// claim the first bounded fee prefix needed to fund its complete payment envelope.
function _fundSync(Params storage p, Budget storage budget, Book storage b, IFWAV2 f,
uint256[] calldata ids, uint256 gasQ, uint256 units, bool distributionTail, uint256 witnessId)
private returns (uint256)
{
(uint256 routine,) = budgetNow(p, budget);
uint256 cost = quote(p, gasQ, units, false);
if (routine < cost) return gasQ;
uint256 credit = f.feeCredit(address(this));
uint256 combined = quote(p, gasQ + Q_CREDIT, units, false);
if (credit != 0 && combined <= routine && (combined - cost) * BPS <= credit * p.keeperShareBps
&& (!distributionTail || _distributionTail(p, b, f, witnessId, gasQ + Q_CREDIT))) {
_withdrawCredit(b, f);
gasQ += Q_CREDIT;
cost = combined;
credit = 0;
}
uint256 free = ISyncVault(address(this)).freeEth();
if (free >= cost) return gasQ;
uint256[] memory claims = new uint256[](ids.length);
uint256 count;
uint256 fees = credit;
for (uint256 i; i < ids.length; ++i) {
uint256 id = ids[i];
if (b.positions[id].state != ACTIVE || listing(f, id).status != LISTING_ACTIVE) continue;
bool duplicate;
for (uint256 j; j < count; ++j) if (claims[j] == id) duplicate = true;
if (duplicate) continue;
uint256 pending = f.pendingFees(id);
if (pending == 0) continue;
claims[count++] = id;
fees += pending;
uint256 fundedGas = gasQ + Q_FUND + count * Q_HARVESTED + (credit != 0 ? Q_CREDIT : 0);
combined = quote(p, fundedGas, units, false);
if (free + fees < combined) continue;
// Once enough cash was found, extra IDs cannot increase the claim or its payment.
if (combined > routine || (combined - cost) * BPS > fees * p.keeperShareBps
|| (distributionTail && !_distributionTail(p, b, f, witnessId, fundedGas))) return gasQ;
assembly ("memory-safe") { mstore(claims, count) }
uint256 before = address(this).balance;
if (!_claimFees(b, f, claims)) return gasQ;
if (credit != 0) _withdrawCredit(b, f);
uint256 received = address(this).balance - before;
if (free + received < combined || (combined - cost) * BPS > received * p.keeperShareBps) revert Payment();
return fundedGas;
}
return gasQ;
}
function _distributionTail(Params storage p, Book storage b, IFWAV2 f, uint256 witnessId, uint256 gasQ)
private view returns (bool)
{
if (b.allocationHead < b.allocationQueue.length) {
Position storage oldest = b.positions[b.allocationQueue[b.allocationHead]];
if (oldest.state != ALLOCATED || block.timestamp >= uint256(oldest.allocatedAt) + f.settlementWindow()) return false;
}
ISyncVault v = ISyncVault(address(this));
uint256 nav_;
try v.accountedNav(witnessId) returns (uint256 n) { nav_ = n; } catch { return false; }
// Prove a real distribution remains possible even after the largest sync payment.
uint256 cost = quote(p, gasQ, 0, false);
if (nav_ <= cost) return false;
nav_ -= cost;
if (b.allocatedValue * BPS > nav_ * p.allocatedBoundBps) return false;
uint256 supply = v.totalShares();
uint256 perShare = nav_ * 1e18 / supply;
uint256 high = v.highWaterMark();
if (supply <= DEAD_SHARES || perShare <= high) return false;
uint256 liquid = v.freeEth() + f.feeCredit(address(this));
if (liquid <= p.reserve) return false;
liquid -= p.reserve;
if (liquid <= cost) return false;
uint256 gain = M.mulDiv(perShare - high, supply, 1e18);
return M.min(gain * p.distributionBps / BPS, liquid - cost) >= MIN_DISTRIBUTION;
}
function _unexposed(Book storage b) private view returns (bool) {
return b.open.length == 0 && b.reservedCount == 0 && b.activeCount == 0
&& b.activeBacking == 0 && b.allocatedValue == 0 && b.pendingPlusOne == 1;
}
function _rebaseUnexposed(Book storage b, IFWAV2 f) private returns (bool advanced) {
if (!_unexposed(b)) return false;
uint64 end = f.nextSequenceToProcess();
if (b.acquisitionCursor < end) {
b.acquisitionCursor = end;
emit JournalProgress(end, 0, 0);
return true;
}
}
function _syncJournal(Book storage b, IFWAV2 f, IShapePacks packs)
private returns (uint256 processed, uint256 own)
{
uint64 cursor = b.acquisitionCursor;
uint64 end = f.nextSequenceToProcess();
while (cursor < end && processed < MAX_JOURNAL) {
uint256 requestId = f.requestIdAtSequence(cursor);
if (requestId == 0) revert InvalidJournal();
IFWAV2.Acquisition memory a = f.acquisitions(requestId);
if (a.status == 2) {
if (a.listingId == 0) revert InvalidJournal();
if (b.positions[a.listingId].value != 0) {
if (own == MAX_SELECTIONS) break;
Position memory p = b.positions[a.listingId];
if (p.state != ACTIVE) revert InvalidJournal();
IFWAView.Listing memory l = listing(f, a.listingId);
_validate(l, packs, p.packId, p.backing);
if (l.status != LISTING_ALLOCATED && l.status != LISTING_SETTLED) revert InvalidJournal();
select(b, a.listingId, l.allocatedAt);
++own;
}
} else if (a.status != 3 && a.status != 4) revert InvalidJournal();
++cursor;
++processed;
}
b.acquisitionCursor = cursor;
if (processed != 0) emit JournalProgress(cursor, processed, own);
}
function _syncTerminal(Book storage b, IFWAV2 f, IShapePacks packs, uint256 id) private returns (bool) {
Position memory p = b.positions[id];
if (p.state == NONE) return false;
IFWAView.Listing memory l = listing(f, id);
_validate(l, packs, p.packId, p.backing);
if (p.state == OWED) {
if (f.stuckNFTRecipient(id) == address(this)) {
(bool ok,) = address(f).call(abi.encodeCall(IFWAV2.recoverStuckNFT, (id)));
if (!ok) return false;
}
if (!owns(packs, p.packId)) return false;
claimReturned(b, id);
return true;
}
if (l.status == LISTING_ALLOCATED) {
if (p.state != ALLOCATED || block.timestamp < uint256(l.allocatedAt) + f.settlementWindow()) return false;
// Expiry resolution must still identify its genuine keep payment.
if (p.backing * (BPS - f.ownerSettlementFeeBps()) / BPS >= p.value) f.depositorReclaimBacking(id);
else f.depositorReclaimNFT(id);
l = listing(f, id);
}
if (l.status == LISTING_ACTIVE) return false;
// FWA changes a listing's status and pays its depositor in the same transaction
// (forceSafeTransferETH, which force-sends when receive() fails), so FWA's record alone
// proves the outcome and its cash. The receipt only gates checkpoints until this sync;
// a payment whose receipt was never recorded resolves here the same way.
bool owned = owns(packs, p.packId);
bool returned = owned || f.stuckNFTRecipient(id) == address(this);
if (l.status == LISTING_SETTLED) {
if (p.state == ACTIVE) return false;
if (p.state != ALLOCATED) revert InvalidListing();
// Keep, relist, expiry or default: B (1 - s) paid, the pack went to the purchaser.
// A bid returns the pack to the depositor (or owes it) and pays nothing. A kept pack
// that came back (a gift, perhaps with extra Shapes) joins inventory at its actual value.
if (b.receipts[id].kind == 1 || !returned) {
release(b, id, p.backing);
keep(b, id);
if (owned) addInventory(b, p.packId, packs.valueOf(p.packId));
return true;
}
} else if (l.status == LISTING_WITHDRAWN) {
// Only a kick withdraws a listing outside this account's own calls: B refunded, pack returned.
if (p.state != ACTIVE || !returned) revert InvalidListing();
} else return false;
release(b, id, p.backing);
returnPack(b, id, owned);
return true;
}
function withdraw(Book storage b, IFWAV2 f, IShapePacks packs, uint256 id) external {
Position memory p = b.positions[id];
if (p.state != ACTIVE) revert WrongState();
b.controlled = true;
f.withdrawListing(id);
b.controlled = false;
bool owned = owns(packs, p.packId);
if (!owned && f.stuckNFTRecipient(id) != address(this)) revert InvalidListing();
release(b, id, p.backing);
returnPack(b, id, owned);
}
function harvest(Book storage b, IFWAV2 f, uint256[] calldata ids) external {
if (ids.length > MAX_BATCH) revert BadBatch();
for (uint256 i; i < ids.length; ++i) {
if (i != 0 && ids[i] <= ids[i - 1]) revert BadBatch();
}
_claimFees(b, f, ids);
if (f.feeCredit(address(this)) != 0) _withdrawCredit(b, f);
}
function _claimFees(Book storage b, IFWAV2 f, uint256[] memory ids) private returns (bool claimed) {
b.controlled = true;
if (ids.length != 0) {
try f.claimListingFees(ids) {
for (uint256 i; i < ids.length; ++i) {
IFWAView.Listing memory l = listing(f, ids[i]);
if (b.positions[ids[i]].state == ACTIVE && l.status == LISTING_ACTIVE) updateFeeDebt(b, ids[i], l.feeDebt);
}
claimed = true;
} catch {}
}
b.controlled = false;
}
function harvestCredit(Book storage b, IFWAV2 f) external {
if (f.feeCredit(address(this)) != 0) _withdrawCredit(b, f);
}
function _withdrawCredit(Book storage b, IFWAV2 f) private {
b.controlled = true;
f.withdrawEarnings();
b.controlled = false;
}
function accountedNav(Book storage b, IFWAV2 f, IShapePacks packs, uint256 freeEth, uint256 witnessId)
external view returns (uint256 value)
{
(value,) = _accountedNav(b, f, packs, freeEth, witnessId);
}
/// @return value NAV; gasQ the checkpoint's quoted gas, including the allocation proof it read.
function checkpointNav(Book storage b, IFWAV2 f, IShapePacks packs, uint256 freeEth, uint256 witnessId)
external returns (uint256 value, uint256 gasQ)
{
_rebaseUnexposed(b, f);
return _accountedNav(b, f, packs, freeEth, witnessId);
}
function _accountedNav(Book storage b, IFWAV2 f, IShapePacks packs, uint256 freeEth, uint256 witnessId)
private view returns (uint256, uint256 gasQ)
{
if (b.acquisitionCursor != f.nextSequenceToProcess()) revert CatchUpFirst();
if (b.pendingPlusOne != 1) revert PendingReceipts();
(uint256 entries, uint256 reads) = ScanLib.requireAllocatedCurrent(b, f, packs);
gasQ = Q_CHECKPOINT + entries * Q_ALLOCATION_ENTRY + reads * Q_ALLOCATION_READ;
uint256 pending;
if (b.activeCount != 0) {
Position memory p = b.positions[witnessId];
IFWAView.Listing memory l = listing(f, witnessId);
if (p.state != ACTIVE || l.status != LISTING_ACTIVE || p.feeDebt != l.feeDebt) revert BadWitness();
_validate(l, packs, p.packId, p.backing);
pending = f.pendingFees(witnessId);
}
return (nav(b, freeEth, f.feeCredit(address(this)), witnessId, pending), gasQ);
}
function validateBacking(Params storage p, Book storage b, IFWAV2 f, address packs,
uint256 units, uint256 backing, uint256 build, bool newlyBuilt) public view
{
_validateBacking(p, b, _backingTerms(p, f, packs, units, build), backing, newlyBuilt);
}
function _validateBacking(Params storage p, Book storage b, BackingTerms memory t,
uint256 backing, bool newlyBuilt) private view
{
if (!t.ok || backing == 0 || backing > type(uint128).max || backing % BPS != 0
|| b.idForBacking[backing] != 0) revert InvalidBacking();
uint256 delta = backing > t.desired ? backing - t.desired : t.desired - backing;
if (delta > (b.reservedCount + 1) * BPS) revert InvalidBacking();
if (backing < t.floor || (t.cap != type(uint256).max && backing > t.cap * (BPS - p.bufferBps) / BPS)
|| !_profitable(t, backing, newlyBuilt)) revert InvalidBacking();
}
/// @notice Mint `count` packs of `units` straight into ShapePacks (one paid primary mint per
/// Shape, no split) and list each at its validated backing proposal. `available` is the
/// account's spendable ETH; idle packs keep their reserved backing (`idleFunding`).
function buildAndList(Params storage p, Book storage b, IFWAV2 f, IShapePacks packs, IShapes shapes,
uint256 units, uint256[] calldata backingProposals, uint256 available) external
{
uint256 count = backingProposals.length;
if (count == 0 || count > MAX_LIST_BATCH || units < MIN_PACK_UNITS || units > MAX_PACK_UNITS
|| (p.packUnitsMask >> units) & 1 == 0) revert BadBatch();
(uint32[] memory counts, uint256 n) = makeup(units);
uint256 fee = shapes.mintFee();
uint256 price = units * UNIT + n * fee;
BackingTerms memory terms = _backingTerms(p, f, address(packs), units, buildCost(p, units, fee));
uint256 need = b.idleFunding + count * price;
for (uint256 i; i < count; ++i) need += backingProposals[i];
if (available < need) revert InsufficientBacking();
uint256[] memory none = new uint256[](0);
for (uint256 i; i < count; ++i) {
// Validated one at a time, as in `list`: each admission widens the identifier interval.
_validateBacking(p, b, terms, backingProposals[i], true);
uint256 packId = packs.createPack{value: price}(none, counts);
// ShapePacks records exactly the minted backing; a different value is not our pack.
if (packs.valueOf(packId) != units * UNIT) revert MissingInventory();
addInventory(b, packId, units * UNIT);
admit(b, f, packs, packId, backingProposals[i]);
}
}
/// @dev An extended gift may contain arbitrarily many Shapes. Never enumerate its contents.
function recoverInventory(Book storage b, IShapePacks packs, IShapes shapes) external returns (uint256 gasQ) {
uint256 id = b.recoveryPacks[b.recoveryPacks.length - 1];
gasQ = Q_RECOVERY_BASE;
if (!b.recoveryUnsealed[id]) {
packs.unseal(id, address(this));
b.recoveryUnsealed[id] = true;
gasQ += Q_RECOVERY_UNSEAL;
}
uint256 before = address(this).balance;
uint256 supply = shapes.totalSupply();
packs.claimEth(id, MAX_REDEEM_SHAPES, payable(address(this)));
uint256 out = address(this).balance - before;
// The immutable Shapes path burns exactly the claimed IDs before its sole ETH callback.
// No other supply mutation can interleave while this guarded vault receives that ETH.
uint256 burned = supply - shapes.totalSupply();
if (out == 0 || burned == 0 || burned > MAX_REDEEM_SHAPES) revert MissingInventory();
gasQ += burned * Q_RECOVERY_SHAPE;
b.trackedValue -= out;
b.idleValue -= out;
b.idleValueOf[id] -= out;
bool unsealed = true;
if (packs.claimantOf(id) == address(0)) {
if (b.idleValueOf[id] != 0) revert MissingInventory();
delete b.idleValueOf[id];
delete b.recoveryUnsealed[id];
b.idleFunding -= b.idleQuote[id];
delete b.idleQuote[id];
b.recoveryPacks.pop();
unsealed = false;
}
emit RecoveryUpdated(id, b.idleValueOf[id], unsealed);
}
}
lib/solady/src/utils/FixedPointMathLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if gt(x, div(not(0), y)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if iszero(eq(div(z, y), x)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(mul(y, eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
/// Note: This function is an approximation.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r = int256(
(uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
);
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function lnWad(int256 x) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
/// Note: This function is an approximation. Monotonically increasing.
function lambertW0Wad(int256 x) internal pure returns (int256 w) {
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
(int256 wad, int256 p) = (int256(WAD), x);
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (uint256(w >> 63) == uint256(0)) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == uint256(0)) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != uint256(0));
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c == uint256(0)) return w;
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `a * b == x * y`, with full precision.
function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// 512-bit multiply `[p1 p0] = x * y`.
// Compute the product mod `2**256` and mod `2**256 - 1`
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that `product = p1 * 2**256 + p0`.
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`.
for {} 1 {} {
// If overflows.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
let r := mulmod(x, y, d) // Compute remainder using mulmod.
let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
// Make sure `z` is less than `2**256`. Also prevents `d == 0`.
// Placing the check here seems to give more optimal stack operations.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
d := div(d, t) // Divide `d` by `t`, which is a power of two.
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// Now use 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.
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
z :=
mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
)
break
}
z := div(z, d)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
/// Performs the full 512 bit calculation regardless.
function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z)))
let t := and(d, sub(0, d))
let r := mulmod(x, y, d)
d := div(d, t)
let inv := xor(2, mul(3, d))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
z :=
mul(
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv)
)
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
z = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let k := and(n, 0xff) // `n`, cleaned.
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(k, p1)) {
z := add(shl(sub(256, k), p1), shr(k, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(and(n, 0xff), z)
break
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(z, d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(z, d))), div(z, d))
}
}
/// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
/// @solidity memory-safe-assembly
assembly {
let g := n
let r := mod(a, n)
for { let y := 1 } 1 {} {
let q := div(g, r)
let t := g
g := r
r := sub(t, mul(r, q))
let u := x
x := y
y := sub(u, mul(y, q))
if iszero(r) { break }
}
x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `max(0, x - y)`.
function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x + y)`.
function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(0, lt(add(x, y), x)), add(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x * y)`.
function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `x != 0 ? x : y`, without branching.
function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != bytes32(0) ? x : y`, without branching.
function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != address(0) ? x : y`, without branching.
function coalesce(address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(shl(96, x))))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if x {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`, rounded down.
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), z)
// Goal was to get `z*z*y` within a small factor of `x`. More iterations could
// get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
// We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
// That's not possible if `x < 256` but we can just verify those cases exhaustively.
// Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
// Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
// Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
// For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
// is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
// with largest error when `s = 1` and when `s = 256` or `1/256`.
// Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
// Then we can estimate `sqrt(y)` using
// `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
// There is no overflow risk here since `y < 2**136` after the first branch above.
z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If `x+1` is a perfect square, the Babylonian method cycles between
// `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`, rounded down.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// Makeshift lookup table to nudge the approximate log2 result.
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
// Newton-Raphson's.
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
// Round down.
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
function sqrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
z = (1 + sqrt(x)) * 10 ** 9;
z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
}
/// @solidity memory-safe-assembly
assembly {
z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
z = (1 + cbrt(x)) * 10 ** 12;
z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
}
/// @solidity memory-safe-assembly
assembly {
let p := x
for {} 1 {} {
if iszero(shr(229, p)) {
if iszero(shr(199, p)) {
p := mul(p, 100000000000000000) // 10 ** 17.
break
}
p := mul(p, 100000000) // 10 ** 8.
break
}
if iszero(shr(249, p)) { p := mul(p, 100) }
break
}
let t := mulmod(mul(z, z), z, p)
z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
}
}
/// @dev Returns `sqrt(x * y)`. Also called the geometric mean.
function mulSqrt(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (x == y) return x;
uint256 p = rawMul(x, y);
if (y == rawDiv(p, x)) return sqrt(p);
for (z = saturatingMul(rawAdd(sqrt(x), 1), rawAdd(sqrt(y), 1));; z = avg(z, p)) {
if ((p = fullMulDivUnchecked(x, y, z)) >= z) break;
}
}
/// @dev Returns the factorial of `x`.
function factorial(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := 1
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for {} x { x := sub(x, 1) } { z := mul(z, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(uint256 x) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(uint256 x) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(uint256 x) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(uint256 x) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards zero.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(int256 x) internal pure returns (uint256 z) {
unchecked {
z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
internal
pure
returns (uint256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
unchecked {
if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
return a - fullMulDiv(a - b, t - begin, end - begin);
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
internal
pure
returns (int256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
// forgefmt: disable-next-item
unchecked {
if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
uint256(t - begin), uint256(end - begin)));
return int256(uint256(a) - fullMulDiv(uint256(a - b),
uint256(t - begin), uint256(end - begin)));
}
}
/// @dev Returns if `x` is an even number. Some people may need this.
function isEven(uint256 x) internal pure returns (bool) {
return x & uint256(1) == uint256(0);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}
src/KeeperPolicy.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
/// @notice Keeper payment policy: proposes what verified work pays. PackVault calls it with a
/// bounded-gas staticcall, after the work, with facts the vault established itself; the
/// vault then pays at most its own envelope, free ETH and budget. A policy holds nothing,
/// moves nothing and cannot decide whether work happened. Replace it by deploying a new
/// contract and setting its address with the vault owner's `setPolicy` (D57, D58).
interface IKeeperPolicy {
/// @notice Nonzero; the vault checks it before accepting a policy address.
function policyVersion() external view returns (uint256);
/// @param op PackVault.OP_* (1 restock, 2 list, 3 sync, 5 unlist, 6 liquidate,
/// 8 checkpoint). Operations 4 and 7 are retired.
/// @param units completed units of work the vault counted (packs built, positions
/// listed, resolved, activated or unlisted, items liquidated, 1 checkpoint).
/// @param gasAllowance the vault's calibrated quoted gas for this work (base + per unit).
/// @param essential redemption or wind-down work.
/// @param gasCeiling the vault's gas ceiling, wei per gas.
/// @param maxTip the vault's tip allowance over basefee, wei per gas.
/// @param workFee the vault's flat fee per unit, wei.
/// @return payment proposed wei; the vault caps it.
function quote(
uint256 op,
uint256 units,
uint256 gasAllowance,
bool essential,
uint256 gasCeiling,
uint256 maxTip,
uint256 workFee
) external view returns (uint256 payment);
}
/// @notice V1: the gas allowance at basefee + maxTip, capped at the ceiling, plus the flat work fee
/// per completed unit. No premium: the work fee is the keeper's margin.
contract KeeperPolicyV1 is IKeeperPolicy {
function policyVersion() external pure returns (uint256) {
return 1;
}
function quote(uint256, uint256 units, uint256 gasAllowance, bool, uint256 gasCeiling, uint256 maxTip, uint256 workFee)
external
view
returns (uint256)
{
uint256 price = block.basefee + maxTip;
if (price > gasCeiling) price = gasCeiling;
return gasAllowance * price + units * workFee;
}
}
src/ScanLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {VaultLib} from "./VaultLib.sol";
import {IFWAV2, IFWAView, IShapePacks, LISTING_ACTIVE, LISTING_ALLOCATED, LISTING_SETTLED} from "./interfaces/External.sol";
/// @notice The read half of VaultLib's scan proof, a separate library only for EIP-170 size.
library ScanLib {
/// @dev Every position the book holds Allocated must still be Allocated at FWA. A settlement
/// pays the account in its own transaction; if receive() could not record the receipt
/// (forced ETH), the cash would otherwise count beside the position until it is synced.
/// Reads at most MAX_ALLOCATION_SCAN queue entries from the head (else CatchUpFirst: sync
/// and prune first), so pricing cost never grows with allocation history.
/// A kick refunds B the same way, so while FWA can kick (the ShapePacks oracle exemption
/// lifted) and the account holds at most MAX_ALLOCATION_SCAN open entries, every booked
/// Active listing must also still be Active at FWA. Above that the check is skipped, not
/// refused, so pricing never stalls on FWA's exemption: an unrecorded kick refund needs
/// receive() to exceed FWA's 100,000 gas stipend (it uses 35,148), and with the exemption in
/// place no listing can be kicked.
function requireAllocatedCurrent(VaultLib.Book storage b, IFWAV2 f, IShapePacks packs)
external view returns (uint256 entries, uint256 reads)
{
uint256 n = b.open.length;
if (b.activeCount != 0 && n <= VaultLib.MAX_ALLOCATION_SCAN && !f.oracleExemptCollections(address(packs))) {
entries = n;
for (uint256 i; i < n; ++i) {
uint256 id = b.open[i];
if (b.positions[id].state != VaultLib.ACTIVE) continue;
++reads;
if (IFWAView(address(f)).listings(id).status != LISTING_ACTIVE) revert VaultLib.PendingReceipts();
}
}
if (b.allocatedValue == 0) return (entries, reads);
uint256 head = b.allocationHead;
uint256 queued = b.allocationQueue.length - head;
if (queued > VaultLib.MAX_ALLOCATION_SCAN) revert VaultLib.CatchUpFirst();
entries += queued;
for (uint256 i = head; i < head + queued; ++i) {
uint256 id = b.allocationQueue[i];
if (b.positions[id].state != VaultLib.ALLOCATED) continue;
++reads;
uint8 status = IFWAView(address(f)).listings(id).status;
// A bid pays nothing and returns the pack: the booked position already counts it.
if (status == LISTING_ALLOCATED || (status == LISTING_SETTLED
&& (VaultLib.owns(packs, b.positions[id].packId) || f.stuckNFTRecipient(id) == address(this)))) continue;
revert VaultLib.PendingReceipts();
}
}
function rebase(VaultLib.Book storage b, IFWAV2 f) external returns (bool, uint256 scanned, uint256 own) {
uint64 end = f.nextSequenceToProcess();
uint256 backlog = end - b.acquisitionCursor;
// Taken only when it costs no more than the next journal batch: a small vault's upkeep then
// scales with its own positions, not with FWA's global activity, and the scan stays within
// the journal batch's gas envelope.
uint256 batch = backlog < VaultLib.MAX_JOURNAL ? backlog : VaultLib.MAX_JOURNAL;
if (backlog == 0 || b.open.length * VaultLib.Q_SCAN > batch * VaultLib.Q_JOURNAL) return (false, 0, 0);
uint256[] memory found = new uint256[](VaultLib.MAX_SELECTIONS);
for (uint256 i; i < b.open.length; ++i) {
uint256 id = b.open[i];
if (b.positions[id].state != VaultLib.ACTIVE) continue;
++scanned;
IFWAView.Listing memory l = IFWAView(address(f)).listings(id);
if (l.status != LISTING_ALLOCATED && l.status != LISTING_SETTLED) continue;
if (own == found.length) return (false, 0, 0);
uint256 x = uint256(l.allocatedAt) << 192 | id;
uint256 j = own++;
for (; j != 0 && found[j - 1] > x; --j) found[j] = found[j - 1];
found[j] = x;
}
if (own != 0 && found[0] >> 192 < b.lastAllocatedAt) return (false, 0, 0);
for (uint256 i; i < own; ++i) VaultLib.select(b, uint192(found[i]), uint64(found[i] >> 192));
b.acquisitionCursor = end;
emit VaultLib.JournalProgress(end, 0, own);
return (true, scanned, own);
}
}
src/interfaces/External.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
/// @dev Minimal surfaces of the deployed contracts this repo calls, taken from their verified
/// sources: FWAV2 0x958C41181182e76F221331b2755b77D9e1426A98, FWAV2Rewards
/// 0xA54b44C7a894AA19C49734A753D01f9B8C5f6516, Shapes 0x6fE9193276bF7aBCbEE44AB7aFd717d637D6FAf0,
/// ShapePacks 0xf21514B090Da7dF4390803497d6ae673801E5cA7, the FWA floor oracle and the
/// Uniswap v4 PoolManager the FWA token reports.
interface IERC721Min {
function ownerOf(uint256 tokenId) external view returns (address);
function setApprovalForAll(address operator, bool approved) external;
function transferFrom(address from, address to, uint256 tokenId) external;
}
interface IShapes is IERC721Min {
function totalSupply() external view returns (uint256);
function mint(uint256 amountWei) external payable returns (uint256 tokenId);
function mintFee() external view returns (uint256);
function split(uint256 tokenId, uint8[] calldata outDenoms) external returns (uint256[] memory newIds);
function redeem(uint256 tokenId) external;
function backingOf(uint256 tokenId) external view returns (uint256);
}
interface IShapePacks is IERC721Min {
function createPack(uint256[] calldata shapeIds, uint32[] calldata mintCounts)
external
payable
returns (uint256 packId);
function redeem(uint256 packId) external;
function unseal(uint256 packId, address claimant) external;
function claimEth(uint256 packId, uint256 maxCount, address payable recipient) external;
function claimantOf(uint256 packId) external view returns (address);
function valueOf(uint256 packId) external view returns (uint256);
function contentsOf(uint256 packId) external view returns (uint256[] memory);
}
interface IFloorOracle {
function getFloorRange(address collection)
external
view
returns (uint256 bidPrice, uint256 askPrice, uint48 observedAt, uint48 periodUsed);
}
/// @dev FWAV2 ListingStatus values.
uint8 constant LISTING_ACTIVE = 1;
uint8 constant LISTING_ALLOCATED = 2;
uint8 constant LISTING_WITHDRAWN = 3;
uint8 constant LISTING_SETTLED = 4;
uint8 constant LISTING_STAGED = 5;
/// @dev Struct return is ABI-identical to the deployed public mapping getter.
interface IFWAView {
struct Listing {
address collection; address depositor; address purchaser;
uint256 tokenId; uint256 weight; uint256 value; uint256 feeShare;
uint256 feeDebt; uint256 slot; uint64 allocatedAt; uint8 status;
}
function listings(uint256 id) external view returns (Listing memory);
}
interface IFWAV2 {
struct Acquisition {
address purchaser; uint256 requestBlock; uint256 priceEscrowed;
uint256 listingId; uint8 status;
}
function nextSequenceToProcess() external view returns (uint64);
function lastIssuedSequence() external view returns (uint64);
function requestIdAtSequence(uint64 sequence) external view returns (uint256);
function acquisitions(uint256 requestId) external view returns (Acquisition memory);
function fwairListing(uint256 id) external view returns (bool);
function listNFT(address collection, uint256 tokenId) external payable returns (uint256 listingId);
function withdrawListing(uint256 listingId) external;
function claimListingFees(uint256[] calldata listingIds) external returns (uint256 total);
function withdrawEarnings() external returns (uint256 amount);
function depositorReclaimBacking(uint256 listingId) external;
function depositorReclaimNFT(uint256 listingId) external;
function recoverStuckNFT(uint256 listingId) external;
function stuckNFTRecipient(uint256 listingId) external view returns (address);
function finalizeUnsettled(uint256 listingId) external;
function pendingFees(uint256 listingId) external view returns (uint256);
function feeCredit(address depositor) external view returns (uint256);
function listings(uint256 listingId)
external
view
returns (
address collection,
address depositor,
address purchaser,
uint256 tokenId,
uint256 weight,
uint256 value,
uint256 feeShare,
uint256 feeDebt,
uint256 slot,
uint64 allocatedAt,
uint8 status
);
function unsettledAcquisitionCount() external view returns (uint256);
function isPurchaseBlackout() external view returns (bool);
function canDeposit(address collection) external view returns (bool);
function oracleExemptCollections(address collection) external view returns (bool);
function floorOracle() external view returns (address);
function oracleCeilingPremiumBps() external view returns (uint256);
function maxOracleAge() external view returns (uint48);
function minOracleChallengePeriod() external view returns (uint48);
function ownerAcquisitionFeeBps() external view returns (uint256);
function ownerSettlementFeeBps() external view returns (uint256);
function topListingShareBps() external view returns (uint256);
function topListingId() external view returns (uint256);
function topListingSince() external view returns (uint64);
function settlementDiscountBps() external view returns (uint256);
function tokenSettlementDiscountBps() external view returns (uint256);
function settlementWindow() external view returns (uint256);
function finalizeWindow() external view returns (uint256);
function acquisitionFee() external view returns (uint256);
function totalWeight() external view returns (uint256);
function weightedBackingTotal() external view returns (uint256);
function activeListingCount() external view returns (uint256);
function token() external view returns (address);
function rewards() external view returns (address);
}
interface IFWARewards {
function claimDepositorTokens(uint256[] calldata listingIds) external returns (uint256 total);
function withdrawTokens() external returns (uint256 amount);
function pendingDepositorTokens(uint256 listingId) external view returns (uint256);
function tokenCredit(address depositor) external view returns (uint256);
}
interface IERC20Min {
function balanceOf(address account) external view returns (uint256);
function totalSupply() external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
}
/// @dev Uniswap v4 types, ABI-compatible with v4-core: Currency is an address, BalanceDelta packs
/// amount0 in the high 128 bits and amount1 in the low 128 bits.
struct PoolKey {
address currency0;
address currency1;
uint24 fee;
int24 tickSpacing;
address hooks;
}
struct SwapParams {
bool zeroForOne;
int256 amountSpecified;
uint160 sqrtPriceLimitX96;
}
interface IFWAToken is IERC20Min {
function poolManager() external view returns (address);
function poolKey() external view returns (PoolKey memory);
function isDistributor(address account) external view returns (bool);
/// Allowed for any holder, though transfers are otherwise locked (probed on a fork).
function burn(uint256 amount) external;
}
interface IPoolManager {
function unlock(bytes calldata data) external returns (bytes memory);
function swap(PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (int256 delta);
function take(address currency, address to, uint256 amount) external;
function sync(address currency) external;
function settle() external payable returns (uint256);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {
"src/ScanLib.sol": {
"ScanLib": "0x5d42A8D00C2f320247771e0A76E0D525454a9E8A"
}
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"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.