Verified contractPartialMIT
FloorBookEngine
Address0xd7ee879addf66bc3117a3def5367fb05c5d6bc53
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,480,120
- Creation transaction
- 0x66eec7c22e…e095cb36a0
21 files
- src/v2/engines/FloorBookEngine.solmain16.55 KB
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.15 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- src/interfaces/IFloorAmm.sol32.86 KB
- src/interfaces/IRegistries.sol4.58 KB
- src/libraries/FloorFixed.sol6.59 KB
- src/libraries/FloorRewards.sol24.78 KB
- src/v2/FloorBandsV2.sol315 B
- src/v2/FloorBookTypes.sol7.18 KB
- src/v2/FloorSlotV2.sol620 B
- src/v2/engines/FloorCreditV2.sol9.06 KB
- src/v2/engines/IFloorBookEngine.sol4.13 KB
- src/v2/engines/IFloorTradeEngines.sol1.96 KB
- src/v2/engines/book/FloorBookStore.sol23.52 KB
- src/v2/engines/book/FloorBookWalk.sol42.62 KB
- src/v2/math/FloorFeesV2.sol6.71 KB
- src/v2/math/FloorSqrtV2.sol5.22 KB
- src/v2/math/FloorSupplyV2.sol858 B
- src/v2/math/FloorWideV2.sol3.81 KB
- src/v2/storage/FloorBookStorage.sol8.42 KB
src/v2/engines/FloorBookEngine.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IFloorAmm} from "../../interfaces/IFloorAmm.sol";
import {IFloorBookEngine, KIND_TEAM_SHARE} from "./IFloorBookEngine.sol";
import {FloorRewards as Rw} from "../../libraries/FloorRewards.sol";
import {IFloorBookEvents} from "../FloorBookTypes.sol";
import {FloorBookStorage as S} from "../storage/FloorBookStorage.sol";
import {FloorSqrtV2 as Q} from "../math/FloorSqrtV2.sol";
import {FloorSupplyV2 as Sup} from "../math/FloorSupplyV2.sol";
import {FloorBookWalk as W} from "./book/FloorBookWalk.sol";
import {FloorBookStore as St} from "./book/FloorBookStore.sol";
import {IFloorBuyEngine, IFloorSellEngine, TradeAfter} from "./IFloorTradeEngines.sol";
import {FloorCreditV2 as Cr} from "./FloorCreditV2.sol";
import {FloorSlotV2 as Sl} from "../FloorSlotV2.sol";
/// FLOOR v2 walk engine (stateless; DELEGATECALLed by FloorAmmV2 after the start-of-trade settle).
/// `buy` / `sell` DELEGATECALL the buy / sell engine (load, walk, commit), then credit the fees and emit `Trade`;
/// `simBuy` / `simSell` run the same code's `view` entry, which stops before the commit.
/// Chain units at the seam: tokens ×`TOKEN_SCALE`, money in quote base units.
/// Every unit that enters or leaves moves `S.layout().held`; the fee legs go to `RewardsV2`.
contract FloorBookEngine is IFloorBookEngine, IFloorBookEvents {
uint256 internal constant TOKEN_SCALE = 1e12;
/// The buy and sell engines (DELEGATECALLed; EIP-170 split), at their CREATE2 addresses.
IFloorBuyEngine internal immutable buyEngine;
IFloorSellEngine internal immutable sellEngine;
constructor(IFloorBuyEngine buy_, IFloorSellEngine sell_) {
buyEngine = buy_;
sellEngine = sell_;
}
function _launch(uint256 id) internal view returns (S.LaunchV2 storage L) {
L = S.layout().launches[id];
if (L.token == address(0)) revert IFloorAmm.UnknownLaunch();
}
// ------------------------------------------------------------------------------------------------------------ buy
/// The buy engine's `buy` in this storage; `tokens·scale < min` ⇔ `tokens <
/// ⌈min ÷ scale⌉`.
function _buy(uint256 id, uint256 gross, uint256 minTokensOut) internal returns (W.BookBuy memory, TradeAfter memory) {
uint256 minT = (minTokensOut + TOKEN_SCALE - 1) / TOKEN_SCALE;
W.BookBuy memory r =
abi.decode(_hop(address(buyEngine), abi.encodeCall(IFloorBuyEngine.buy, (id, gross, minT, true))), (W.BookBuy));
// the buy engine is at EIP-170: the committed book is read back here for what fees and events read of it
S.LaunchV2 storage L = S.layout().launches[id];
return (r, St.summary(L, St.load(L)));
}
/// A DELEGATECALL into a trade engine; its revert bubbles up unchanged.
function _hop(address m, bytes memory data) internal returns (bytes memory ret) {
bool ok;
(ok, ret) = m.delegatecall(data);
if (!ok) {
assembly ("memory-safe") {
revert(add(ret, 32), mload(ret))
}
}
}
/// The buy's Milestones are paid at once (Team / Holder by `FloorCreditV2`, Platform → `platformOwed`, $FLOOR →
/// `cutOwed`); `Trade.msPaid` logs them.
function _payMs(uint256 id, S.LaunchV2 storage L, W.BookBuy memory r) internal {
uint256[4] memory booked = r.split.booked;
if (r.split.ms == 0) return;
S.RewardsV2 storage R = S.layout().rewards[id];
Cr.team(L, R, booked[0]);
Cr.holder(L, R, booked[1]);
if (booked[2] != 0) R.platformOwed = Cr.add(R.platformOwed, booked[2]);
if (booked[3] != 0) R.cutOwed = Cr.add(R.cutOwed, booked[3]);
for (uint256 i; i < 4; ++i) {
L.msBooked[i] = Cr.add(L.msBooked[i], booked[i]);
L.msPaid[i] = Cr.add(L.msPaid[i], booked[i]);
}
}
function _buyOut(W.BookBuy memory r) internal pure returns (BuyOut memory) {
return BuyOut({
tokensOut: r.tokens * TOKEN_SCALE,
spent: r.gross - r.refund,
refund: r.refund,
sqrtAfter: uint128(r.sqrtAfter),
steps: uint8(r.steps),
budgetHit: r.budgetHit,
graduatedNow: r.graduatedNow
});
}
function buy(uint256 id, uint256 gross, uint256 minTokensOut, address beneficiary, address payer, uint8 kind)
external
payable
returns (BuyOut memory)
{
S.LaunchV2 storage L = _launch(id);
(W.BookBuy memory r, TradeAfter memory b) = _buy(id, gross, minTokensOut);
_payMs(id, L, r);
S.Layout storage s = S.layout();
s.held[L.quote] += r.gross - r.refund;
if (beneficiary != address(this)) s.held[L.token] -= r.tokens * TOKEN_SCALE;
(uint256 traderRef, uint256 creatorRef) = _creditFees(id, L, b, r.fees, _who(beneficiary));
_emitBuy(id, L, b, r, payer, beneficiary, traderRef, creatorRef, kind);
return _buyOut(r);
}
function simBuy(uint256 id, uint256 gross, address) external payable returns (BuyOut memory) {
return _simBuy(id, gross);
}
/// The buy engine's `buy` with `commit` false (run under a static frame); only the entry is `payable`.
function _simBuy(uint256 id, uint256 gross) internal returns (BuyOut memory) {
_launch(id);
bytes memory ret = _hop(address(buyEngine), abi.encodeCall(IFloorBuyEngine.buy, (id, gross, 0, false)));
W.BookBuy memory r = abi.decode(ret, (W.BookBuy));
return _buyOut(r);
}
// ------------------------------------------------------------------------------------------------------------ sell
/// The sell engine's `sell` (load, walk, re-lay, commit) in this storage.
function _sell(uint256 id, uint256 tokensIn, uint256 minQuoteOut) internal returns (W.BookSell memory, TradeAfter memory) {
if (tokensIn % TOKEN_SCALE != 0) revert IFloorAmm.BadArgument();
bytes memory ret =
_hop(address(sellEngine), abi.encodeCall(IFloorSellEngine.sell, (id, tokensIn / TOKEN_SCALE, minQuoteOut, true)));
return abi.decode(ret, (W.BookSell, TradeAfter));
}
function _sellOut(W.BookSell memory r) internal pure returns (SellOut memory) {
return SellOut({
quoteOut: r.out,
tokensTaken: (r.tokensIn - r.unfilled) * TOKEN_SCALE,
unfilled: r.unfilled * TOKEN_SCALE,
sqrtAfter: uint128(r.sqrtAfter),
steps: uint8(r.steps)
});
}
function sell(uint256 id, uint256 tokensIn, uint256 minQuoteOut, address beneficiary, address)
external
returns (SellOut memory, SellEv memory e)
{
S.LaunchV2 storage L = _launch(id);
(W.BookSell memory r, TradeAfter memory b) = _sell(id, tokensIn, minQuoteOut);
S.Layout storage s = S.layout();
s.held[L.token] += (r.tokensIn - r.unfilled) * TOKEN_SCALE;
s.held[L.quote] -= r.out;
(e.traderRef, e.creatorRef) = _creditFees(id, L, b, r.fees, _who(beneficiary));
(e.gross, e.fees, e.sqrtBefore, e.sqrtF) = (r.gross, r.fees, uint128(r.sqrtBefore), uint128(b.sqrtF));
(e.floor, e.cushion, e.sCirc, e.bidMoney) = (b.floor, b.cushion, b.sCirc, b.bidMoney);
return (_sellOut(r), e);
}
/// The sell engine's `sell` with `commit` false (FloorAmmV2's `quoteSell` runs it under a static frame).
function simSell(uint256 id, uint256 tokensIn, address) external returns (SellOut memory) {
_launch(id);
if (tokensIn % TOKEN_SCALE != 0) revert IFloorAmm.BadArgument();
bytes memory ret =
_hop(address(sellEngine), abi.encodeCall(IFloorSellEngine.sell, (id, tokensIn / TOKEN_SCALE, 0, false)));
(W.BookSell memory r,) = abi.decode(ret, (W.BookSell, TradeAfter));
return _sellOut(r);
}
// ------------------------------------------------------------------------------------------------------------ the rest
/// A Team Slot member spends its owed Team Share on an ordinary buy: place by wallet (`NotTeamMember`); `amount` 0 or
/// above the owed share = all of it (`NothingToDo` at 0); the member's trader referrers as a buy by that wallet (§42,
/// `_who(member)`);
/// the refund stays in the share; the tokens stay held, booked to the member (claim bit 256). `held` does not move.
/// Its `Trade` (kind 2) names the member as `trader` and `recipient`, as Solana's (Q-7 C, 2026-11-16).
function teamShareBuy(uint256 id, address member, uint256 amount, uint256 minTokensOut) external returns (BuyOut memory) {
S.LaunchV2 storage L = _launch(id);
S.RewardsV2 storage R = S.layout().rewards[id];
uint256 place = _placeOf(R, member);
uint256 c = R.slotOwed[place];
uint256 spend = amount == 0 || amount > c ? c : amount;
if (spend == 0) revert IFloorAmm.NothingToDo();
// debit the spend first, refund after: the buy's own Team Milestone, paid into
// this place at once (`_payMs`), stays the member's
R.slotOwed[place] = uint128(c - spend);
R.slotOwedTotal -= uint128(spend);
(W.BookBuy memory r, TradeAfter memory b) = _buy(id, spend, minTokensOut);
_payMs(id, L, r);
R.slotOwed[place] += uint128(r.refund);
R.slotOwedTotal += uint128(r.refund);
(uint256 traderRef, uint256 creatorRef) = _creditFees(id, L, b, r.fees, _who(member));
uint64 bought = R.slotBoughtOwed[place] + uint64(r.tokens);
R.slotBoughtOwed[place] = bought;
R.slotBoughtTotal += uint64(r.tokens);
_emitBuy(id, L, b, r, member, member, traderRef, creatorRef, KIND_TEAM_SHARE);
_emitShareBought(id, R, member, place, r, bought);
return _buyOut(r);
}
function _placeOf(S.RewardsV2 storage R, address member) internal view returns (uint256) {
if (member != address(0)) {
for (uint256 i; i < Rw.MAX_MEMBERS; ++i) {
if (Sl.member(R, i) == member) return i; // a bound handle place too
}
}
revert IFloorAmm.NotTeamMember();
}
function _emitShareBought(uint256 id, S.RewardsV2 storage R, address member, uint256 place, W.BookBuy memory r, uint64 bought)
internal
{
uint64 day = uint64(block.timestamp / 86_400 + 1);
bool first = R.teamShareBuyDay != day;
R.teamShareBuyDay = day;
emit IFloorAmm.TeamShareBought(
id,
member,
uint8(place),
r.gross - r.refund,
r.refund,
r.tokens * TOKEN_SCALE,
R.slotOwed[place],
uint256(bought) * TOKEN_SCALE,
day,
first
);
}
/// The donation joins F's own money (`f`) and logs `BackingCredited`. Nothing circulating: `NothingToDo` (§16: the
/// next buyer would take it, or the all-burned sweep would; Solana NobodyBacked, TON NothingToDo).
function creditBacking(uint256 id, uint256 amount) external payable {
S.LaunchV2 storage L = _launch(id);
W.Book memory bk = St.load(L);
(bool ok, uint256 sc) = Sup.circulating(L.supply, 0, W.forSale(bk), W.boughtBack(bk), L.deadTokens);
if (!ok || sc == 0) revert IFloorAmm.NothingToDo();
uint128 fAfter = Cr.add(L.f, amount);
L.f = fAfter;
S.layout().held[L.quote] += amount;
emit BackingCredited(id, msg.sender, amount, fAfter, uint64(block.number));
}
/// v2's held total in `x` + `FloorRewards`' per-wallet owed (trader referrers, failed payouts) and buckets in `x`.
function heldIn(address x) external view returns (uint256) {
return Cr.heldIn(x);
}
// ------------------------------------------------------------------------------------------------------------ fees
/// Books the fee legs; the Backing leg is already in F (`f`):
/// - team → the creator's referrers 800 / 140 / 60 bps of it, an OG tier 2,400 / 420 / 180 on a launch created inside
/// its window (`creatorRefOwed`); the rest to the members by `slotWeightPpb` (`slotOwed`, the rounding dust to F), or
/// with no weights to `creatorOwed`;
/// - platform → `trader`'s referrers 2,400 / 420 / 180 bps, an OG tier 4,000 / 700 / 300 while its window runs
/// (`FloorRewards`' per-wallet `owed.traderRef`, claim bit 8), the rest to `platformOwed`;
/// - $FLOOR → `cutOwed`; holder → `holderOwed` and the token's index (`addReward`), or F at W = 0.
/// Returns the trader referrers' part (`Trade.traderRef`; it leaves `held` for `FloorRewards.owedTotal`) and the creator
/// referrers' (`Trade.creatorRef`). `b`'s `floor` / `bidMoney` gain what the legs moved into F (the members' dust, a
/// buy's W = 0 Holder Fee).
function _creditFees(uint256 id, S.LaunchV2 storage L, TradeAfter memory b, uint256[5] memory fees, address trader)
internal
virtual
returns (uint256 toRefs, uint256 toCreatorRefs)
{
S.RewardsV2 storage R = S.layout().rewards[id];
uint256 f0 = L.f;
toCreatorRefs = Cr.team(L, R, fees[1]);
toRefs = _creditPlatform(L.quote, R, fees[2], trader);
if (fees[3] != 0) R.cutOwed = Cr.add(R.cutOwed, fees[3]);
Cr.holderFee(L, R, fees[4]);
if (toRefs != 0) S.layout().held[L.quote] -= toRefs;
f0 = L.f - f0;
(b.floor, b.bidMoney) = (b.floor + f0, b.bidMoney + f0);
}
function _creditPlatform(address q, S.RewardsV2 storage R, uint256 fee, address trader) internal returns (uint256 toRefs) {
if (fee == 0) return 0;
Rw.Store storage rs = Rw.store();
address[3] memory tr = rs.traderRefs[trader];
uint256 rest = fee;
// an unlinked trader (tier 1 = 0) has no tier at all: the whole fee is the platform's
if (tr[0] != address(0)) {
uint256[3] memory rr;
// each tier at its own referrer's rate: the OG rate while that referrer's window runs (ruling 2026-11-22)
(uint256[3] memory bps, uint256 og) = Rw.traderBps(rs, tr);
(rr, rest) = Rw.slices(fee, [true, tr[1] != address(0), tr[2] != address(0)], bps);
for (uint256 i; i < 3; ++i) {
if (rr[i] == 0) continue;
Rw.Owed storage o = rs.owed[tr[i]][q];
o.traderRef = Cr.add(o.traderRef, rr[i]);
toRefs += rr[i];
}
rs.owedTotal[q] += toRefs;
Cr.noteRefs(0, rr, og);
}
R.platformOwed = Cr.add(R.platformOwed, rest);
}
/// The referred trader: `to` when it is
/// this contract or has a link, else `tx.origin`.
function _who(address to) internal view returns (address) {
return to == address(this) || Rw.store().traderRefs[to][0] != address(0) ? to : tx.origin;
}
// ------------------------------------------------------------------------------------------------------------ events
/// `trader` = the payer, `recipient` = the beneficiary; ONE floor (`sqrtF`), `bidMoney` = F + C + K after the trade.
function _emitBuy(
uint256 id,
S.LaunchV2 storage L,
TradeAfter memory b,
W.BookBuy memory r,
address trader,
address recipient,
uint256 traderRef,
uint256 creatorRef,
uint8 kind
) internal {
emit Trade(
id,
trader,
recipient,
true,
r.gross,
r.net,
r.refund,
r.tokens * TOKEN_SCALE,
r.fees,
traderRef,
r.fromResale * TOKEN_SCALE,
r.fromFirst * TOKEN_SCALE,
0,
uint128(r.sqrtBefore),
uint128(r.sqrtAfter),
uint128(b.sqrtF),
b.floor,
b.cushion,
b.sCirc,
uint8(r.steps),
r.budgetHit,
uint64(block.number),
uint64(block.timestamp),
kind,
creatorRef,
b.bidMoney,
r.split.booked
);
Cr.emitRefs(id, trader);
// the `Graduated` event; `raised` is the Bonding money the graduation moved into F
if (r.graduatedNow) {
uint256 px = Q.priceX64(b.sqrtF) / TOKEN_SCALE;
(,, uint256 bondTokens) = St.rec(L, 0);
emit IFloorAmm.Graduated(id, px, Q.priceX64(b.sqrtP) / TOKEN_SCALE, r.bondingMoney, bondTokens * TOKEN_SCALE);
}
}
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
src/interfaces/IFloorAmm.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.24;
import {IRegistries} from "./IRegistries.sol";
/// @title FloorAmm: the FLOOR Program on EVM, one UUPS proxy per chain at one CREATE2 address.
/// @notice A launch trades from its first block against this contract (no pool, no hook, no bonding sale). The window
/// sells flat at p0; when it sells out the launch graduates to the curve on this same contract. The schedule sells the
/// inventory; the F (floor) and C (cushion) pots buy back. Every receipt number is floor-math's reference trade.
/// @dev Units: amounts are base units (`uint256`; a token is 18 decimals, 1B = 1e27); prices Q64.64 quote base per
/// token base (`...X64`); shares bps (10_000 = 100 %). A launch is `uint256 launchId`, sequential from 1 (0 = none).
/// The native coin is the quote `NATIVE = address(0)`: it comes in as `msg.value` and is never wrapped.
///
/// Nothing pauses a buy or a sell. The only pause is `createPaused`.
interface IFloorAmm is IRegistries {
// =================================================================================================================
// Types
// =================================================================================================================
/// @notice `createLaunch`'s arguments.
struct CreateParams {
uint8 presetId;
address quote; // a listed, enabled quote; NATIVE = address(0)
string name; // ≤ 32 bytes
string symbol; // ≤ 10 bytes
/// Quote in for the optional Team Buy at p0: 0 ..= the row's `creatorBuyMaxBps` of the window
/// (above it `CreatorBuyTooLarge`)
uint256 creatorBuy;
uint256 creatorBuyMinTokens; // slippage on the creator buy
/// The token's CREATE2 salt. false: `keccak256(chainid, launchId)`, an address of this chain alone. true:
/// `keccak256(creator, creatorSalt)`, the same address on every chain for the same creator (`msg.sender`) and
/// salt; the same pair twice on one chain reverts.
bool sameAddressEverywhere;
bytes32 creatorSalt;
/// The USD price of one whole quote, cents, Q64.64, declared by the creator for an unlisted quote
/// (> 0, ≤ 2¹²⁸ − 1). 0 for a listed quote.
uint256 quoteUsdCentsX64;
/// The Team Slot's rate, bps: EXACTLY the row's `teamSlotMaxBps`; any other rate, under or over, is
/// `TeamSlotRateOverMax` (INTERFACE.md "Amendment 2026-10-25 (Team Slot at the row's max)"). Every launch
/// opens its slot in `createLaunch`, after the Team Buy, the creator member 0.
uint16 teamSlotRateBps;
}
/// @notice What `buy` / `quoteBuy` return.
struct BuyResult {
uint256 tokensOut;
uint256 spent; // quote actually taken (gross; fees included)
uint256 refund; // amountIn - spent (fill-and-refund): ERC-20 pulls the whole amountIn and pays `refund` back to msg.sender (D10-A), native sent back
uint256 priceAfterX64; // where the next buy fills
bool graduatedNow; // this buy sold the window out
bool endedNow; // this buy ended the schedule
/// The buy's schedule fill stopped on its compute budget (`refund` holds the rest)
bool budgetHit;
}
/// @notice A wallet's balances in one quote, across every launch. Each field is one claim bit.
struct Owed {
uint128 creator; // bit 1
uint128 creatorRef; // bit 2
uint128 teamSlot; // bit 4
uint128 traderRef; // bit 8
uint128 holder; // always 0: the holder money is `holderBucket`, bit 16 refused
uint128 extra; // bit 32 (extra fee legs, credited to each leg's destination)
}
/// @notice A launch's market, read in one call.
struct LaunchView {
address token;
address quote;
address creator;
uint8 presetId;
uint32 presetVersion;
bytes32 presetHash;
bool graduated; // the window sold out (or the preset had no window)
uint64 createdAt; // block.timestamp
uint64 createdBlock; // the chain's own block number (L2 block on Arbitrum-family chains)
uint64 creatorUnlockAt; // createdAt + 1 day
uint256 supply; // the stored live supply (only falls)
uint256 sOut; // the circulating supply
uint256 creatorLocked; // the Team Buy still held for the creator
uint256 floor; // F
uint256 cushion; // C (every band's money + K)
uint256 p0X64;
uint256 priceX64; // the book's price
uint256 floorX64; // F / S_out, as published after the last trade
uint16 slotRateBps; // the Team Slot's rate (0 included)
}
// =================================================================================================================
// Events (slot / ts come from the log's block, not the event)
// =================================================================================================================
event LaunchCreated(
uint256 indexed launchId,
address indexed token,
address indexed quote,
address creator,
uint8 presetId,
uint32 presetVersion,
bytes32 presetHash,
uint256 p0X64,
uint256 raise,
uint256 windowTokens,
uint256 creatorBuyTokens,
uint256 createFee,
string name,
string symbol,
string uri, // `<metadataBase()>/<token as 0x + 40 lowercase hex>.json` (= IFloorToken.metadataURI)
// listed at create, the price the raise used (cents a whole quote, Q64.64), and the native create fee an
// unlisted create paid
bool listed,
uint256 quoteUsdCentsX64,
uint256 nativeCreateFee
);
/// @notice Every buy and sell (and the creator buy).
/// `fees = [skim, skimCut, creator, platform, saleCut, teamSlot, extra]`; `split = [window, schedule (the lot's
/// resale included), flat lot, flat tail]` tokens; `credits = [creator, creatorRef, teamSlot, platform, backing]`.
/// `trader` is msg.sender; `recipient` is `to` (the beneficiary: its referrers and list discount apply).
event Trade(
uint256 indexed launchId,
address indexed trader,
address indexed recipient,
bool isBuy,
uint256 quoteGross,
uint256 quoteNet,
uint256 refund,
uint256 tokens,
uint256[7] fees,
uint256 traderRef,
uint256[4] split,
uint256[5] credits,
uint256 priceBeforeX64,
uint256 priceAfterX64,
uint256 floorAfterX64,
uint256 floor,
uint256 cushion,
uint256 reserveTokens,
uint256 sOut,
uint256 floorToken, // the $FLOOR fee leg
uint256 msPlatform, // a buy's Platform Marketcap Milestone (→ the bucket; in `credits[3]`); a sell 0
uint256 msFloor, // a buy's `$FLOOR` Marketcap Milestone (→ the bucket; in `credits[3]`); a sell 0
uint256 tailPay, // a buy's pay to the tail range (part of `quoteGross`); a sell 0
uint256 tailToFloor, // of what the range kept, the floor-first part into `F`; a sell 0
uint256 tailTokens, // a sell's tokens the range took back first (chain units); a buy 0
uint256 tailFromFloor, // their pay from `F`; a buy 0
uint256 tailFromMoney, // their pay from the range's money; a buy 0
uint256 msHolder, // a buy's Holder Marketcap Milestone (→ the holder bucket); a sell 0
uint256 polOut, // a buy's tokens from the POL range (part of `tokens`, chain units); a sell 0
uint256 polPay, // their pay to the range (part of `quoteGross`); a sell 0
uint256 polTokens, // a sell's tokens the POL range bought (part of `tokens`, chain units); a buy 0
uint256 polGross, // their pay from the range's money (part of `quoteGross`); a buy 0
uint256 holderFee, // the Holder Fee (→ the holder bucket); 0 before graduation
uint256 liveBuyPriceX64, // the price the next buy pays after this trade, per chain unit
uint256 polMoney // the POL range's money after the trade (quote base units)
);
/// @notice The window sold out; the launch graduated (flat raise -> curve). Emitted by the buy that sells the window
/// out, or by `createLaunch` of a preset with no window.
event Graduated(
uint256 indexed launchId, uint256 windowPriceX64, uint256 priceX64, uint256 windowRaised, uint256 windowTokens
);
/// @notice Nobody outside; F + C moved to the platform bucket. `reason` 0 = burn, 1 = total exit, 2 = a burn
/// synced outside any trade (`burnTokens`).
event PotsSwept(uint256 indexed launchId, uint256 amount, uint8 reason);
/// @notice One per quote paid by `claim` (nothing owed: no event).
event Claimed(
address indexed wallet,
address indexed sender,
address indexed quote,
uint16 types,
uint256 creator,
uint256 creatorRef,
uint256 teamSlot,
uint256 traderRef,
uint256 holder,
uint256 extra,
uint256 amount
);
/// @notice A quote whose transfer failed inside `claim`: skipped, still owed.
event ClaimSkipped(address indexed wallet, address indexed quote, uint256 amount);
event PlatformWithdrawn(address indexed quote, address indexed to, uint256 amount, uint256 owedAfter);
/// The holder bucket withdrawn to `holderDest`.
event HolderWithdrawn(address indexed quote, address indexed to, uint256 amount, uint256 owedAfter);
/// The platform bucket's destination changed.
event TreasurySet(address indexed previous, address indexed treasury);
/// The native-coin fee an unlisted quote's create pays.
event NativeCreateFeeSet(uint256 fee);
/// The metadata host every later launch's uri is built on.
event MetadataBaseSet(string base);
event ConfigWritten(
address authority,
address pendingAuthority,
address timelock,
address referralAuthority,
bool createPaused,
address holderDest
);
event TeamSlotOpened(uint256 indexed launchId, uint16 rateBps, uint256 price);
event TeamSlotMember(
uint256 indexed launchId,
uint8 index,
bytes32 key,
uint8 kind,
uint8 state,
uint256 paid,
uint256 requested,
uint256 bought,
uint32 boughtPpm
);
/// @notice A pending handle bound to its wallet; `moved` = the handle's balances moved into `owed[wallet]`.
event HandleBound(bytes32 indexed handleId, address indexed wallet, uint256 moved);
/// @notice A bound handle's leftover `handleOwed` moved to its wallet.
event HandleOwedMoved(bytes32 indexed handleId, address indexed wallet, uint256 moved);
/// @notice A trader's referral tiers were set (one record per trader, not per quote).
event TraderRefOpened(address indexed trader, address[3] tiers);
/// @notice Governance cleared `trader`'s referral link. Credited balances stay their referrers'; the wallet may be
/// linked again.
event TraderRefCleared(address indexed trader);
/// The Team Buy split at its unlock pro rata by the Team Slot's weights (`tokens` the whole Team Buy, `members` its
/// parts by place, Σ = `tokens`); `paid` is what place 0, the creator, was paid in that call.
event CreatorBuyUnlocked(uint256 indexed launchId, address indexed creator, uint256 tokens, uint256[10] members, uint256 paid);
/// A place's booked Team Buy part paid to its payee.
event TeamBuyClaimed(uint256 indexed launchId, address indexed wallet, uint8 place, uint256 tokens);
/// @notice A sell's payout or a refund whose transfer failed is owed to `wallet` (claim bit 64); the trade settles.
event PayoutOwed(address indexed wallet, address indexed quote, uint256 amount);
/// @notice Owed payouts paid, by `claim` (bit 64, to the wallet) or `claimPayoutTo` (to the address it names).
event PayoutClaimed(address indexed wallet, address indexed sender, address indexed quote, address to, uint256 amount);
/// @notice Governance's exposure note on a quote, information only.
event QuoteCapSet(address indexed token, uint128 cap);
// =================================================================================================================
// Errors (append-only)
// =================================================================================================================
error NotAuthority();
error NotTimelock();
/// Unused; kept because errors are append-only.
error NotReferralAuthority();
error PresetInvalid();
error PresetIdNotNext();
error PresetDeleted();
error PresetDisabled();
error QuoteNotListed();
error QuoteListed();
error QuoteDisabled();
error QuoteTransferShort();
error CreatesPaused();
error CreatorBuyTooLarge();
error SlippageExceeded();
error NothingToDo();
error Overflow();
error MathFailed(uint8 code); // floor-math's MathError, by index
error UnknownLaunch();
error Locked();
error OverOwed();
error UnknownClaimType();
error TeamSlotRateOverMax();
error TeamSlotFull();
error TeamSlotPaid();
error TeamSlotExists();
error TeamSlotNoRequest();
error SellTooLarge();
error BadArgument();
error BadValue(); // msg.value is not what the call needs
error Expired(); // past `deadline`
error NativeTransferFailed();
error Reentrancy();
error NotCreator();
error HandleAlreadyBound();
error NothingToUnlock();
/// The trader's / the wallet's own signature is missing or wrong.
error BadSignature();
/// A trader's referral link is written once.
error TraderRefSet();
/// `withdrawPlatform` before a treasury is set.
error TreasuryUnset();
/// `setQuotePrice` by anyone but the price updater.
error NotPriceUpdater();
/// `createLaunch` while no metadata base is set.
error MetadataBaseUnset();
/// `setMetadataBase` with a base that is not `""` or one of `https://` `ipfs://` `ar://` with something after it,
/// printable ASCII with no space (0x21–0x7e), no trailing slash, ≤ 72 bytes.
error MetadataBaseInvalid();
/// `createLaunch` on a quote / row pair a launch cannot open on, at the quote's current price and decimals.
error QuoteRowCannotOpen(uint8 presetId, address quote);
/// The referral authority's signature is past its `deadline`.
error ReferralSigExpired();
/// The referral authority's signature is malformed, by another key, or over another chain, contract or argument.
error BadReferralSig();
/// `withdrawPlatform` would leave FloorAmm holding less of the quote than its books owe.
error ClaimsShort();
/// `withdrawHolder` while no `holderDest` is set.
error HolderDestUnset();
/// `burnTokens`' team part by a sender that is not the place's payee (place 0 the creator; 1..4 that place's member).
error RoleNotHeld();
/// `burnTokens`' team part over the place's booked Team Buy part.
error BurnTooLarge();
// =================================================================================================================
// Governance
// =================================================================================================================
/// @notice Called once, atomically by the ERC1967Proxy constructor.
function initialize(address authority, address timelock, address referralAuthority, address holderDest) external;
/// @notice Two-step authority handover.
function transferAuthority(address newAuthority) external;
function acceptAuthority() external;
/// @notice `authority` while no timelock is set, else only the timelock itself.
function setTimelock(address timelock) external;
/// @notice Pauses `createLaunch` only; no trade path reads it.
function setCreatePaused(bool paused) external;
function setReferralAuthority(address referralAuthority) external;
/// @notice The holder bucket's one destination.
function setHolderDest(address holderDest) external;
/// @notice The only way out of the holder bucket. onlyAuthority; pays only `holderDest()` (`HolderDestUnset` while
/// none). `amount == 0` = all; an empty bucket is `NothingToDo`; `ClaimsShort` while the quote is short of its books.
function withdrawHolder(address quote, uint256 amount) external returns (uint256 paid);
/// @notice The only way out of the platform bucket. onlyAuthority; pays only `treasury()` (`TreasuryUnset` while
/// none). `amount == 0` = all; an empty bucket is `NothingToDo`.
function withdrawPlatform(address quote, uint256 amount) external returns (uint256 paid);
/// @notice The treasury every platform withdrawal pays. Timelock only (`NotTimelock`); never address(0)
/// (`BadArgument`).
function setTreasury(address treasury) external;
/// @notice The native-coin create fee of an unlisted quote's create, into the native coin's platform bucket.
/// onlyAuthority.
function setNativeCreateFee(uint256 fee) external;
/// @notice The metadata host. onlyAuthority. `base` is `""` (unset) or one of `https://` `ipfs://` `ar://` with
/// something after it, printable ASCII with no space, no trailing slash, ≤ 72 bytes (else `MetadataBaseInvalid`).
/// Affects later launches only. Emits `MetadataBaseSet(base)`.
function setMetadataBase(string calldata base) external;
// =================================================================================================================
// A launch
// =================================================================================================================
/// @notice Create a launch: deploy the token (CREATE2) with 1B minted to this contract, copy the preset row for
/// life, take the create fee into the platform bucket, open the books at p0, and fill the creator buy atomically at
/// p0, locked 1 day. The creator's referrers are read from `traderRef(msg.sender)` now and fixed for life.
/// @dev Native quote: `msg.value == createFee + p.creatorBuy` exactly (the creator buy's refund is sent back).
/// ERC-20 quote: `msg.value == 0`; pulls `createFee + spent` with transferFrom. Reverts `CreatesPaused`.
/// The token's `metadataURI` is `<metadataBase()>/<token>.json` (lowercase hex address), set once;
/// `MetadataBaseUnset` while no base is set.
function createLaunch(CreateParams calldata p)
external
payable
returns (uint256 launchId, address token, uint256 creatorTokens);
/// @notice Exact-in buy with min-out and fill-and-refund. Tokens go to `to`.
/// @dev Native quote: `msg.value == amountIn`; the refund is sent back to msg.sender. ERC-20: pulls the whole `amountIn` and pays `refund` back to msg.sender (D10-A).
/// During the snipe span (`snipe_slots` blocks after the create block) the tokens are capped per transaction.
/// `deadline == 0` = none.
function buy(uint256 launchId, uint256 amountIn, uint256 minTokensOut, address to, uint256 deadline)
external
payable
returns (BuyResult memory r);
/// @notice Pay-first buy for routers: spends `quote.balanceOf(this) - accounted(quote)` (ERC-20 quote only), the
/// refund to `refundTo`. Same checks as `buy`.
function buyFromBalance(uint256 launchId, uint256 minTokensOut, address to, address refundTo, uint256 deadline)
external
returns (BuyResult memory r);
/// @notice Exact-in sell with min-out: pulls `tokensIn` from msg.sender, pays `quoteOut` to `to`.
function sell(uint256 launchId, uint256 tokensIn, uint256 minQuoteOut, address to, uint256 deadline)
external
returns (uint256 quoteOut);
/// @notice `sell` with the seller's EIP-2612 permit. The permit runs in a try: a used permit does not revert; the
/// sell then needs the allowance.
function sellWithPermit(
uint256 launchId,
uint256 tokensIn,
uint256 minQuoteOut,
address to,
uint256 deadline,
uint256 permitDeadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 quoteOut);
/// @notice Pay-first sell for routers: sells `token.balanceOf(this) - heldTokens(launchId)`.
function sellFromBalance(uint256 launchId, uint256 minQuoteOut, address to, uint256 deadline)
external
returns (uint256 quoteOut);
/// @notice After `creatorUnlockAt`, anyone may unlock the Team Buy.
/// @dev Splits the Team Buy pro rata to the Team Slot's places and books it (`CreatorBuyUnlocked`), then pays place
/// 0's part to the creator (`TeamBuyClaimed`). `tokens` = place 0's part. Nothing paid: `Locked` while locked, else
/// `NothingToUnlock`.
function unlockCreatorBuy(uint256 launchId) external returns (uint256 tokens);
// =================================================================================================================
// The Team Slot
// =================================================================================================================
/// @notice The creator requests a place for `key` (`kind` 0 wallet, 1 pending handle). With `payNow` the creator
/// pays `amount` now (native: msg.value == amount). Every cent paid is backing (F), never withdrawable.
function teamSlotAdd(uint256 launchId, bytes32 key, uint8 kind, uint256 amount, bool payNow) external payable;
/// @notice Bind a pending handle to its wallet, once. Anyone may send it: `authSig` is the referral authority's
/// EIP-191 signature over `keccak256(abi.encode("floor.amm.bindHandle.auth.v1", chainid, this, handleId, wallet,
/// quotes_, deadline))`, valid while `block.timestamp <= deadline` (`ReferralSigExpired`, `BadReferralSig`). The
/// wallet consents by sending the call, or by `walletSig`: EIP-191 over `keccak256(abi.encode(
/// "floor.amm.bindHandle.v1", chainid, this, handleId, wallet))` (ERC-1271 allowed). Moves
/// `handleOwed[handleId][q]` for each `quotes_` entry into `owed[wallet][q].teamSlot`; later credits go to the wallet.
function bindHandle(
bytes32 handleId,
address wallet,
address[] calldata quotes_,
uint256 deadline,
bytes calldata authSig,
bytes calldata walletSig
) external;
/// @notice Permissionless. Moves a bound handle's leftover `handleOwed[handleId][q]` for each `quotes_` entry into
/// `owed[wallet][q].teamSlot` of its bound wallet. `NothingToDo` while unbound; nothing left returns 0 with no
/// event; else `HandleOwedMoved`.
function moveHandleOwed(bytes32 handleId, address[] calldata quotes_) external returns (uint256 moved);
// =================================================================================================================
// Referrals
// =================================================================================================================
/// @notice A trader's 3 tiers (one record for every quote on this chain), written once. Anyone may send it:
/// `authSig` is the referral authority's EIP-191 signature over `keccak256(abi.encode("floor.amm.traderRef.auth.v1",
/// chainid, this, trader, tiers, deadline))`, valid while `block.timestamp <= deadline` (`ReferralSigExpired`,
/// `BadReferralSig`). The trader consents by sending the call, or by `traderSig`: EIP-191 over
/// `keccak256(abi.encode("floor.amm.traderRef.v1", chainid, this, trader, tiers))` (ERC-1271 allowed).
function setTraderRef(
address trader,
address[3] calldata tiers,
uint256 deadline,
bytes calldata authSig,
bytes calldata traderSig
) external;
/// @notice onlyAuthority: clear `trader`'s referral link (tiers to zero; list discount untouched). Credited balances
/// stay; `setTraderRef` may link it again. `NothingToDo` when it has no link.
function clearTraderRef(address trader) external;
// =================================================================================================================
// Claim
// =================================================================================================================
/// @notice Pay `wallet` everything it is owed of `types` in each of `quotes`; `paid[i]` is quotes[i]'s total.
/// Anyone may send it; it pays only `wallet`. Bits: 1 creator, 2 creator referral, 4 Team Slot, 8 trader referral,
/// 16 reserved (refused), 32 extra legs, 64 failed payouts; any other bit reverts `UnknownClaimType`. Nothing owed:
/// success, no transfer, no event. A quote whose transfer fails is skipped (`ClaimSkipped`) and stays owed.
/// @dev Bit 128, the Team Buy (`CLAIM_TEAM_BUY`), is per launch: for each of `launchIds` it first splits that
/// launch's Team Buy if its lock has ended (best effort, never a revert), then pays `wallet` the Team Buy part booked
/// to every Team Slot place it holds (`TeamBuyClaimed`); nothing owed is a no-op. `paid` counts quotes only.
function claim(address wallet, uint256 types, uint256[] calldata launchIds, address[] calldata quotes_)
external
returns (uint256[] memory paid);
// =================================================================================================================
// Views
// =================================================================================================================
function NATIVE() external pure returns (address);
function authority() external view returns (address);
function pendingAuthority() external view returns (address);
function timelock() external view returns (address);
function referralAuthority() external view returns (address);
function holderDest() external view returns (address);
/// @notice Where `withdrawPlatform` pays (0 until set).
function treasury() external view returns (address);
/// @notice The native-coin create fee an unlisted quote's create pays.
function nativeCreateFee() external view returns (uint256);
/// @notice The metadata host (`""` until set: creates refuse `MetadataBaseUnset`).
function metadataBase() external view returns (string memory);
function createPaused() external view returns (bool);
/// @notice The last launch id (ids are 1..launchCount()).
function launchCount() external view returns (uint256);
function launchQuote(uint256 launchId) external view returns (address);
function launchToken(uint256 launchId) external view returns (address);
/// @notice 0 for a token that is not a FLOOR Program launch on this chain.
function launchOf(address token) external view returns (uint256 launchId);
function launchState(uint256 launchId) external view returns (LaunchView memory);
/// @notice What a buy of `amountIn` would do now for beneficiary `to` (its list discount, this block's snipe cap).
function quoteBuy(uint256 launchId, uint256 amountIn, address to) external view returns (BuyResult memory r);
/// @notice What a sell of `tokensIn` would pay now for beneficiary `to`. Reverts `SellTooLarge` past S_out.
function quoteSell(uint256 launchId, uint256 tokensIn, address to) external view returns (uint256 quoteOut);
/// @notice The per-wallet owed view: one quote / many quotes.
function owedOf(address wallet, address quote) external view returns (Owed memory);
function owedOfMany(address wallet, address[] calldata quotes_) external view returns (Owed[] memory);
/// @notice A pending handle's Team Slot balance in `quote` (until `bindHandle`).
function handleOwed(bytes32 handleId, address quote) external view returns (uint256);
function handleWallet(bytes32 handleId) external view returns (address);
function traderRef(address trader) external view returns (address[3] memory tiers);
/// @notice The platform bucket in `quote` (one per quote, across launches).
function platformOwed(address quote) external view returns (uint256);
/// @notice Every quote unit this contract owes or holds as pots in `quote`: Σ launches (F + C) + Σ owed +
/// Σ handleOwed + platformOwed. Invariant: `balance(quote) >= accounted(quote)`.
function accounted(address quote) external view returns (uint256);
/// @notice The holder bucket in `quote` (one per quote, across launches).
function holderBucket(address quote) external view returns (uint256);
// =================================================================================================================
// Payouts and risk
// =================================================================================================================
/// @notice Claim bit 64: the caller's owed payouts in `quote` to any address it names. Nothing owed: 0, no
/// transfer, no event.
function claimPayoutTo(address quote, address to) external returns (uint256 paid);
/// @notice What `wallet` is owed of `quote` from payouts whose transfer failed (claim bit 64).
function payoutOwed(address wallet, address quote) external view returns (uint256);
/// @notice What the program accounts for in `token`, what it holds, governance's cap note, short arrivals, failed
/// payouts and the last failure's block.
function quoteRisk(address token)
external
view
returns (uint256 accounted_, uint256 held, uint128 cap, uint32 shortIns, uint32 failedOuts, uint64 lastFailBlock);
/// @notice onlyAuthority. Governance's exposure note on a quote, in its base units. Information only.
function setQuoteCap(address token, uint128 cap) external;
/// @notice floor-math's `spec_ok` on a preset row (the checks of `addPreset` / `updatePreset`). Never reverts on a
/// bad row: `false`.
function checkPreset(bytes calldata spec) external view returns (bool ok);
/// @notice The $FLOOR fee leg (`Trade.floorToken`) accrued in `quote`, monotonic. It sits inside the platform bucket
/// (`platformOwed`), counted apart; there is no separate withdrawal.
function floorTokenAccrued(address quote) external view returns (uint256);
/// @notice The token address a create with `sameAddressEverywhere = true` would deploy for `creator` and
/// `creatorSalt`: `Clones.predictDeterministicAddress(tokenImpl(), keccak256(abi.encode(creator, creatorSalt)),
/// address(this))`. Not for the default salt, which depends on the next launch id.
function predictToken(address creator, bytes32 creatorSalt) external view returns (address);
// =================================================================================================================
// Team Share buyback
// =================================================================================================================
/// @notice A Team Slot member spent `spent` of its Team Share of `launchId` on that launch's token at the normal
/// price (the buy's own `Trade` precedes it; `refund` went back to the Team Share); `tokens` are booked to it
/// (`boughtOwed` after) and paid by the claim's bit 256. `day` = `⌊block.timestamp ÷ 86,400⌋ + 1`; `firstToday` =
/// the launch's first buyback of that UTC day.
event TeamShareBought(
uint256 indexed launchId,
address indexed member,
uint8 place,
uint256 spent,
uint256 refund,
uint256 tokens,
uint256 shareLeft,
uint256 boughtOwed,
uint64 day,
bool firstToday
);
/// @notice The tokens a wallet bought with its Team Share, paid by the claim (bit 256).
event TeamShareBoughtClaimed(uint256 indexed launchId, address indexed wallet, uint256 tokens);
/// @notice `teamShareBuy` by a wallet holding no member place in the launch's Team Slot.
error NotTeamMember();
/// @notice Spend up to `amount` (0 = all) of the caller's claimable Team Share of `launchId` on its token, as
/// `buy(…, to = caller)` would (the caller's trader referrers and list discount apply).
function teamShareBuy(uint256 launchId, uint256 amount, uint256 minTokensOut, uint256 deadline)
external
returns (BuyResult memory);
/// @notice `wallet`'s claimable Team Share of `launchId` (quote base units), its bought tokens owed (chain units)
/// and the launch's last buyback day (`⌊ts ÷ 86,400⌋ + 1`, 0 = never).
function teamShareOf(uint256 launchId, address wallet)
external
view
returns (uint256 claimable, uint256 boughtOwed, uint64 lastDay);
}
src/interfaces/IRegistries.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.24;
/// @title The FLOOR Program's governance registries on EVM: presets and quotes.
/// @notice Storage written by `authority`; rows change with no redeploy or upgrade. A launch copies its preset row for
/// life at create: a later `updatePreset` never changes a live launch.
interface IRegistries {
// ---- types -----------------------------------------------------------------------------------------------------
/// @notice A preset row as stored. `spec` is floor-math's `PresetSpec::to_bytes` (`PRESET_LEN` bytes,
/// little-endian), the same bytes as Solana's `PresetRow.spec`. Its byte 0 is `id`.
struct PresetRow {
uint8 id;
bool enabled;
bool deleted;
uint32 rowVersion;
bytes32 specHash; // keccak256(spec): what `LaunchCreated.presetHash` carries
bytes spec;
}
/// @notice A quote as listed. `token == NATIVE` (address(0)) is the chain's native coin (ETH, BNB, HYPE, ...).
struct QuoteEntry {
bool listed; // true once added; a quote is never removed, only disabled
bool enabled;
uint8 decimals; // read from the token at `addQuote` (18 for NATIVE)
uint256 createFee; // the create fee in quote base units
uint256 usdCentsX64; // USD price of one whole quote unit, in cents, Q64.64
uint64 launches; // launches created in this quote
uint64 updatedAt; // block.timestamp of the last write
}
// ---- events ----------------------------------------------------------------------------------------------------
/// @notice Every preset write (add / update / enable / delete). Mirrors Solana's `PresetWritten`.
event PresetWritten(uint8 indexed id, uint32 rowVersion, bool enabled, bool deleted);
/// @notice `addQuote` / `updateQuote`. Mirrors Solana's `QuoteWritten`.
event QuoteWritten(address indexed token, bool enabled, uint256 createFee, uint256 usdCentsX64);
/// @notice A new price updater was set (address(0) = none).
event PriceUpdaterSet(address indexed previous, address indexed updater);
// ---- governance writes (onlyAuthority) -------------------------------------------------------------------------
/// @notice Append a preset. `id` must equal `nextPresetId()` (starts at 1, id 0 reserved; `PresetIdNotNext`) and
/// `spec[0] == id`. Reverts `PresetInvalid` unless floor-math's `spec_ok` holds.
/// @dev An extra leg's 32-byte destination is a right-aligned EVM address (top 12 bytes zero), else PresetInvalid.
function addPreset(uint8 id, bytes calldata spec) external;
/// @notice Replace a row's spec (`rowVersion += 1`). Live launches keep their copy. Same checks as `addPreset`.
function updatePreset(uint8 id, bytes calldata spec) external;
function setPresetEnabled(uint8 id, bool enabled) external;
/// @notice Mark a row deleted. The row stays so the id is never reused.
function deletePreset(uint8 id) external;
/// @notice List a quote. Reverts `QuoteListed` if already listed. `token == NATIVE` lists the native coin.
/// @dev Fee-on-transfer or rebasing tokens must not be listed. Every pull checks the balance delta and reverts
/// `QuoteTransferShort` if short.
function addQuote(address token, uint256 createFee, uint256 usdCentsX64) external;
function updateQuote(address token, bool enabled, uint256 createFee, uint256 usdCentsX64) external;
/// @notice Set the price updater; address(0) = none. onlyAuthority (`NotAuthority`).
function setPriceUpdater(address updater) external;
/// @notice Price updater only (`NotPriceUpdater`): re-price a listed quote (`QuoteNotListed`); the price must be
/// `> 0` and `<= 2^128 - 1` (`BadArgument`). Writes `usdCentsX64` and `updatedAt` and emits `QuoteWritten`. Live
/// launches keep their copied price.
function setQuotePrice(address token, uint256 usdCentsX64) external;
// ---- views -----------------------------------------------------------------------------------------------------
function nextPresetId() external view returns (uint8);
function presetRow(uint8 id) external view returns (PresetRow memory);
function quoteEntry(address token) external view returns (QuoteEntry memory);
/// @notice Who may `setQuotePrice` (address(0) = none).
function priceUpdater() external view returns (address);
/// @notice Every listed quote, in listing order (enabled or not).
function quotes() external view returns (address[] memory);
}
src/libraries/FloorFixed.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.26;
/// @title FloorFixed — the math crate's errors and fixed-point `log2` / `exp2`, bit for bit
/// @notice A bit-exact port of the math crate's fixed-point `log2` / `exp2` and its errors.
library FloorFixed {
uint256 private constant U128_MAX = type(uint128).max;
uint256 private constant ONE_127 = 1 << 127;
/// `MathError::VaultShareOutOfRange` — vault share outside 1..=10,000.
error VaultShareOutOfRange();
/// `MathError::Zero` — a zero backing, supply or ratio where one is divided by.
error Zero();
/// `MathError::Overflow` — an intermediate or a result does not fit.
error Overflow();
/// `K[i-1] = floor(2^(2^-i) · 2^127)` for `i = 1..=64`, 16 bytes each. Generated; never edit by hand.
bytes private constant K =
hex"b504f333f9de6484597d89b3754abe9f9837f0518db8a96f46ad23182e42f6f6"
hex"8b95c1e3ea8bd6e6fbe4628758a53c9085aac367cc487b14c5c95b8c2154c1b2"
hex"82cd8698ac2ba1d73e2a475b46520bff8164d1f3bc0307737be56527bd14def4"
hex"80b1ed4fd999ab6c25335719b6e6fd208058d7d2d5e5f6b094d589f608ee4aa2"
hex"802c6436d0e04f50ff8ce94a6797b3ce8016302f174676283690dfe44d11d008"
hex"800b179c82028fd0945e54e2ae18f2f080058baf7fee3b5d1c718b38e549cb93"
hex"8002c5d00fdcfcb6b6566a58c048be1f800162e61bed4a48e84c2e1a463473d9"
hex"8000b17292f702a3aa22beacca949013800058b92abbae02030c5fa5256f41fe"
hex"80002c5c8dade4d71776c0f4dbea67d68000162e44eaf636526be456600bdbe4"
hex"80000b1721fa7c188307016c1cd4e8b68000058b90de7e4cecfc487503488bb1"
hex"800002c5c8678f36cbfce50a6de60b1480000162e431db9f80b2347b5d62e516"
hex"800000b1721872d0c7b08cf1e011415280000058b90c1aa8a5c3736cb77e8dff"
hex"8000002c5c8605a4635f2efc2362d978800000162e4300e635cf4a109e3939bd"
hex"8000000b17217ff81bef9c551590cf83800000058b90bfdd4e39cd52c0cfa27c"
hex"80000002c5c85fe6f72d669e0e76e4118000000162e42ff18f9ad35186d0df28"
hex"80000000b17217f84cce71aa0dcfffe78000000058b90bfc07a77ad56ed22aaa"
hex"800000002c5c85fdfc23cdead40da8d680000000162e42fefc25eb1571853a66"
hex"800000000b17217f7d97f692baacded580000000058b90bfbead3b8b5dd254d7"
hex"8000000002c5c85fdf4eedd62f084e67800000000162e42fefa58aef378bf586"
hex"8000000000b17217f7d24a78a3c7ef02800000000058b90bfbe9067c93e474a6"
hex"80000000002c5c85fdf47b8e5a72599f8000000000162e42fefa3bdb315934a2"
hex"80000000000b17217f7d1d7299b49c468000000000058b90bfbe8e9a8d1c4ea0"
hex"800000000002c5c85fdf4745969ea76f80000000000162e42fefa3a0df5373bf"
hex"800000000000b17217f7d1cff4aac1e180000000000058b90bfbe8e7db95a2f1"
hex"8000000000002c5c85fdf473e61ae1f8800000000000162e42fefa39f121751c"
hex"8000000000000b17217f7d1cf815bb96800000000000058b90bfbe8e7bec1e0d"
hex"80000000000002c5c85fdf473dee5f178000000000000162e42fefa39ef5438f"
hex"80000000000000b17217f7d1cf7a26c88000000000000058b90bfbe8e7bcf4a4"
hex"800000000000002c5c85fdf473de72a280000000000000162e42fefa39ef3765"
hex"800000000000000b17217f7d1cf79b3780000000000000058b90bfbe8e7bcd7d"
hex"8000000000000002c5c85fdf473de6b6800000000000000162e42fefa39ef359"
hex"8000000000000000b17217f7d1cf79ac800000000000000058b90bfbe8e7bcd6";
function _u128(uint256 v) private pure returns (uint256) {
if (v > U128_MAX) revert Overflow();
return v;
}
/// `log2(n)` for an integer `1 ≤ n < 2^128`, Q64.64, rounded down (`fixed::log2_x64`).
function log2X64(uint256 n) internal pure returns (uint256) {
if (n == 0) revert Zero();
_u128(n);
uint256 msb = _msb(n);
// the mantissa n ÷ 2^msb in [1, 2) as Q1.127
uint256 m = n << (127 - msb);
uint256 frac;
// 64 squarings, branchless, four a pass: the digit `b` is m²'s top bit; m = m² >> (127 + b)
assembly ("memory-safe") {
for { let i := 64 } i {} {
i := sub(i, 4)
let p := mul(m, m)
let b := shr(255, p)
frac := or(frac, shl(add(i, 3), b))
m := shr(add(127, b), p)
p := mul(m, m)
b := shr(255, p)
frac := or(frac, shl(add(i, 2), b))
m := shr(add(127, b), p)
p := mul(m, m)
b := shr(255, p)
frac := or(frac, shl(add(i, 1), b))
m := shr(add(127, b), p)
p := mul(m, m)
b := shr(255, p)
frac := or(frac, shl(i, b))
m := shr(add(127, b), p)
}
}
return (msb << 64) | frac;
}
/// `2^y` for `y` in Q64.64 (`y < 2^128`), Q64.64, rounded down (`fixed::exp2_x64`); reverts
/// `Overflow` for `y ≥ 64`.
function exp2X64(uint256 y) internal pure returns (uint256) {
_u128(y);
uint256 intPart = y >> 64;
if (intPart >= 64) revert Overflow();
bytes memory k = K;
uint256 r = ONE_127;
// The products in order (bit 63 of the fraction first), four bits a pass; the table's copy is released after
// (this call's last allocation), so repeated calls do not grow memory
assembly ("memory-safe") {
let p := add(k, 32)
for { let bit := shl(63, 1) } bit {
bit := shr(4, bit)
p := add(p, 64)
} {
if and(y, bit) { r := shr(127, mul(r, shr(128, mload(p)))) }
if and(y, shr(1, bit)) { r := shr(127, mul(r, shr(128, mload(add(p, 16))))) }
if and(y, shr(2, bit)) { r := shr(127, mul(r, shr(128, mload(add(p, 32))))) }
if and(y, shr(3, bit)) { r := shr(127, mul(r, shr(128, mload(add(p, 48))))) }
}
mstore(0x40, k)
}
return r >> (63 - intPart);
}
/// The most significant bit of `n > 0` (0 for `n = 0`), by eight branchless halvings.
function _msb(uint256 n) internal pure returns (uint256 r) {
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, n))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, n))))
r := or(r, shl(5, lt(0xffffffff, shr(r, n))))
r := or(r, shl(4, lt(0xffff, shr(r, n))))
r := or(r, shl(3, lt(0xff, shr(r, n))))
r := or(r, shl(2, lt(0xf, shr(r, n))))
r := or(r, shl(1, lt(0x3, shr(r, n))))
r := or(r, lt(0x1, shr(r, n)))
}
}
}
src/libraries/FloorRewards.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.24;
/// @title FloorRewards — the shared rewards store: owed balances, buckets, trader links, handles, Team Slot weights
/// @notice What a wallet is owed in a quote:
///
/// - One balance per wallet per quote, `owed[wallet][quote]`, credited on the trade; a trade never pays a payee directly.
/// - Referrer slices of the Platform fee (24 / 4.2 / 1.8 %, 30 % in all) and of the whole Team Share (8 / 1.4 / 0.6 %, 10 %
/// in all), split 80 / 14 / 6 and rounded down; an OG User's tier pays more while its window runs (ruling 2026-11-22).
/// - The platform bucket and the holder bucket per quote, withdrawn by governance alone.
/// - The layout is append-only.
///
/// Storage is ERC-7201 namespaced (`floor.rewards`), run by DELEGATECALL in the proxy's storage.
library FloorRewards {
// ------------------------------------------------------------------------------------------------------------ constants
uint256 internal constant BPS = 10_000;
/// The trader's referrers' slices of the Platform fee, bps of it (tiers 1–3): 30 % split 80 / 14 / 6 (floor-math
/// `team::TRADER_REF_BPS`).
uint256 internal constant TRADER_REF_BPS_1 = 2_400;
uint256 internal constant TRADER_REF_BPS_2 = 420;
uint256 internal constant TRADER_REF_BPS_3 = 180;
/// The creator's referrers' slices of the whole Team Share, bps of it: 10 % split 80 / 14 / 6 (`team::CREATOR_REF_BPS`).
uint256 internal constant CREATOR_REF_BPS_1 = 800;
uint256 internal constant CREATOR_REF_BPS_2 = 140;
uint256 internal constant CREATOR_REF_BPS_3 = 60;
/// An OG User's tier while its window runs (ruling 2026-11-22; `team::TRADER_REF_OG_BPS` / `CREATOR_REF_OG_BPS`):
/// the trader's referrers 50 %, the creator's 30 % (only on a launch created inside the window), each 80 / 14 / 6.
uint256 internal constant TRADER_REF_OG_BPS_1 = 4_000;
uint256 internal constant TRADER_REF_OG_BPS_2 = 700;
uint256 internal constant TRADER_REF_OG_BPS_3 = 300;
uint256 internal constant CREATOR_REF_OG_BPS_1 = 2_400;
uint256 internal constant CREATOR_REF_OG_BPS_2 = 420;
uint256 internal constant CREATOR_REF_OG_BPS_3 = 180;
/// An OG window: 183 days from its set (`team::OG_WINDOW_SECS`); at most `OG_MAX` live per chain (`team::OG_MAX`).
uint256 internal constant OG_WINDOW_SECS = 15_811_200;
uint16 internal constant OG_MAX = 100;
/// At most 10 members (the creator is member 0); weights in parts per billion; β in ppm.
uint256 internal constant MAX_MEMBERS = 10;
uint256 internal constant WEIGHT_ONE = 1_000_000_000;
uint256 internal constant PPM = 1_000_000;
/// The hard cap on any Team Slot rate (the row's `team_slot_max_bps` is the live limit).
uint16 internal constant TEAM_SLOT_HARD_MAX_BPS = 9_500;
uint256 internal constant MAX_EXTRA_LEGS = 4;
/// The claim's type bits (bit 32: the extra legs).
uint256 internal constant CLAIM_CREATOR = 1;
uint256 internal constant CLAIM_CREATOR_REF = 2;
uint256 internal constant CLAIM_TEAM_SLOT = 4;
uint256 internal constant CLAIM_TRADER_REF = 8;
/// Reserved: outside `CLAIM_ALL` and refused (`UnknownClaimType`); never reused.
uint256 internal constant RESERVED_HOLDER_BIT = 16;
uint256 internal constant CLAIM_EXTRA = 32;
/// A payout whose transfer failed, owed per wallet per quote in `payoutOwed`.
uint256 internal constant CLAIM_PAYOUT = 64;
uint256 internal constant CLAIM_ALL = 111; // 127 less the reserved bit 16
/// Member places.
uint8 internal constant EMPTY = 0;
uint8 internal constant REQUESTED = 1;
uint8 internal constant MEMBER = 2;
/// keccak256(abi.encode(uint256(keccak256("floor.rewards.v1")) - 1)) & ~bytes32(uint256(0xff)) (ERC-7201)
bytes32 internal constant STORE_SLOT = 0xedc53fde0f7f214d9d2d6d847548f53f38fc623e1b962cd4902a5c9c251b0d00;
// ------------------------------------------------------------------------------------------------------------ storage
/// What one wallet is owed in one quote, by claim type; one record per wallet per quote across every launch.
struct Owed {
uint128 creator; // bit 1
uint128 creatorRef; // bit 2
uint128 teamSlot; // bit 4
uint128 traderRef; // bit 8
uint128 holder; // bit 16
uint128 extra; // bit 32
}
/// A Team Slot place: a wallet (`key`) or a pending social handle (`handle`, `key` 0).
struct Member {
address key;
uint8 state; // EMPTY / REQUESTED / MEMBER
bytes32 handle;
uint128 paid; // what it paid in: backing, never withdrawable
uint128 requested; // a request's amount, held in `reserved` until paid
}
/// A launch's Team Slot. `open` is whether the slot exists, apart from its rate (0 ..= the row's max). The trade reads
/// `rateBps`, `boughtPpm`, `open` and `weights`, then a member's key only when its weight is non-zero.
struct Slot {
uint16 rateBps;
uint32 boughtPpm; // β = bought ÷ price, ppm, rounded down
bool free; // `$FLOOR`'s slot: free to the deployer
bool open; // the slot exists (set once by `initSlot`)
uint128 price; // quote base units for 100 % of the rate
uint128 bought; // Σ paid
uint128 reserved; // Σ open requests
uint32[10] weights; // ⌊paid_i · 10⁹ ÷ bought⌋
Member[10] members;
}
/// What the rewards side keeps of a launch, written once at create (copied from the preset row and the creator's link).
struct LaunchRewards {
address creator;
address quote;
address[3] creatorRefs; // the creator's own referrer tiers at create
address[4] extraDest; // the preset row's extra legs' destinations
}
struct Store {
mapping(address wallet => mapping(address quote => Owed)) owed;
/// Σ every `owed` and `handleOwed` per quote.
mapping(address quote => uint256) owedTotal;
/// The platform bucket per quote, withdrawn by governance only.
mapping(address quote => uint256) bucket;
/// The trader's referrers, tiers 1–3, written once when the trader is linked.
mapping(address trader => address[3]) traderRefs;
mapping(bytes32 launchId => LaunchRewards) launches;
mapping(bytes32 launchId => Slot) slots;
/// A pending handle's Team Slot earnings until it is bound to a wallet.
mapping(bytes32 handle => mapping(address quote => uint256)) handleOwed;
mapping(bytes32 handle => address) handleWallet;
/// The holder bucket's one destination, set by governance, read at `withdrawHolder`; 0 = refused.
address holderPayout;
/// The `$FLOOR` leg accrued in `quote`, monotonic. The money sits inside `bucket[quote]`; this only counts it.
mapping(address quote => uint256) floorTokenAccrued;
/// Payouts owed after a failed transfer (bit 64), counted in `owedTotal`.
mapping(address wallet => mapping(address quote => uint256)) payoutOwed;
/// The holder bucket per quote, withdrawn by governance to `holderPayout`; counted in `_owedIn`.
/// `Owed.holder` stays in the layout, always 0.
mapping(address quote => uint256) holderBucket;
// ---- Team Share buyback ----
/// Each wallet's Team Share per launch, tagged with its claim epoch in the quote; a bit-4 claim bumps the epoch,
/// so an older entry reads 0.
mapping(bytes32 launchId => mapping(address wallet => TeamShareEntry)) teamShare;
mapping(address wallet => mapping(address quote => uint64)) teamShareEpoch;
/// Launch tokens a wallet bought with its Team Share, held by the program, paid by claim bit 128; and their sum.
mapping(bytes32 launchId => mapping(address wallet => uint256)) teamShareBought;
mapping(bytes32 launchId => uint256) teamShareBoughtTotal;
/// The launch's last buyback's UTC day, `⌊block.timestamp ÷ 86,400⌋ + 1` (0 = never).
mapping(bytes32 launchId => uint64) teamShareDay;
// ---- OG Users (ruling 2026-11-22; APPENDED: no earlier member moves) ----
/// A referrer's one OG window `[from, until)`, set once by the referral authority; a revoke lowers `until`.
mapping(address referrer => OgWindow) og;
/// The live windows (≤ `OG_MAX`; a revoke frees one) and every set ever.
uint16 ogCount;
uint64 ogTotal;
}
/// One referrer's OG window (unix seconds); `from` 0 = none.
struct OgWindow {
uint64 from;
uint64 until;
bool revoked;
}
/// One wallet's Team Share on one launch.
struct TeamShareEntry {
uint128 amount;
uint64 epoch;
}
// ------------------------------------------------------------------------------------------------------------ events
/// One per quote paid: `amount` = the sum of the type columns, one transfer.
event Claimed(
address indexed wallet,
address indexed sender,
address indexed quote,
uint16 types,
uint256 creator,
uint256 creatorRef,
uint256 teamSlot,
uint256 traderRef,
uint256 holder,
uint256 extra,
uint256 amount
);
/// A quote whose transfer refused: nothing paid, `amount` stays owed.
event ClaimSkipped(address indexed wallet, address indexed quote, uint256 amount);
event TeamSlotOpened(uint256 indexed launchId, uint16 rateBps, uint256 price);
event TeamSlotMember(
uint256 indexed launchId,
uint8 index,
bytes32 key,
uint8 kind,
uint8 state,
uint256 paid,
uint256 requested,
uint256 bought,
uint32 boughtPpm
);
event HandleBound(bytes32 indexed handleId, address indexed wallet, uint256 moved);
/// A payout whose transfer failed is owed to `wallet` instead (bit 64); `PayoutClaimed` when it is paid.
event PayoutOwed(address indexed wallet, address indexed quote, uint256 amount);
event PayoutClaimed(address indexed wallet, address indexed sender, address indexed quote, address to, uint256 amount);
// ------------------------------------------------------------------------------------------------------------ errors
error UnknownClaimType(uint256 types);
error Overflow();
error SlotRateOverMax();
error SlotExists();
error NoTeamSlot();
error NotCreator();
error TeamSlotFull();
error BadMember();
error NotRequested();
error TeamSlotPaidMember();
error HandleAlreadyBound();
error ZeroAmount();
// ------------------------------------------------------------------------------------------------------------ store
function store() internal pure returns (Store storage s) {
bytes32 slot = STORE_SLOT;
// memory-safe: it only names a slot
assembly ("memory-safe") {
s.slot := slot
}
}
// ------------------------------------------------------------------------------------------------------------ math
// Twins of `floor-math::fees`.
/// `⌊leg · bps ÷ 10⁴⌋` (`fees::part`): the splits of a fee and the `$FLOOR` cut.
function part(uint256 leg, uint256 bps) internal pure returns (uint256) {
return mulDiv(leg, bps, BPS);
}
/// The trader's referrers' bps by tier: the OG rate where that tier's own referrer's window runs now
/// (`team::platform_legs_og`); `og` bits 0–2 the tiers paid so. Absent tiers read nothing.
function traderBps(Store storage rs, address[3] memory tr) internal view returns (uint256[3] memory bps, uint256 og) {
bps = [TRADER_REF_BPS_1, TRADER_REF_BPS_2, TRADER_REF_BPS_3];
uint256[3] memory hi = [TRADER_REF_OG_BPS_1, TRADER_REF_OG_BPS_2, TRADER_REF_OG_BPS_3];
for (uint256 i; i < 3; ++i) {
if (tr[i] != address(0) && block.timestamp < rs.og[tr[i]].until) (bps[i], og) = (hi[i], og | (1 << i));
}
}
/// The creator's referrers' bps by tier: the OG rate only on a launch created inside that tier's window, while it runs
/// (`team::og_launch`, new launches only); `og` bits 3–5 the tiers paid so.
function creatorBps(Store storage rs, address[3] memory cr, uint256 createdAt)
internal
view
returns (uint256[3] memory bps, uint256 og)
{
bps = [CREATOR_REF_BPS_1, CREATOR_REF_BPS_2, CREATOR_REF_BPS_3];
uint256[3] memory hi = [CREATOR_REF_OG_BPS_1, CREATOR_REF_OG_BPS_2, CREATOR_REF_OG_BPS_3];
for (uint256 i; i < 3; ++i) {
if (cr[i] == address(0)) continue;
OgWindow storage w = rs.og[cr[i]];
(uint256 from, uint256 until) = (w.from, w.until);
if (from != 0 && from <= createdAt && createdAt < until && block.timestamp < until) {
(bps[i], og) = (hi[i], og | (1 << (i + 3)));
}
}
}
/// `fees::slices`: a gross `fee`'s slice for each tier present, each `part` and bounded by what is left.
function slices(uint256 fee, bool[3] memory present, uint256[3] memory bps)
internal
pure
returns (uint256[3] memory out, uint256 left)
{
left = fee;
for (uint256 i; i < 3; ++i) {
if (!present[i] || bps[i] == 0) continue;
uint256 v = _min(part(fee, bps[i]), left);
out[i] = v;
left -= v;
}
}
/// Each member's weight, ppb of `bought`, rounded down (never summing past 10⁹).
function weights(uint256[10] memory paid, uint256 bought) internal pure returns (uint32[10] memory w) {
if (bought == 0) return w;
// the members' payments never sum past what is bought
uint256 total;
for (uint256 i; i < MAX_MEMBERS; ++i) total += paid[i];
if (total > bought) revert Overflow();
for (uint256 i; i < MAX_MEMBERS; ++i) {
w[i] = uint32(mulDiv(_min(paid[i], bought), WEIGHT_ONE, bought));
}
}
/// A free slot's weights, `share_i ÷ Σ shares` in ppb, rounded down; `[10⁹, 0, …, 0]` while Σ shares is 0.
/// Σ past u128 is `Overflow`.
function slotWeights(uint256[10] memory shares) internal pure returns (uint32[10] memory w) {
uint256 total;
for (uint256 i; i < MAX_MEMBERS; ++i) total += shares[i];
if (total > type(uint128).max) revert Overflow();
if (total == 0) {
w[0] = uint32(WEIGHT_ONE);
return w;
}
return weights(shares, total);
}
/// Each member's `⌊amount · w_i ÷ 10⁹⌋`, and the dust.
function splitMembers(uint256 amount, uint32[10] memory w) internal pure returns (uint256[10] memory parts, uint256 dust) {
uint256 given;
for (uint256 i; i < MAX_MEMBERS; ++i) {
uint256 wi = w[i] > WEIGHT_ONE ? WEIGHT_ONE : w[i];
if (wi == 0) continue; // a zero weight is a zero part
// never past the amount, whatever the weights
parts[i] = _min(mulDiv(amount, wi, WEIGHT_ONE), amount - given);
given += parts[i];
}
dust = amount > given ? amount - given : 0;
}
// ------------------------------------------------------------------------------------------------------------ buckets
/// Credit the platform bucket (the `$FLOOR` cuts and the create fee).
function creditBucket(address quote, uint256 amount) internal {
if (amount > 0) store().bucket[quote] += amount;
}
/// Holder-bucket withdrawal bookkeeping (the caller gates and transfers).
function debitHolderBucket(address quote, uint256 amount) internal {
store().holderBucket[quote] -= amount;
}
/// Platform-bucket withdrawal bookkeeping (the caller gates and transfers); `floorTokenAccrued` never falls.
function debitBucket(address quote, uint256 amount) internal {
store().bucket[quote] -= amount;
}
// ------------------------------------------------------------------------------------------------------------ claim
/// The claim. Anyone may send it; it pays only `wallet`. For each quote: the sum of the `types` columns of
/// `owed[wallet][quote]`, in one transfer, and one `Claimed`.
/// - Nothing owed is a success: `paid[i]` 0, no transfer, no event.
/// - A quote whose transfer refuses is skipped: `paid[i]` 0, the amount stays owed, `ClaimSkipped`.
/// - A quote named twice pays once.
/// - A bit outside `CLAIM_ALL` is refused (`UnknownClaimType`).
function claim(address wallet, uint256 types, address[] calldata quotes)
internal
returns (uint256[] memory paid)
{
if (types & ~CLAIM_ALL != 0) revert UnknownClaimType(types);
Store storage s = store();
paid = new uint256[](quotes.length);
for (uint256 i; i < quotes.length; ++i) {
address q = quotes[i];
Owed storage o = s.owed[wallet][q];
uint256[6] memory c;
if (types & CLAIM_CREATOR != 0) (c[0], o.creator) = (o.creator, 0);
if (types & CLAIM_CREATOR_REF != 0) (c[1], o.creatorRef) = (o.creatorRef, 0);
if (types & CLAIM_TEAM_SLOT != 0) (c[2], o.teamSlot) = (o.teamSlot, 0);
if (types & CLAIM_TRADER_REF != 0) (c[3], o.traderRef) = (o.traderRef, 0);
if (types & CLAIM_EXTRA != 0) (c[5], o.extra) = (o.extra, 0);
if (types & CLAIM_PAYOUT != 0) paid[i] = claimPayout(wallet, q, wallet);
uint256 amount = c[0] + c[1] + c[2] + c[3] + c[4] + c[5];
if (amount == 0) continue;
s.owedTotal[q] -= amount;
if (_transfer(q, wallet, amount)) {
paid[i] += amount;
// the Team Share is paid whole: every per-launch entry of this epoch is spent
if (c[2] != 0) ++s.teamShareEpoch[wallet][q];
emit Claimed(wallet, msg.sender, q, uint16(types), c[0], c[1], c[2], c[3], c[4], c[5], amount);
} else {
// restore by ADDING: a credit that landed meanwhile is kept
o.creator = _add128(o.creator, c[0]);
o.creatorRef = _add128(o.creatorRef, c[1]);
o.teamSlot = _add128(o.teamSlot, c[2]);
o.traderRef = _add128(o.traderRef, c[3]);
o.holder = _add128(o.holder, c[4]);
o.extra = _add128(o.extra, c[5]);
s.owedTotal[q] += amount;
emit ClaimSkipped(wallet, q, amount);
}
}
}
/// Book a failed payout as owed to `wallet` (bit 64), counted in `owedTotal`.
function owePayout(address wallet, address quote, uint256 amount) internal {
Store storage s = store();
s.payoutOwed[wallet][quote] += amount;
s.owedTotal[quote] += amount;
emit PayoutOwed(wallet, quote, amount);
}
/// Pay `wallet`'s owed payouts in `quote` to `to`. A failed transfer keeps it owed (`ClaimSkipped`) and returns 0.
function claimPayout(address wallet, address quote, address to) internal returns (uint256 amount) {
Store storage s = store();
amount = s.payoutOwed[wallet][quote];
if (amount == 0) return 0;
s.payoutOwed[wallet][quote] = 0;
s.owedTotal[quote] -= amount;
if (_transfer(quote, to, amount)) {
emit PayoutClaimed(wallet, msg.sender, quote, to, amount);
} else {
s.payoutOwed[wallet][quote] += amount;
s.owedTotal[quote] += amount;
emit ClaimSkipped(wallet, quote, amount);
amount = 0;
}
}
/// Native ETH as a quote.
address internal constant NATIVE = address(0);
/// `quote.transfer(to, amount)` by a low-level call: true only if the quote has code, the call succeeded, and it
/// returned nothing or `true`. Native ETH: a plain value call. At most 32 bytes of return data are copied.
function tryTransfer(address quote, address to, uint256 amount) internal returns (bool) {
return _transfer(quote, to, amount);
}
function _transfer(address quote, address to, uint256 amount) private returns (bool ok) {
if (quote == NATIVE) {
// memory-safe: no memory is touched
assembly ("memory-safe") {
ok := call(gas(), to, amount, 0, 0, 0, 0)
}
return ok;
}
if (quote.code.length == 0) return false;
bytes memory data = abi.encodeWithSelector(0xa9059cbb, to, amount);
// memory-safe: only the scratch word 0x00 and `data`'s own bytes
assembly ("memory-safe") {
mstore(0x00, 0)
let success := call(gas(), quote, 0, add(data, 0x20), mload(data), 0x00, 0x20)
let rs := returndatasize()
ok := and(success, or(iszero(rs), and(gt(rs, 31), eq(mload(0x00), 1))))
}
}
// ------------------------------------------------------------------------------------------------------------ Team Slot
// The slot is free; its rate is bounded by the row's `team_slot_max_bps` and the hard cap; at most 10 members.
// Weights are share ÷ Σ shares, forward only; while Σ shares is 0 the whole take is place 0's. Earnings are credited
// on the trade and claimable at once (bit 4).
/// Bind a pending handle to its wallet, once; what it built up in `quotes` moves to the wallet's bit 4.
function bindHandle(bytes32 handle, address wallet, address[] calldata quotes) internal {
Store storage s = store();
if (wallet == address(0)) revert BadMember();
if (s.handleWallet[handle] != address(0)) revert HandleAlreadyBound();
s.handleWallet[handle] = wallet;
emit HandleBound(handle, wallet, _moveHandleOwed(s, handle, wallet, quotes));
}
/// Permissionless: move a bound handle's leftover balances to its wallet. `wallet` 0 = not bound (nothing moved).
function moveHandleOwed(bytes32 handle, address[] calldata quotes) internal returns (address wallet, uint256 moved) {
Store storage s = store();
wallet = s.handleWallet[handle];
if (wallet == address(0)) return (wallet, 0);
moved = _moveHandleOwed(s, handle, wallet, quotes);
}
function _moveHandleOwed(Store storage s, bytes32 handle, address wallet, address[] calldata quotes)
private
returns (uint256 moved)
{
for (uint256 i; i < quotes.length; ++i) {
uint256 v = s.handleOwed[handle][quotes[i]];
if (v == 0) continue;
moved += v;
s.handleOwed[handle][quotes[i]] = 0;
Owed storage o = s.owed[wallet][quotes[i]];
o.teamSlot = _add128(o.teamSlot, v);
}
}
// ------------------------------------------------------------------------------------------------------------ views
// ------------------------------------------------------------------------------------------------------------ helpers
function _min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
function _u128(uint256 v) private pure returns (uint128) {
if (v > type(uint128).max) revert Overflow();
return uint128(v);
}
function _add128(uint128 a, uint256 b) private pure returns (uint128) {
return _u128(uint256(a) + b);
}
/// `⌊a · b ÷ d⌋` with a 512-bit product (Remco Bloemen's mulDiv, MIT).
function mulDiv(uint256 a, uint256 b, uint256 d) internal pure returns (uint256 result) {
unchecked {
uint256 prod0;
uint256 prod1;
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
return prod0 / d;
}
if (d <= prod1) revert Overflow();
uint256 remainder;
assembly {
remainder := mulmod(a, b, d)
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
uint256 twos = d & (~d + 1);
assembly {
d := div(d, twos)
prod0 := div(prod0, twos)
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
uint256 inv = (3 * d) ^ 2;
inv *= 2 - d * inv;
inv *= 2 - d * inv;
inv *= 2 - d * inv;
inv *= 2 - d * inv;
inv *= 2 - d * inv;
inv *= 2 - d * inv;
result = prod0 * inv;
}
}
}
src/v2/FloorBandsV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
// The bid's most segments (C and K together); sizes every fixed bid array. Edges are `BANDS_MAX + 1`.
uint256 constant BANDS_MAX = 24;
// A row's most bands: the row codec's byte layout and the row's copied band shape.
uint256 constant ROW_BANDS_MAX = 4;
src/v2/FloorBookTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// FLOOR v2 view structs, events and errors. Money is base units `uint128`, √prices Q56.72; token amounts in
/// `BookRange`, `LaunchBook` are math units (10⁻⁶ of a token; × `TOKEN_SCALE` 1e12 gives chain units).
/// Band arrays are dynamic, as long as the storage array.
library FloorBookTypes {
/// Math units: `tokens`, `askLeft`, `back`. Money: `place`.
struct BookRange {
uint128 sqrtA;
uint128 sqrtB;
uint64 tokens;
uint64 askLeft;
uint64 back;
uint128 place;
uint16 thetaBps;
uint16 psiBps;
uint8 kind;
uint8 class_;
}
/// The whole math `Book` (`FloorBookWalk.Book`) plus each range's ψ / θ / class: enough for an off-chain walk.
struct LaunchBook {
uint128 sqrtP;
uint128 sqrtF;
uint128 f; // money: `floor` (F's own money + ckAtF)
uint128[] bandMoney; // money, segment i (0 = C on top); length = storage's band slots
uint8 nRanges;
BookRange[48] ranges; // only the first `nRanges` are set
uint128 sqrtLMax; // the highest price first-time issuance reached
uint64 floorTokens; // math units: tokens the F point bought
uint64[] bandTokens; // math units: tokens band i bought; length = storage's band slots
uint128[] bandEdge; // Q56.72, descending: band i = [bandEdge[i+1], bandEdge[i]], K = [sqrtF, bandEdge[nBands]]
uint8 nBands; // the BOOK's segment count (rewritten by each re-lay)
uint8 nC; // segments 0 .. nC are C, nC .. nBands are K
uint128[] bandF; // money: F's money inside segment i
uint128[] bandFClaim; // money: F's claim on the tokens segment i holds
uint128 ckAtF; // money: C + K parked inside `f` at f
uint64 ckFloorTokens; // math units: tokens C + K's parked money bought at the F point
bool graduated;
uint32[5] feePpm; // the curve's END rates (not the rate now): backing, team, platform, $FLOOR, holder
// K own pot (appended; API.md "K own pot"): `ckAtF` / `ckFloorTokens` stay the totals, these are K's parts
uint128 kAtF; // money: K's part of `ckAtF` (C's is the rest)
uint64 kFloorTokens; // math units: K's part of `ckFloorTokens`
bool kpot; // the book keeps two pots (false on a live pre-upgrade launch until its first trade, D10)
}
/// Money: `booked`, `paid`. Milestones are paid at once by the buy.
struct LaunchMs {
uint128[4] booked;
uint128[4] paid;
}
/// Money (`owed`) is `uint128`; tokens math units.
struct HolderPos {
bool matured;
uint64 amount;
uint64 avgTs;
uint128 owed;
uint128 indexSnap;
bool skipped;
}
/// The launch's fee curve (copied at create): each leg's start rate (ppm: backing, team, platform, $FLOOR, holder)
/// and the knots' √ on the launch's quote (Q56.72; `sqrtFeeB` 0 = no curve, the legs flat at `LaunchBook.feePpm`, the
/// end rate). Before graduation every trade pays `FloorFeesV2.pregrad` instead.
struct FeeCurve {
uint32[5] feeStartPpm;
uint128 sqrtFeeA;
uint128 sqrtFeeB;
}
/// The Team Slot per place (place 0 the creator). Tokens in math units, money in quote base units. `slotMember` is
/// the stored member (0 for an unbound handle); `wallet` is who bit 4 pays (the member, else the bound handle's
/// wallet); bits 128 / 256 pay place 0's part to the creator and every other place's to its `wallet`.
struct TeamSlot {
uint64[10] teamBuyPart; // the Team Buy split at unlock, not yet claimed (bit 128)
uint32[10] slotWeightPpb;
uint64[10] slotShare; // share units
address[10] slotMember;
bytes32[10] slotHandle;
uint128[10] slotOwed; // the Team Share owed (bit 4)
uint64[10] slotBoughtOwed; // tokens bought with the Team Share, not yet claimed (bit 256)
address[10] wallet;
}
/// The token's `bookState()` (`wMatured` = W; `wPending` and `dust` read 0).
struct HolderBookV {
uint128 index;
uint64 wMatured;
uint64 wPending;
uint128 carry;
uint128 dust;
}
}
/// The v2 events and errors, inherited by every v2 hop so they are emitted with one ABI.
interface IFloorBookEvents {
/// A trade; `fees` is backing, team, platform, $FLOOR, holder.
event Trade(
uint256 indexed launchId,
address indexed trader,
address indexed recipient,
bool isBuy,
uint256 quoteGross,
uint256 quoteNet,
uint256 refund,
uint256 tokens,
uint256[5] fees,
uint256 traderRef,
uint256 fromResale,
uint256 fromFirst,
uint256 unfilled,
uint128 sqrtBefore,
uint128 sqrtAfter,
uint128 sqrtF,
uint256 floor,
uint256 cushion, // C + K's money (`ck_money`)
uint256 sCirc,
uint8 steps,
bool budgetHit,
uint64 slot,
uint64 ts,
uint8 kind, // 0 trade, 1 the create's Team Buy, 2 `teamShareBuy`
uint256 creatorRef, // the creator referrers' slices of this trade's Team Fee; 0 when none
uint256 bidMoney, // F + C + K after the trade
uint256[4] msPaid // this trade's Milestones, paid at once
);
event HolderIndexRolled(uint256 indexed launchId, uint128 index, uint64 wMatured, uint64 wPending, uint64 carry);
event DeadSynced(uint256 indexed launchId, uint256 added, uint256 deadTokens, uint256 sCirc);
/// `creditBacking`: `amount` (what FloorAmm received) joined F at once; `fAfter` is F after it; `slot` is the block
/// number. Solana's `BackingCredited` fields in order.
event BackingCredited(uint256 indexed launchId, address indexed donor, uint256 amount, uint256 fAfter, uint64 slot);
/// Ruling 2026-11-22 (OG Users): each referrer tier's slice of one trade, right after its `Trade`, only when one is
/// non-zero: `traderParts` of the Platform fee (Σ = `Trade.traderRef`), `creatorParts` of the whole Team Share (the
/// Team Fee's, Σ = `Trade.creatorRef`, plus the Team Milestone's); `og` bits 0–2 the trader tiers, 3–5 the creator
/// tiers paid the OG rate. `trader` is `Trade.trader`. Solana's `RefSlices`.
event RefSlices(uint256 indexed launchId, address indexed trader, uint256[3] traderParts, uint256[3] creatorParts, uint8 og);
/// A referrer's one OG window `[from, until)` (unix s), set by the referral authority; `count` the live windows after.
event OgUserSet(address indexed referrer, uint64 from, uint64 until, uint16 count);
/// Governance ended a window (`until` = now, or its natural end when that came first); one place freed.
event OgUserRevoked(address indexed referrer, uint64 until, uint16 count);
error RowTooManyRanges();
error RowNotFeasible();
error NotToken();
/// `OG_MAX` windows are live on this chain (Solana `OgFull` 6071).
error OgFull();
/// The wallet's one window is already set (never set twice, never extended).
error OgAlreadySet();
}
src/v2/FloorSlotV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {FloorRewards as Rw} from "../libraries/FloorRewards.sol";
import {FloorBookStorage as S} from "./storage/FloorBookStorage.sol";
/// Who place `i` of a Team Slot is: a wallet place's `slotMember[i]`, else the wallet its handle is bound to (0 while unbound).
library FloorSlotV2 {
function member(S.RewardsV2 storage R, uint256 i) internal view returns (address m) {
m = R.slotMember[i];
if (m == address(0)) {
bytes32 h = R.slotHandle[i];
if (h != bytes32(0)) m = Rw.store().handleWallet[h];
}
}
}
src/v2/engines/FloorCreditV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IFloorAmm} from "../../interfaces/IFloorAmm.sol";
import {FloorRewards as Rw} from "../../libraries/FloorRewards.sol";
import {FloorBookStorage as S} from "../storage/FloorBookStorage.sol";
import {IFloorBookEvents} from "../FloorBookTypes.sol";
/// The launch token's holder index (`FloorTokenIndexed`): FloorAmm's index step and the book read (`takeOwed` is the claim hop's).
interface IFloorTokenV2 {
function addReward(uint256 amount) external;
function bookState()
external
view
returns (uint128 index, uint64 wMatured, uint64 wPending, uint128 carry, uint128 dust);
function positionOf(address a)
external
view
returns (uint64 amount, uint64 avgTs, uint128 owed, bool matured, uint128 indexSnap);
function takeOwed(address wallet) external returns (uint256);
}
/// The Team and holder credits shared by the book engine (Team Fees, Holder Fee) and the settle engine (Team and Holder
/// Milestones, paid at once).
library FloorCreditV2 {
/// Team: the creator's referrers first (800 / 140 / 60 bps of the whole Team Share; an OG tier 2,400 / 420 / 180 on a
/// launch created inside its window, while it runs: ruling 2026-11-22), then the members by weight (dust → backing),
/// or the creator when no weights are set. Returns what the creator's referrers were booked (`Trade.creatorRef`).
function team(S.LaunchV2 storage L, S.RewardsV2 storage R, uint256 amount) internal returns (uint256 toRefs) {
if (amount == 0) return 0;
address[3] memory cr = R.creatorRef;
uint256[3] memory refs;
uint256 rest = amount;
if (cr[0] != address(0) || cr[1] != address(0) || cr[2] != address(0)) {
(uint256[3] memory bps, uint256 og) = Rw.creatorBps(Rw.store(), cr, L.createdAt);
(refs, rest) = Rw.slices(amount, [cr[0] != address(0), cr[1] != address(0), cr[2] != address(0)], bps);
for (uint256 i; i < 3; ++i) {
if (refs[i] != 0) R.creatorRefOwed[i] = add(R.creatorRefOwed[i], refs[i]);
toRefs += refs[i];
}
noteRefs(3, refs, og);
}
uint32[10] memory w = R.slotWeightPpb;
bool any;
for (uint256 i; i < Rw.MAX_MEMBERS; ++i) {
if (w[i] != 0) any = true;
}
if (!any) {
R.creatorOwed = add(R.creatorOwed, rest);
return toRefs;
}
(uint256[10] memory parts, uint256 dust) = Rw.splitMembers(rest, w);
uint256 total;
for (uint256 i; i < Rw.MAX_MEMBERS; ++i) {
if (parts[i] != 0) R.slotOwed[i] = add(R.slotOwed[i], parts[i]);
total += parts[i];
}
R.slotOwedTotal = add(R.slotOwedTotal, total);
if (dust != 0) L.f = add(L.f, dust); // F's own money
}
/// Transient (ruling 2026-11-22): the trade's referrer slices by tier, for its one `RefSlices` after `Trade`. Words 0–2
/// the trader's referrers', 3–5 the creator's (the Team Fee's plus the Team Milestone's), 6 the OG bits.
bytes32 private constant REF_SLICES = keccak256("floor.book.v2.refSlices");
/// Adds `parts` at words `base ..= base + 2` and ORs `og` into word 6.
function noteRefs(uint256 base, uint256[3] memory parts, uint256 og) internal {
bytes32 k = REF_SLICES;
for (uint256 i; i < 3; ++i) {
uint256 v = parts[i];
if (v == 0) continue;
assembly ("memory-safe") {
let at := add(k, add(base, i))
tstore(at, add(tload(at), v))
}
}
if (og != 0) {
assembly ("memory-safe") {
tstore(add(k, 6), or(tload(add(k, 6)), og))
}
}
}
/// The trade's `RefSlices` (after its `Trade`), only when a part is non-zero; clears the tally.
function emitRefs(uint256 id, address trader) internal {
bytes32 k = REF_SLICES;
uint256[3] memory t;
uint256[3] memory c;
uint256 og;
bool any;
for (uint256 i; i < 3; ++i) {
uint256 a;
uint256 b;
assembly ("memory-safe") {
a := tload(add(k, i))
b := tload(add(k, add(3, i)))
}
(t[i], c[i]) = (a, b);
if (a != 0 || b != 0) any = true;
}
if (!any) return;
assembly ("memory-safe") {
og := tload(add(k, 6))
for { let i := 0 } lt(i, 7) { i := add(i, 1) } { tstore(add(k, i), 0) }
}
emit IFloorBookEvents.RefSlices(id, trader, t, c, uint8(og));
}
/// Transient: a buy flow's holder money waits here until its tokens reach the buyer (`deferHolder` / `flushHolder`).
/// Word 0 = deferring (1) or not (0); word 1 = the money waiting.
bytes32 private constant HOLDER_DEFER = keccak256("floor.book.v2.holder.defer");
/// Holder: owed to the holder index, which the token spreads by `addReward`; inside a buy flow the index steps once,
/// before the tokens move (`flushHolder`).
function holder(S.LaunchV2 storage L, S.RewardsV2 storage R, uint256 amount) internal {
if (amount == 0) return;
R.holderOwed = add(R.holderOwed, amount);
bytes32 k = HOLDER_DEFER;
bool deferred;
assembly ("memory-safe") {
deferred := tload(k)
if deferred { tstore(add(k, 1), add(tload(add(k, 1)), amount)) }
}
if (!deferred) IFloorTokenV2(L.token).addReward(amount);
}
/// A Holder Fee paid while no holder has weight (the token's W = 0, read here: before a buy's tokens reach
/// the buyer; after a sell's unfilled tokens went back, `deferSellFee` / `flushSellFee`)
/// joins F's own money (`f`) instead of waiting in the index's carry for the next holder. Holder
/// Milestones keep `holder`.
function holderFee(S.LaunchV2 storage L, S.RewardsV2 storage R, uint256 amount) internal {
if (amount == 0) return;
bytes32 k = SELL_DEFER;
bool deferred;
assembly ("memory-safe") {
deferred := tload(k)
if deferred { tstore(add(k, 1), add(tload(add(k, 1)), amount)) }
}
if (deferred) return;
_holderFeeNow(L, R, amount);
}
/// Returns what joined F (`amount` at W = 0, else 0).
function _holderFeeNow(S.LaunchV2 storage L, S.RewardsV2 storage R, uint256 amount) private returns (uint256) {
(, uint64 w,,,) = IFloorTokenV2(L.token).bookState();
if (w == 0) {
L.f = add(L.f, amount);
return amount;
}
holder(L, R, amount);
return 0;
}
/// Transient: a sell flow's Holder Fee waits here until its unfilled tokens are back with the seller (W is read
/// after them, where `unfilled` never leaves the trader). Word 0 = deferring.
bytes32 private constant SELL_DEFER = keccak256("floor.book.v2.holder.sell-defer");
function deferSellFee() internal {
bytes32 k = SELL_DEFER;
assembly ("memory-safe") {
tstore(k, 1)
}
}
/// The sell's Holder Fee, after the unfilled tokens moved back: W > 0 indexes it, W = 0 sends it to F.
/// Returns what joined F (the sell's `Trade.floor` / `bidMoney` count it).
function flushSellFee(S.LaunchV2 storage L, S.RewardsV2 storage R) internal returns (uint256 toF) {
bytes32 k = SELL_DEFER;
uint256 amount;
assembly ("memory-safe") {
amount := tload(add(k, 1))
tstore(k, 0)
tstore(add(k, 1), 0)
}
if (amount != 0) toF = _holderFeeNow(L, R, amount);
}
/// Buy order: the holder index steps by the trade's Holder Fee plus
/// the Holder Milestones its settle paid (`holder_reward`), THEN the tokens go to the buyer, so the buyer never earns
/// the Holder Fee of its own buy. A buy flow calls `deferHolder` before its settle and `flushHolder` before the tokens
/// move.
function deferHolder() internal {
bytes32 k = HOLDER_DEFER;
assembly ("memory-safe") {
tstore(k, 1)
}
}
function flushHolder(address token) internal {
bytes32 k = HOLDER_DEFER;
uint256 amount;
assembly ("memory-safe") {
amount := tload(add(k, 1))
tstore(k, 0)
tstore(add(k, 1), 0)
}
if (amount != 0) IFloorTokenV2(token).addReward(amount);
}
/// v2's held total in `x` + `FloorRewards`' per-wallet owed (trader referrers, failed payouts) and buckets in `x`.
function heldIn(address x) internal view returns (uint256) {
Rw.Store storage r = Rw.store();
return S.layout().held[x] + r.owedTotal[x] + r.bucket[x] + r.holderBucket[x];
}
function add(uint128 a, uint256 b) internal pure returns (uint128) {
uint256 v = uint256(a) + b;
if (v > type(uint128).max) revert IFloorAmm.Overflow();
return uint128(v);
}
}
src/v2/engines/IFloorBookEngine.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
// `Trade.kind`: an ordinary buy or sell, the create's Team Buy, `teamShareBuy`.
uint8 constant KIND_TRADE = 0;
uint8 constant KIND_TEAM_BUY = 1;
uint8 constant KIND_TEAM_SHARE = 2;
/// The v2 engines' entry points. Engines are STATELESS contracts that `FloorAmmV2`
/// DELEGATECALLs: they read and write `floor.book.v2` (and `floor.rewards` for the owed buckets) in FloorAmmV2's
/// storage. Amounts at this seam are CHAIN units (token 18 decimals, quote base units); the engines convert to math
/// units (`TOKEN_SCALE`). `simBuy`/`simSell` run the same code on a copy.
/// A DELEGATECALL carries the caller's `msg.value`, so every entry a value-carrying FloorAmmV2 frame reaches
/// (native `buy`, `creditBacking`, `createLaunch`'s Team Buy: `simBuy`, `buy`, `creditBacking`) is `payable`; an engine never reads or moves `msg.value` (the entry counted it once).
interface IFloorBookEngine {
/// What a buy did (the part the entry needs to move money and fill `BuyResult`).
struct BuyOut {
uint256 tokensOut; // chain units
uint256 spent; // gross quote taken, fees included
uint256 refund;
uint128 sqrtAfter;
uint8 steps;
bool budgetHit;
bool graduatedNow;
}
/// What a sell did.
struct SellOut {
uint256 quoteOut; // net to the seller
uint256 tokensTaken; // chain units
uint256 unfilled; // chain units handed back (step bound)
uint128 sqrtAfter;
uint8 steps;
}
/// A sell's `Trade` values the entry does not know: FloorAmmV2 emits the sell's `Trade` after
/// `flushSellFee`, so `floor` / `bidMoney` count a W = 0 Holder Fee moved into F.
struct SellEv {
uint256 gross;
uint256[5] fees;
uint256 traderRef;
uint256 creatorRef;
uint128 sqrtBefore;
uint128 sqrtF;
uint256 floor;
uint256 cushion;
uint256 sCirc;
uint256 bidMoney;
}
/// The walk (the immediate split pays F, then C + K, then the Milestones inside it); credits the fees, emits `Trade` (and `Graduated`). The
/// entry has already received `gross`. `payer` is `Trade.trader`; the trader referrers are the engine's `_who`:
/// `beneficiary` when it has a link, else `tx.origin`. Tokens to `beneficiary == address(this)` stay held.
function buy(uint256 id, uint256 gross, uint256 minTokensOut, address beneficiary, address payer, uint8 kind)
external
payable
returns (BuyOut memory);
/// The walk down; credits the fees (the Holder Fee waits for `flushSellFee`); emits nothing: the entry emits `Trade`
/// from `SellEv` after the flush.
function sell(uint256 id, uint256 tokensIn, uint256 minQuoteOut, address beneficiary, address payer)
external
returns (SellOut memory, SellEv memory);
/// The same walk on a copy (read-only; reached through a STATICCALL to FloorAmmV2's `simBuy`/`simSell`; `payable`
/// because a DELEGATECALL carries `msg.value`; the trial is DELEGATECALLed, so not `view` here).
function simBuy(uint256 id, uint256 gross, address beneficiary) external payable returns (BuyOut memory);
function simSell(uint256 id, uint256 tokensIn, address beneficiary) external returns (SellOut memory);
/// A Team Slot member spends up to `amount` (0 = all) of its owed Team Share of `id` on an ordinary v2 buy
/// (beneficiary FloorAmmV2, no trader referrer); the refund goes back to the Team Share, the tokens are booked to it.
function teamShareBuy(uint256 id, address member, uint256 amount, uint256 minTokensOut) external returns (BuyOut memory);
/// The donation into F (`floor`, F's own money). `amount` has been received.
function creditBacking(uint256 id, uint256 amount) external payable;
/// The pay-first liabilities in `x`: `FloorBookStorage.held[x]` (every v2 pot, place, Milestone, owed and book
/// token) + `FloorRewards`' per-wallet owed, platform and holder buckets in `x`.
function heldIn(address x) external view returns (uint256);
}
src/v2/engines/IFloorTradeEngines.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {FloorBookWalk as W} from "./book/FloorBookWalk.sol";
/// What the book engine's fees and events read of the book after a trade (chain units where `Trade` prints them).
struct TradeAfter {
uint256 sqrtP;
uint256 sqrtF;
uint256 floor;
uint256 cushion; // `ck_money`
uint256 sCirc; // circulating ×`TOKEN_SCALE`, 0 if it would be negative
uint256 bidMoney; // F + C + K
}
/// The walks, the split and the C + K re-lay in their own stateless contracts (EIP-170)
/// (`FloorBuyEngine`, `FloorSellEngine`), DELEGATECALLed by the book engine, so they run in FloorAmmV2's storage
/// (`floor.book.v2`): each loads the launch, trades the memory book and (trade entry) commits it; no book crosses the
/// seam. A sim is the same entry with `commit` false (the load and the trade are `view`; the commit, the one write, is
/// skipped; `TradeAfter` then reads 0), run under `quoteBuy` / `quoteSell`'s static frame. One entry per engine
/// keeps each under EIP-170. Math units; `id` is a launch the book engine
/// has resolved.
interface IFloorBuyEngine {
/// The whole `trade::buy` (`FloorSplitRelay.buy`: the walk up, then on a graduated book the split and the re-lay),
/// committed when `commit`. `payable`: a DELEGATECALL carries the trade's `msg.value` (never read). No `TradeAfter`
/// (EIP-170: this engine is at the limit): the book engine reads the committed book back (`FloorBookStore.summary`).
function buy(uint256 id, uint256 gross, uint256 minTokens, bool commit) external payable returns (W.BookBuy memory);
}
interface IFloorSellEngine {
/// The whole `trade::sell` (`FloorSplitRelay.sell`: the walk down, then on a graduated book the re-lay), committed
/// when `commit`.
function sell(uint256 id, uint256 tokens, uint256 minOut, bool commit)
external
payable
returns (W.BookSell memory, TradeAfter memory);
}
src/v2/engines/book/FloorBookStore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IFloorAmm} from "../../../interfaces/IFloorAmm.sol";
import {FloorBookStorage as S} from "../../storage/FloorBookStorage.sol";
import {FloorBookWalk as W} from "./FloorBookWalk.sol";
import {BANDS_MAX as BANDS} from "../../FloorBandsV2.sol";
import {FloorSupplyV2 as Sup} from "../../math/FloorSupplyV2.sol";
import {TradeAfter} from "../IFloorTradeEngines.sol";
import {FloorSqrtV2 as Q} from "../../math/FloorSqrtV2.sol";
/// Loads a `LaunchV2` into the walk's memory book and commits it back (only the fields a walk can change).
/// The create writes the launch's write-once data into one data contract per launch (`deployData`, address in
/// `LaunchV2.data`): code `0x00` ‖ per range one word, `sqrtA` (bits 0..127) | `tokens` (bits 128..191) (`sqrtB` is the
/// next range's `sqrtA`, the last range's `SQRT_TAIL_END`) ‖ the tail (`T_*`: storage words the trade reads).
/// A created launch's `rngSqrtA` / `rngSqrtB` / `rngTokens` live only there (storage stays 0); with no data contract
/// (a launch seeded straight into storage) the readers use storage.
library FloorBookStore {
uint256 private constant M64 = type(uint64).max;
uint256 private constant M128 = type(uint128).max;
uint256 private constant TOKEN_SCALE = 1e12; // token chain units per math unit
/// A range's record in the data contract: one word, `sqrtA` (bits 0..127) | `tokens` (bits 128..191).
uint256 internal constant REC = 0x20;
/// The tail after the records: these fields' storage words, in order (word index in the tail: count).
uint256 internal constant T_KIND = 0; // rngKind: 2
uint256 internal constant T_FEE = 2; // feePpm: 1
uint256 internal constant T_FEE_START = 3; // feeStartPpm: 1
uint256 internal constant T_SQRT_FEE = 4; // sqrtFeeA (low 128 bits) | sqrtFeeB (high 128 bits): 1
uint256 internal constant T_THETA = 5; // rngTheta: 3
uint256 internal constant T_PSI = 8; // rngPsi: 3
uint256 internal constant T_MS_CAP = 11; // rngMsCap: 6
uint256 internal constant T_WORDS = 17;
function load(S.LaunchV2 storage L) internal view returns (W.Book memory b) {
b.sqrtP = L.sqrtP;
b.sqrtF = L.sqrtF;
b.sqrtLMax = L.sqrtLMax;
b.floor = L.f;
uint256 nb = L.nBands;
b.nBands = nb;
b.nC = L.nC;
// segments `≥ nBands` (edges `> nBands`) are 0 in storage, so only the live ones are read
if (nb > W.BANDS_MAX) nb = W.BANDS_MAX;
unpack(slotOf(L.bandMoney), ptrOf(b.bandMoney), 0x20, 128, nb);
unpack(slotOf(L.bandF), ptrOf(b.bandF), 0x20, 128, nb);
unpack(slotOf(L.bandFClaim), ptrOf(b.bandFClaim), 0x20, 128, nb);
b.ckAtF = L.ckAtF;
b.ckFloorTokens = L.ckFloorTokens;
// K own pot: one word, `kAtF` (bits 0..127) | `kFloorTokens` (128..191) | `on` (192..199)
S.KPotV2 storage kp = L.kpot;
b.kAtF = kp.kAtF;
b.kFloorTokens = kp.kFloorTokens;
b.kpot = kp.on;
b.feePpm = L.feePpm;
b.feeStartPpm = L.feeStartPpm;
b.sqrtFeeA = L.sqrtFeeA;
b.sqrtFeeB = L.sqrtFeeB;
b.graduated = L.graduated != 0;
uint256 n = L.nRanges;
b.nRanges = n;
b.ranges = _ranges(L, n);
b.floorTokens = L.floorTokens;
unpack(slotOf(L.bandTokens), ptrOf(b.bandTokens), 0x20, 64, nb);
unpack(slotOf(L.bandEdge), ptrOf(b.bandEdge), 0x20, 128, nb + 1);
}
/// The ranges read slot by slot (each packed slot once) into one block of `n` `Range`s; `Panic(0x32)` past 48.
function _ranges(S.LaunchV2 storage L, uint256 n) private view returns (W.Range[] memory rs) {
if (n > 48) panic(0x32);
uint256 rs0;
assembly ("memory-safe") {
rs := mload(0x40)
mstore(rs, n)
rs0 := add(rs, add(0x20, shl(5, n)))
mstore(0x40, add(rs0, mul(0xe0, n)))
for { let i := 0 } lt(i, n) { i := add(i, 1) } { mstore(add(rs, shl(5, add(i, 1))), add(rs0, mul(0xe0, i))) }
}
// `sqrtA`, `sqrtB`, `tokens` from the data contract's records: one EXTCODECOPY into the block's last `32·n` bytes,
// spread front to back (range `i` writes bytes `[224i, 224i + 128)`, record `k` sits at `192n + 32k`, so records
// `i` and `i + 1` are read before range `i` is written; the last `sqrtB` is overwritten with `SQRT_TAIL_END`).
// The same pass turns the stored tokens sold (`tokens − askLeft`) back into `askLeft`.
address a = L.data;
if (a != address(0)) {
uint256 end = Q.SQRT_TAIL_END;
uint256 sold = slotOf(L.rngAskLeft);
assembly ("memory-safe") {
let m := 0xffffffffffffffffffffffffffffffff
let s := add(rs0, mul(0xc0, n))
let e := add(rs0, mul(0xe0, n))
// the tail's two `rngKind` words too, at `e` (past the block, read just below)
extcodecopy(a, s, 1, add(shl(5, n), 0x40))
let w := 0
let k := 0
for { let r := rs0 } lt(r, e) { r := add(r, 0xe0) } {
let x := mload(s)
s := add(s, 0x20)
let t := shr(128, x)
mstore(r, and(x, m))
mstore(add(r, 0x20), and(mload(s), m))
mstore(add(r, 0x40), t)
if iszero(and(k, 3)) {
w := sload(sold)
sold := add(sold, 1)
}
mstore(add(r, 0x60), sub(t, and(w, 0xffffffffffffffff)))
w := shr(64, w)
k := add(k, 1)
}
if n { mstore(sub(e, 0xc0), end) }
}
unpackM(rs0 + 0xe0 * n, rs0 + 0xc0, 0xe0, 8, n);
} else {
unpack(slotOf(L.rngSqrtA), rs0, 0xe0, 128, n);
unpack(slotOf(L.rngSqrtB), rs0 + 0x20, 0xe0, 128, n);
unpack(slotOf(L.rngTokens), rs0 + 0x40, 0xe0, 64, n);
unpack(slotOf(L.rngAskLeft), rs0 + 0x60, 0xe0, 64, n);
unpack(slotOf(L.rngKind), rs0 + 0xc0, 0xe0, 8, n);
}
unpack(slotOf(L.rngBack), rs0 + 0x80, 0xe0, 64, n);
unpack(slotOf(L.rngPlace), rs0 + 0xa0, 0xe0, 128, n);
}
// ======================================================================================== the per-launch data contract
/// At create, once the launch's fields are stored: its data contract (CREATE2, salt = the launch's `LaunchV2` slot),
/// code `0x00` ‖ `n` records from the created book `b` ‖ the tail's storage words; its address into `L.data`. A failed
/// deploy is `Panic(0x01)`; a book the one-word record cannot hold exactly (`sqrtA` past 128 bits, `tokens` past 64,
/// an edge that does not continue, a last edge other than `SQRT_TAIL_END`) is `Panic(0x01)` too, never a cut value.
function deployData(S.LaunchV2 storage L, W.Book memory b) internal {
_deployData(L, b, 0);
}
/// `deployData` for a create that does not store the tail's range words (`rngKind`, `rngTheta`, `rngPsi`,
/// `rngMsCap`: write-once, read only through the data contract): `kind` packed from `b`'s ranges, `theta`, `psi`,
/// `msCap` the 12 words at memory `x` (3, 3, 6: each the storage word a create would have written, elements past
/// `nRanges` 0); `feePpm`, `feeStartPpm`, `sqrtFeeA | sqrtFeeB` from storage as before.
function deployData(S.LaunchV2 storage L, W.Book memory b, uint256 x) internal {
_deployData(L, b, x);
}
function _deployData(S.LaunchV2 storage L, W.Book memory b, uint256 x) private {
uint256 n = L.nRanges;
if (n > 48) panic(0x32);
uint256 len = 1 + n * REC + (T_WORDS << 5);
bytes memory init = new bytes(10 + len);
uint256 p;
assembly ("memory-safe") {
p := add(init, 0x20)
// PUSH2 len, DUP1, PUSH1 10, RETURNDATASIZE, CODECOPY, RETURNDATASIZE, RETURN; then the 0x00 (STOP) byte
mstore(p, or(shl(248, 0x61), or(shl(232, len), shl(176, 0x80600a3d393df3))))
p := add(p, 11)
}
W.Range[] memory rs = b.ranges;
if (rs.length < n) panic(0x32);
for (uint256 i; i < n; ++i) {
W.Range memory r = rs[i];
uint256 nextA = i + 1 < n ? rs[i + 1].sqrtA : Q.SQRT_TAIL_END;
if (r.sqrtA > M128 || r.tokens > M64 || r.sqrtB != nextA) panic(0x01);
uint256 w = r.sqrtA | (r.tokens << 128);
uint256 q = p + i * REC;
assembly ("memory-safe") {
mstore(q, w)
}
}
if (x == 0) {
tail(L, p + n * REC);
} else {
_tailFrom(L, rs, n, x, p + n * REC);
}
address a;
assembly ("memory-safe") {
a := create2(0, add(init, 0x20), mload(init), L.slot)
}
if (a == address(0) || a.code.length != len) panic(0x01);
L.data = a;
}
/// Range `i` (< `nRanges`)'s `sqrtA`, `sqrtB`, `tokens`: from the data contract, or storage when `data` is 0.
function rec(S.LaunchV2 storage L, uint256 i) internal view returns (uint256 sqrtA, uint256 sqrtB, uint256 tokens) {
address a = L.data;
if (a == address(0)) return (L.rngSqrtA[i], L.rngSqrtB[i], L.rngTokens[i]);
if (i >= 48) panic(0x32);
uint256 n = L.nRanges;
uint256 end = Q.SQRT_TAIL_END;
assembly ("memory-safe") {
// records `i` and `i + 1` (`sqrtB` is the next record's `sqrtA`, the last range's `SQRT_TAIL_END`)
let m := mload(0x40)
extcodecopy(a, m, add(1, mul(i, REC)), shl(1, REC))
let w := mload(m)
sqrtA := and(w, 0xffffffffffffffffffffffffffffffff)
tokens := shr(128, w)
sqrtB := end
if lt(add(i, 1), n) { sqrtB := and(mload(add(m, REC)), 0xffffffffffffffffffffffffffffffff) }
}
}
/// The tail's storage words (`T_*` order) to memory from `p`.
function tail(S.LaunchV2 storage L, uint256 p) internal view {
p = _words(slotOf(L.rngKind), 2, p);
p = _words(slotOf(L.feePpm), 1, p);
p = _words(slotOf(L.feeStartPpm), 2, p); // feeStartPpm, then sqrtFeeA | sqrtFeeB (the next slot)
p = _words(slotOf(L.rngTheta), 3, p);
p = _words(slotOf(L.rngPsi), 3, p);
_words(slotOf(L.rngMsCap), 6, p);
}
/// The tail (`T_*` order) to memory from `p` for `deployData(L, b, x)`: `kind` packed from `rs` (8 bits each, low
/// first), the fee words from storage, then `x`'s 12 words.
function _tailFrom(S.LaunchV2 storage L, W.Range[] memory rs, uint256 n, uint256 x, uint256 p) private view {
uint256 k0;
uint256 k1;
for (uint256 i; i < n; ++i) {
uint256 k = rs[i].kind & 0xff; // `uint8(r.kind)`, as the storage write was
if (i < 32) k0 |= k << (i << 3);
else k1 |= k << ((i - 32) << 3);
}
assembly ("memory-safe") {
mstore(p, k0)
mstore(add(p, 0x20), k1)
}
p = _words(slotOf(L.feePpm), 1, p + 0x40);
p = _words(slotOf(L.feeStartPpm), 2, p);
assembly ("memory-safe") {
for { let i := 0 } lt(i, 0x180) { i := add(i, 0x20) } { mstore(add(p, i), mload(add(x, i))) }
}
}
function _words(uint256 slot, uint256 k, uint256 p) private view returns (uint256 q) {
assembly ("memory-safe") {
for { let i := 0 } lt(i, k) { i := add(i, 1) } { mstore(add(p, shl(5, i)), sload(add(slot, i))) }
q := add(p, shl(5, k))
}
}
/// The tail's words in a fresh memory block (word `k` at `+ 32·k`): from the launch's data contract when it has one
/// (one EXTCODECOPY), else from storage.
function tailWords(S.LaunchV2 storage L) internal view returns (uint256 p) {
address a = L.data;
uint256 n = L.nRanges;
assembly ("memory-safe") {
p := mload(0x40)
mstore(0x40, add(p, shl(5, T_WORDS)))
}
if (a == address(0)) {
tail(L, p);
return p;
}
assembly ("memory-safe") {
extcodecopy(a, p, add(1, mul(n, REC)), shl(5, T_WORDS))
}
}
/// `unpack` from memory: element `i` (< `n`) of the packed words at `src` to memory `dst + i·stride`.
function unpackM(uint256 src, uint256 dst, uint256 stride, uint256 bits, uint256 n) internal pure {
assembly ("memory-safe") {
let mask := sub(shl(bits, 1), 1)
let w := 0
for { let i := 0 } lt(i, n) { i := add(i, 1) } {
let at := mul(i, bits)
let r := and(at, 255)
if iszero(r) { w := mload(add(src, shl(5, shr(8, at)))) }
mstore(add(dst, mul(i, stride)), and(shr(r, w), mask))
}
}
}
/// Element `i` (< `n`) of the packed storage array at `slot` (`bits` per element, low bits first) to memory
/// `dst + i·stride`; each slot read once.
function unpack(uint256 slot, uint256 dst, uint256 stride, uint256 bits, uint256 n) internal view {
assembly ("memory-safe") {
let mask := sub(shl(bits, 1), 1)
let w := 0
for { let i := 0 } lt(i, n) { i := add(i, 1) } {
let at := mul(i, bits)
let r := and(at, 255)
if iszero(r) { w := sload(add(slot, shr(8, at))) }
mstore(add(dst, mul(i, stride)), and(shr(r, w), mask))
}
}
}
function slotOf(uint128[48] storage a) internal pure returns (uint256 s) {
assembly ("memory-safe") {
s := a.slot
}
}
function slotOf(uint64[48] storage a) internal pure returns (uint256 s) {
assembly ("memory-safe") {
s := a.slot
}
}
function slotOf(uint32[48] storage a) internal pure returns (uint256 s) {
assembly ("memory-safe") {
s := a.slot
}
}
function slotOf(uint16[48] storage a) internal pure returns (uint256 s) {
assembly ("memory-safe") {
s := a.slot
}
}
function slotOf(uint8[48] storage a) internal pure returns (uint256 s) {
assembly ("memory-safe") {
s := a.slot
}
}
function slotOf(uint32[5] storage a) internal pure returns (uint256 s) {
assembly ("memory-safe") {
s := a.slot
}
}
function slotOf(uint128[BANDS] storage a) internal pure returns (uint256 s) {
assembly ("memory-safe") {
s := a.slot
}
}
function slotOf(uint128[BANDS + 1] storage a) internal pure returns (uint256 s) {
assembly ("memory-safe") {
s := a.slot
}
}
function slotOf(uint64[BANDS] storage a) internal pure returns (uint256 s) {
assembly ("memory-safe") {
s := a.slot
}
}
function ptrOf(uint256[] memory a) internal pure returns (uint256 p) {
assembly ("memory-safe") {
p := add(a, 0x20)
}
}
function ptrOf(uint256[BANDS] memory a) internal pure returns (uint256 p) {
assembly ("memory-safe") {
p := a
}
}
function ptrOf(uint256[BANDS + 1] memory a) internal pure returns (uint256 p) {
assembly ("memory-safe") {
p := a
}
}
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
function _u64(uint256 x) private pure returns (uint64) {
if (x > M64) revert IFloorAmm.Overflow();
return uint64(x);
}
function _u128(uint256 x) private pure returns (uint128) {
if (x > M128) revert IFloorAmm.Overflow();
return uint128(x);
}
/// `split::SplitRow` from the launch (row data copied at create) plus the live supply and each range's psi / theta /
/// Milestone cap.
function row(S.LaunchV2 storage L) internal view returns (W.SplitRow memory r) {
r.phiBps = L.phiBps;
r.ckBps = L.ckBps;
r.wcBps = L.wcBps;
r.cShareBps = 5_000; // C's share of C + K
r.msClass = L.msClass;
// the row's switch (FLAG_PLATFORM_MS 1, FLAG_FLOOR_MS 2): a leg off gives its share to the class, as floor-math
// `RowV2::split_row`, Solana `book_io::split_row`, TON and `PresetCodecV2.settleRow` (PARITY-1-2)
r.platformMsBps = L.flags & 1 != 0 ? L.platformMsBps : 0;
r.floorMsBps = L.flags & 2 != 0 ? L.floorMsBps : 0;
r.supply = L.supply;
r.dead = L.deadTokens;
uint256 n = L.nRanges;
// the write-once words from the launch's data contract (storage with none); past 48, `Panic(0x32)`
if (n > 48) panic(0x32);
uint256 t = tailWords(L);
// `psi`, `theta`, `msCap`: three length-`n` arrays in one allocation, every element written by `unpackM`
// (EIP-170: the generated `new T[](n)` is larger)
uint16[] memory psi;
uint16[] memory theta;
uint32[] memory cap;
assembly ("memory-safe") {
let sz := shl(5, add(n, 1))
psi := mload(0x40)
theta := add(psi, sz)
cap := add(theta, sz)
mstore(0x40, add(cap, sz))
mstore(psi, n)
mstore(theta, n)
mstore(cap, n)
}
r.psi = psi;
r.theta = theta;
r.msCap = cap;
uint256 pp;
uint256 pt;
uint256 pm;
assembly ("memory-safe") {
pp := add(psi, 0x20)
pt := add(theta, 0x20)
pm := add(cap, 0x20)
}
unpackM(t + (T_PSI << 5), pp, 0x20, 16, n);
unpackM(t + (T_THETA << 5), pt, 0x20, 16, n);
unpackM(t + (T_MS_CAP << 5), pm, 0x20, 32, n);
}
/// What the book engine's fees and events read of the book after a trade (`TradeAfter`): `sCirc` is
/// `circulating(supply, 0, for_sale, bought_back, dead)` in chain units (0 if it would be negative).
function summary(S.LaunchV2 storage L, W.Book memory b) internal view returns (TradeAfter memory a) {
a.sqrtP = b.sqrtP;
a.sqrtF = b.sqrtF;
a.floor = b.floor;
a.cushion = W.ckMoney(b);
(bool ok, uint256 s) = Sup.circulating(L.supply, 0, W.forSale(b), W.boughtBack(b), L.deadTokens);
a.sCirc = ok ? s * TOKEN_SCALE : 0;
a.bidMoney = W.bidMoney(b);
}
/// Writes back what `walkUp` / `walkDown` / `buy` / `sell` can change (edges, kinds, fees and bands' edges are
/// read-only to the walk).
function commit(S.LaunchV2 storage L, W.Book memory b) internal {
L.sqrtP = _u128(b.sqrtP);
L.sqrtF = _u128(b.sqrtF);
L.sqrtLMax = _u128(b.sqrtLMax);
L.f = _u128(b.floor);
// the re-lay rewrites the whole bid; segments up to the larger of the old and the new count are written
uint256 nb = b.nBands;
if (nb > W.BANDS_MAX) panic(0x32);
uint256 nw = L.nBands;
if (nw > W.BANDS_MAX) nw = W.BANDS_MAX;
if (nw < nb) nw = nb;
L.nBands = uint8(nb);
L.nC = uint8(b.nC);
pack(slotOf(L.bandMoney), ptrOf(b.bandMoney), 0, false, 128, nw);
pack(slotOf(L.bandF), ptrOf(b.bandF), 0, false, 128, nw);
pack(slotOf(L.bandFClaim), ptrOf(b.bandFClaim), 0, false, 128, nw);
pack(slotOf(L.bandEdge), ptrOf(b.bandEdge), 0, false, 128, nw + 1);
L.ckAtF = _u128(b.ckAtF);
L.ckFloorTokens = _u64(b.ckFloorTokens);
uint256 kw = _u128(b.kAtF) | (uint256(_u64(b.kFloorTokens)) << 128) | (b.kpot ? 1 << 192 : 0);
S.KPotV2 storage kp = L.kpot;
assembly ("memory-safe") {
sstore(kp.slot, kw)
}
L.graduated = b.graduated ? 1 : 0;
uint256 n = b.nRanges;
W.Range[] memory rs = b.ranges;
uint256 m = n < rs.length ? n : rs.length;
if (m > 48) m = 48;
uint256 rp;
assembly ("memory-safe") {
rp := rs
}
// with a data contract, the tokens sold (`tokens − askLeft`; a walk only lowers askLeft)
if (L.data != address(0)) packSold(slotOf(L.rngAskLeft), rp, m);
else pack(slotOf(L.rngAskLeft), rp, 0x60, true, 64, m);
pack(slotOf(L.rngBack), rp, 0x80, true, 64, m);
pack(slotOf(L.rngPlace), rp, 0xa0, true, 128, m);
if (n > m) panic(0x32);
L.floorTokens = _u64(b.floorTokens);
pack(slotOf(L.bandTokens), ptrOf(b.bandTokens), 0, false, 64, nw);
}
/// Elements `0..n` of the packed storage array at `slot` (`bits` each, low bits first) from memory
/// (`ind`: field `off` of the struct `src[i]` points to, else word `src[i]` of a fixed array), each slot written once
/// and the bits of elements `≥ n` in the last slot kept; a value past `bits` is the `_u64` / `_u128` `Overflow()`.
function pack(uint256 slot, uint256 src, uint256 off, bool ind, uint256 bits, uint256 n) internal {
bool bad;
assembly ("memory-safe") {
let mask := sub(shl(bits, 1), 1)
let w := 0
for { let i := 0 } lt(i, n) { i := add(i, 1) } {
let at := mul(i, bits)
let r := and(at, 255)
let a := add(src, shl(5, i))
if ind { a := add(mload(add(src, shl(5, add(i, 1)))), off) }
let v := mload(a)
if gt(v, mask) {
bad := 1
break
}
w := or(w, shl(r, v))
let top := add(r, bits)
let last := eq(add(i, 1), n)
if or(eq(top, 256), last) {
let s := add(slot, shr(8, at))
if lt(top, 256) { w := or(w, and(sload(s), not(sub(shl(top, 1), 1)))) }
sstore(s, w)
w := 0
}
}
}
if (bad) revert IFloorAmm.Overflow();
}
/// `pack` of the tokens sold (`tokens − askLeft` of the `Range` `rs[i]` points to) into the 64-bit array at `slot`,
/// `0..n`; `Overflow()` for a sold past 64 bits or an `askLeft` above its `tokens`.
function packSold(uint256 slot, uint256 rs, uint256 n) internal {
bool bad;
assembly ("memory-safe") {
let w := 0
let e := add(rs, shl(5, n))
let j := 0
for { let p := rs } lt(p, e) {} {
p := add(p, 0x20)
let r := mload(p)
let t := mload(add(r, 0x40))
let v := mload(add(r, 0x60))
if gt(v, t) {
bad := 1
break
}
v := sub(t, v)
if gt(v, 0xffffffffffffffff) {
bad := 1
break
}
w := or(w, shl(j, v))
j := add(j, 64)
if or(eq(j, 256), eq(p, e)) {
if lt(j, 256) { w := or(w, and(sload(slot), not(sub(shl(j, 1), 1)))) }
sstore(slot, w)
slot := add(slot, 1)
w := 0
j := 0
}
}
}
if (bad) revert IFloorAmm.Overflow();
}
}
src/v2/engines/book/FloorBookWalk.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IFloorAmm} from "../../../interfaces/IFloorAmm.sol";
import {FloorSqrtV2 as Q} from "../../math/FloorSqrtV2.sol";
import {FloorFeesV2 as Fees} from "../../math/FloorFeesV2.sol";
import {BANDS_MAX as BANDS} from "../../FloorBandsV2.sol";
import {FloorWideV2 as Wd} from "../../math/FloorWideV2.sol";
/// A line-for-line port of `floor_math::v2::{book, trade}` (the walk and the book-level buy / sell) on a MEMORY book.
/// Units are math units (tokens 10⁻⁶, money base units, √prices Q56.72). Every function mirrors the Rust one of the same
/// name; `Option` → `(ok, v)` from `FloorSqrtV2`, `?` on `ov(…)` → `IFloorAmm.Overflow()`. A refused trade reverts (the
/// Rust's "moves nothing"). Errors: `NothingToDo`, `SlippageExceeded`, `Overflow` (IFloorAmm) and `MathFailed(5)`
/// (`MathError::BookEmpty`, by index). Money is u128, tokens u64.
library FloorBookWalk {
uint256 internal constant RANGES_MAX = 48;
uint256 internal constant BANDS_MAX = BANDS; // the bid-segment count
uint256 internal constant PIECES_MAX = 48; // MAX_WALK_STEPS × 2 (a re-fill walks again)
uint256 internal constant MAX_WALK_STEPS = 24;
/// `relay::CUT_NUDGES`: the cut's `+1` nudges past the closed form; past them nothing is taken from that range.
uint256 internal constant CUT_NUDGES = 8;
uint256 internal constant KIND_BONDING = 0;
uint256 internal constant KIND_TAIL = 5;
uint8 internal constant ERR_BOOK_EMPTY = 5;
uint256 private constant U64 = type(uint64).max;
uint256 private constant U128 = type(uint128).max;
/// Pieces: `i < nRanges` is `Range(i)`; `P_BAND + j` is `Band(j)` (a mirror segment, C then K); `P_FLOOR`.
uint256 private constant P_BAND = 1 << 16;
uint256 private constant P_FLOOR = 3 << 16;
uint256 private constant NONE = type(uint256).max;
struct Range {
uint256 sqrtA;
uint256 sqrtB;
uint256 tokens;
uint256 askLeft;
uint256 back;
uint256 place;
uint256 kind;
}
struct Book {
uint256 sqrtP;
uint256 sqrtF;
uint256 sqrtLMax;
uint256 floor;
uint256 floorTokens;
uint256 nBands;
uint256[BANDS_MAX + 1] bandEdge;
uint256[BANDS_MAX] bandMoney;
uint256[BANDS_MAX] bandTokens;
// the split: segments `0 .. nC` are C, `nC .. nBands` are K; F's money and claim per segment
uint256 nC;
uint256[BANDS_MAX] bandF;
uint256[BANDS_MAX] bandFClaim;
uint256 ckAtF; // C + K money with no room to lay, parked inside `floor` at f
uint256 ckFloorTokens; // tokens that money bought at the F point (≤ floorTokens)
// K own pot (API.md "K own pot"): the book keeps two pots; K's parts of `ckAtF` / `ckFloorTokens`
bool kpot;
uint256 kAtF;
uint256 kFloorTokens;
uint32[5] feePpm;
bool graduated;
uint256 nRanges;
Range[] ranges;
/// The fee curve: the legs' start rates at or under `sqrtFeeA`, `feePpm` at or over `sqrtFeeB`;
/// `sqrtFeeB == 0` is no curve.
uint32[5] feeStartPpm;
uint256 sqrtFeeA;
uint256 sqrtFeeB;
}
/// `split::SplitRow` plus what the split reads off the launch: the live supply, the dead tokens and each range's
/// psi / theta / Milestone cap (arrays of `nRanges`, filled by the engine from the launch).
struct SplitRow {
uint256 phiBps;
uint256 ckBps;
uint256 wcBps;
uint256 cShareBps;
uint256 msClass;
uint256 platformMsBps;
uint256 floorMsBps;
uint256 supply;
uint256 dead;
uint16[] psi;
uint16[] theta;
uint32[] msCap;
}
/// `split::Piece`: one first-time slice of a buy (net money, tokens), in the order the walk sold it.
struct Piece {
uint256 sqrtLo;
uint256 sqrtHi;
uint256 money;
uint256 tokens;
uint256 range;
}
/// `split::Split`.
struct Split {
uint256 dF; // the top-up included
uint256 cAdd; // into C (laid by the re-lay)
uint256 kAdd; // into K
uint256 cTake; // the top-up's part from C's pot: in `dF`; the re-lay takes it from C's pool
uint256 kTake; // the top-up's part from K's pot
uint256 ms;
uint256[4] booked; // Team, Holder, Platform, $FLOOR
uint256 sqrtFNew;
}
/// `relay::Relay`.
struct Relay {
uint256 nC;
uint256 nK;
uint256 laidC;
uint256 laidK;
uint256 atF;
uint256 kAtF; // K's part of `atF`
}
struct WalkUp {
Piece[] pieces;
uint256 nPieces;
uint256 money;
uint256 tokens;
uint256 fromResale;
uint256 fromFirst;
uint256 steps;
bool budgetHit;
bool graduatedNow;
uint256 bondingMoney; // the Bonding range's money moved into F at graduation (0 without one)
}
struct WalkDown {
uint256 tokens;
uint256 money;
uint256 fromF;
uint256 fromK;
uint256 fromC;
uint256 fromPlace;
uint256 steps;
bool budgetHit;
}
/// `trade::BookBuy`.
struct BookBuy {
uint256 gross;
uint256 net;
uint256 refund;
uint256 tokens;
uint256[5] fees;
uint256 fromResale;
uint256 fromFirst;
uint256 steps;
bool budgetHit;
bool graduatedNow;
uint256 sqrtBefore;
uint256 sqrtAfter;
uint256 bondingMoney; // `WalkUp.bondingMoney` (`Graduated.raised`)
Split split;
Relay relay;
}
/// `trade::BookSell`.
struct BookSell {
uint256 tokensIn;
uint256 unfilled;
uint256 gross;
uint256[5] fees;
uint256 out;
uint256 steps;
uint256 sqrtBefore;
uint256 sqrtAfter;
uint256 fromF;
uint256 fromK;
uint256 fromC;
uint256 fromPlace;
Relay relay;
}
// ------------------------------------------------------------------------------------------------------------ helpers
function _ov(bool ok, uint256 v) internal pure returns (uint256) {
if (!ok) revert IFloorAmm.Overflow();
return v;
}
/// Money is u128.
function _money(uint256 x) internal pure returns (uint256) {
if (x > U128) revert IFloorAmm.Overflow();
return x;
}
function _min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function _max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
function liquidity(Range memory r) internal pure returns (bool, uint256) {
return Q.liquidityForTokens(r.sqrtA, r.sqrtB, r.tokens);
}
function held(Range memory r) internal pure returns (uint256) {
return r.askLeft + r.back;
}
/// `cp_up`: a money-limited step up a constant-product piece → `(tokens, money, new √p)`. `allAtTop`: a held
/// segment bought to its top sells all its tokens (only rounding dust is left).
function _cpUp(uint256 l, uint256 p, uint256 hi, uint256 rem, uint256 heldT, bool allAtTop)
private
pure
returns (uint256, uint256, uint256)
{
if (heldT == 0 || p >= hi || l == 0) return (0, 0, p);
// the piece's whole money is only an upper bound: past u128 (the Tail to `SQRT_TAIL_END`) no `rem` reaches it,
// so the buy takes the money-limited step (a cap saturates, as the Rust)
(bool ok, uint256 qFull) = Q.moneyBetween(l, p, hi, true);
uint256 p2;
uint256 q;
if (ok && rem >= qFull) {
(p2, q) = (hi, qFull);
} else {
(bool ok2, uint256 pm) = Q.sqrtAfterMoney(l, p, rem);
p2 = _min(_ov(ok2, pm), hi);
(bool ok3, uint256 qq) = Q.moneyBetween(l, p, p2, true);
q = _ov(ok3, qq);
}
if (p2 <= p) return (0, 0, p);
(bool ok4, uint256 t) = Q.tokensBetween(l, p, p2, false);
uint256 dt = _min(_ov(ok4, t), heldT);
if (allAtTop && p2 == hi) dt = heldT;
if (dt == 0) return (0, 0, p);
return (dt, _money(q), p2);
}
/// `cp_down`: a token-limited step down a constant-product piece → `(tokens, money, new √p)`.
function _cpDown(uint256 l, uint256 lo, uint256 p, uint256 rem, uint256 heldM)
private
pure
returns (uint256, uint256, uint256)
{
if (heldM == 0 || p <= lo || l == 0) return (0, 0, p);
(bool ok, uint256 xFull) = Q.tokensBetween(l, lo, p, true);
xFull = _ov(ok, xFull);
uint256 p2;
uint256 dx;
if (rem >= xFull) {
(p2, dx) = (lo, xFull);
} else {
(bool ok2, uint256 pa) = Q.sqrtAfterTokens(l, p, rem);
p2 = _max(_ov(ok2, pa), lo);
if (p2 >= p) return (0, 0, p);
(bool ok3, uint256 t) = Q.tokensBetween(l, p2, p, true);
dx = _min(_ov(ok3, t), rem);
}
(bool ok4, uint256 m) = Q.moneyBetween(l, p2, p, false);
uint256 q = _min(_ov(ok4, m), heldM);
if (q == 0) return (0, 0, p);
return (dx, q, p2);
}
/// `take_place` (the Bonding flat's resale money only).
function _takePlace(Range memory r, uint256 q) private pure {
r.place -= q;
}
// ------------------------------------------------------------------------------------------------------------ pieces
function _nPieces(Book memory b) private pure returns (uint256) {
return b.nRanges + b.nBands + (b.sqrtF != 0 ? 1 : 0);
}
/// The `k`-th piece of `pieces()`: ranges, segments, then F when `sqrt_f != 0`.
function _piece(Book memory b, uint256 k) private pure returns (uint256) {
if (k < b.nRanges) return k;
k -= b.nRanges;
if (k < b.nBands) return P_BAND + k;
return P_FLOOR;
}
function _cpEdges(Book memory b, uint256 pc) private pure returns (uint256 lo, uint256 hi) {
if (pc < P_BAND) {
Range memory r = b.ranges[pc];
return (_max(r.sqrtA, b.sqrtLMax), r.sqrtB);
}
if (pc < P_FLOOR) {
uint256 i = pc - P_BAND;
return (b.bandEdge[i + 1], b.bandEdge[i]);
}
return (b.sqrtF, b.sqrtF);
}
function _tokensOf(Book memory b, uint256 pc) private pure returns (uint256) {
if (pc < P_BAND) return held(b.ranges[pc]);
if (pc < P_FLOOR) return b.bandTokens[pc - P_BAND];
return b.floorTokens;
}
function _moneyOf(Book memory b, uint256 pc) private pure returns (uint256) {
if (pc < P_BAND) return b.ranges[pc].place;
if (pc < P_FLOOR) return b.bandMoney[pc - P_BAND];
return b.floor;
}
function _isFlat(Book memory b, uint256 pc) private pure returns (bool) {
if (pc < P_BAND) return b.ranges[pc].sqrtA == b.ranges[pc].sqrtB; // a flat range is `a == b`
return pc == P_FLOOR;
}
/// `flat_can_buy`: a flat bid at `s²` holding `money` buys at least one whole token for a nonzero payment.
function _flatCanBuy(uint256 s, uint256 money) private pure returns (bool) {
if (money == 0) return false;
(bool ok, uint256 t) = Q.flatTokensForMoney(s, money, false);
if (!ok || t < 1) return false;
(bool ok2, uint256 q) = Q.flatMoneyForTokens(s, t, false);
return ok2 && q > 0;
}
/// `flat_bids`: a flat range's money trades at or above `l_max` (a flat at `l_max` is still in place), and
/// only while it can pay for a whole token.
function _flatBids(Book memory b, uint256 i) private pure returns (bool) {
Range memory r = b.ranges[i];
return r.sqrtA == r.sqrtB && r.sqrtA >= b.sqrtLMax && _flatCanBuy(r.sqrtA, r.place);
}
function _floorBids(Book memory b) private pure returns (bool) {
return b.sqrtF != 0 && _flatCanBuy(b.sqrtF, b.floor);
}
function _flatS(Book memory b, uint256 pc) private pure returns (uint256) {
if (pc < P_BAND) return b.ranges[pc].sqrtA;
return b.sqrtF;
}
/// `money_held`: F + Σ segments (C + K) + Σ place (the liquidity).
function moneyHeld(Book memory b) internal pure returns (uint256 t) {
t = b.floor;
for (uint256 i; i < b.nBands; ++i) t += b.bandMoney[i];
for (uint256 i; i < b.nRanges; ++i) t += b.ranges[i].place;
}
/// `tokens_held`: for sale, bought back, and what F, K and C bought.
function tokensHeld(Book memory b) internal pure returns (uint256 t) {
t = b.floorTokens;
for (uint256 i; i < b.nBands; ++i) t += b.bandTokens[i];
for (uint256 i; i < b.nRanges; ++i) t += held(b.ranges[i]);
}
/// `for_sale`: Σ ask_left.
function forSale(Book memory b) internal pure returns (uint256 t) {
for (uint256 i; i < b.nRanges; ++i) t += b.ranges[i].askLeft;
}
/// `Book::bought_back`: Σ back + every token the F point bought (F's and C + K's) + Σ band tokens.
function boughtBack(Book memory b) internal pure returns (uint256 t) {
for (uint256 i; i < b.nRanges; ++i) t += b.ranges[i].back;
t += b.floorTokens;
for (uint256 i; i < b.nBands; ++i) t += b.bandTokens[i];
}
/// `Book::f_own`: F's money that bids (`floor` less C + K's parked money, plus F's share inside the segments).
function fOwn(Book memory b) internal pure returns (uint256 t) {
t = b.floor - b.ckAtF;
for (uint256 i; i < b.nBands; ++i) t += b.bandF[i];
}
/// `Book::f_claims`.
function fClaims(Book memory b) internal pure returns (uint256 t) {
for (uint256 i; i < b.nBands; ++i) t += b.bandFClaim[i];
}
/// `Book::ck_money`: C + K's own money (its premium plus what waits at f; `cMoney + kMoney`).
function ckMoney(Book memory b) internal pure returns (uint256 t) {
t = b.ckAtF;
for (uint256 i; i < b.nBands; ++i) t += b.bandMoney[i] - b.bandF[i];
}
/// `Book::ck_held`: tokens C + K holds (`cHeld + kHeld`).
function ckHeld(Book memory b) internal pure returns (uint256 t) {
t = b.ckFloorTokens;
for (uint256 i; i < b.nBands; ++i) t += b.bandTokens[i];
}
/// `Book::k_seg`: K's segment (`nC`) when the book lays K's piece (`kpot` and `nBands == nC + 1`).
function kSeg(Book memory b) internal pure returns (bool, uint256) {
return (b.kpot && b.nBands == b.nC + 1, b.nC);
}
/// `Book::c_money`: C's premium in segments `0 .. nC` plus C's part of the money parked at f.
function cMoney(Book memory b) internal pure returns (uint256 t) {
t = b.ckAtF - b.kAtF;
for (uint256 i; i < b.nC; ++i) t += b.bandMoney[i] - b.bandF[i];
}
/// `Book::k_money`: K's piece's premium plus K's part of the money parked at f.
function kMoney(Book memory b) internal pure returns (uint256) {
return ckMoney(b) - cMoney(b);
}
/// `Book::c_held`: tokens C holds (segments `0 .. nC` and C's part at the F point).
function cHeld(Book memory b) internal pure returns (uint256 t) {
t = b.ckFloorTokens - b.kFloorTokens;
for (uint256 i; i < b.nC; ++i) t += b.bandTokens[i];
}
/// `Book::k_held`: tokens K holds (its piece and K's part at the F point).
function kHeld(Book memory b) internal pure returns (uint256) {
return ckHeld(b) - cHeld(b);
}
/// `Book::k_holds`: K's piece holds tokens or an F claim (a sell walked into it): K moves only along its own curve.
function kHolds(Book memory b) internal pure returns (bool) {
(bool ok, uint256 k) = kSeg(b);
return ok && (b.bandTokens[k] > 0 || b.bandFClaim[k] > 0);
}
/// `Book::bid_money` = F + C + K.
function bidMoney(Book memory b) internal pure returns (uint256 t) {
t = b.floor;
for (uint256 i; i < b.nBands; ++i) t += b.bandMoney[i];
}
/// `flat_up`: F's tokens at `f`, then the flat ranges at `p` in order.
function _flatUp(Book memory b) private pure returns (uint256) {
uint256 p = b.sqrtP;
if (b.sqrtF != 0 && b.sqrtF == p && b.floorTokens > 0) return P_FLOOR;
for (uint256 i; i < b.nRanges; ++i) {
Range memory r = b.ranges[i];
if (r.sqrtA == r.sqrtB && r.sqrtA == p && held(r) > 0) return i;
}
return NONE;
}
/// `flat_down`: the flat ranges at `p` from the top, then F at `f`.
function _flatDown(Book memory b) private pure returns (uint256) {
uint256 p = b.sqrtP;
for (uint256 i = b.nRanges; i > 0; --i) {
if (b.ranges[i - 1].sqrtA == p && _flatBids(b, i - 1)) return i - 1;
}
if (b.sqrtF == p && _floorBids(b)) return P_FLOOR;
return NONE;
}
/// `cp_piece_up`: the constant-product piece with `lo ≤ p < hi` and tokens.
function _cpPieceUp(Book memory b) private pure returns (uint256) {
uint256 p = b.sqrtP;
uint256 n = _nPieces(b);
for (uint256 k; k < n; ++k) {
uint256 pc = _piece(b, k);
(uint256 lo, uint256 hi) = _cpEdges(b, pc);
if (!_isFlat(b, pc) && lo < hi && lo <= p && p < hi && _tokensOf(b, pc) > 0) return pc;
}
return NONE;
}
/// `cp_piece_down`: the constant-product piece with `lo < p ≤ hi` and money.
function _cpPieceDown(Book memory b) private pure returns (uint256) {
uint256 p = b.sqrtP;
uint256 n = _nPieces(b);
for (uint256 k; k < n; ++k) {
uint256 pc = _piece(b, k);
(uint256 lo, uint256 hi) = _cpEdges(b, pc);
if (pc >= P_BAND && pc < P_FLOOR && lo < hi && lo < p && p <= hi && _moneyOf(b, pc) > 0) return pc;
}
return NONE;
}
/// `next_up`: the lowest edge above `p` where something sells (`NONE` if none).
function _nextUp(Book memory b) private pure returns (uint256 best) {
best = NONE;
uint256 p = b.sqrtP;
uint256 n = _nPieces(b);
for (uint256 k; k < n; ++k) {
uint256 pc = _piece(b, k);
if (_tokensOf(b, pc) == 0) continue;
uint256 s;
if (_isFlat(b, pc)) {
s = _flatS(b, pc);
} else {
(uint256 lo, uint256 hi) = _cpEdges(b, pc);
if (lo >= hi) continue;
s = lo;
}
if (s > p && s < best) best = s;
}
}
/// `next_down`: the highest edge below `p` where something buys (`found == false` if none).
function _nextDown(Book memory b) private pure returns (bool found, uint256 best) {
uint256 p = b.sqrtP;
uint256 n = _nPieces(b);
for (uint256 k; k < n; ++k) {
uint256 pc = _piece(b, k);
uint256 s;
if (pc == P_FLOOR) {
if (!_floorBids(b)) continue;
s = b.sqrtF;
} else if (_isFlat(b, pc)) {
if (!_flatBids(b, pc)) continue;
s = b.ranges[pc].sqrtA;
} else {
(uint256 lo, uint256 hi) = _cpEdges(b, pc);
if (lo >= hi || _moneyOf(b, pc) == 0) continue;
s = hi;
}
if (s < p && (!found || s > best)) (found, best) = (true, s);
}
}
/// `l_up`: a row range's `L` from its allocation; a band's from the tokens it holds over `[p, hi]`.
function _lUp(Book memory b, uint256 pc, uint256 hi) private pure returns (uint256) {
if (pc < P_BAND) {
(bool ok, uint256 l) = liquidity(b.ranges[pc]);
return _ov(ok, l);
}
(bool ok2, uint256 l2) = Q.liquidityForTokens(b.sqrtP, hi, _tokensOf(b, pc));
return _ov(ok2, l2);
}
/// `l_down`: a row range's `L` from its allocation; a band's from the money it holds over `[lo, p]`.
function _lDown(Book memory b, uint256 pc, uint256 lo) private pure returns (uint256) {
if (pc < P_BAND) {
(bool ok, uint256 l) = liquidity(b.ranges[pc]);
return _ov(ok, l);
}
(bool ok2, uint256 l2) = Q.liquidityForMoney(lo, b.sqrtP, _moneyOf(b, pc));
return _ov(ok2, l2);
}
function _graduate(Book memory b) private pure returns (uint256 raised) {
Range memory r = b.ranges[0];
raised = r.place;
b.floor = _money(b.floor + r.place);
r.place = 0;
b.sqrtF = r.sqrtA;
if (r.sqrtA > b.sqrtLMax) b.sqrtLMax = r.sqrtA; // issuance has reached f₀
b.graduated = true;
}
/// `sqrt_t0` (book.rs): the Tail range's bottom edge (`SQRT_TAIL_END` without one).
function sqrtT0(Book memory b) internal pure returns (uint256) {
for (uint256 i = b.nRanges; i > 0; --i) {
if (b.ranges[i - 1].kind == KIND_TAIL) return b.ranges[i - 1].sqrtA;
}
return Q.SQRT_TAIL_END;
}
// ------------------------------------------------------------------------------------------------------------ walk up
/// `walk_up_from`: spend at most `budget` more (the book's amount, fees not included), continuing `w` (a buy's
/// re-fill: the steps counted on, the totals added; `budgetHit` cleared); every step's money is charged into `acc`
/// at the price where the step ends (`_charge`).
function walkUpFrom(Book memory b, uint256 budget, WalkUp memory w, Fees.Acc memory acc) internal pure {
w.budgetHit = false;
uint256 rem = budget;
while (rem > 0) {
if (w.steps == MAX_WALK_STEPS) {
w.budgetHit = true;
break;
}
w.steps += 1;
uint256 pc = _flatUp(b);
if (pc != NONE) {
bool stop;
(stop, rem) = _flatUpStep(b, pc, rem, w, acc);
if (stop) break;
continue;
}
pc = _cpPieceUp(b);
if (pc != NONE) {
(, uint256 hi) = _cpEdges(b, pc);
uint256 l = _lUp(b, pc, hi);
bool moved;
if (pc < P_BAND) {
(moved, rem) = _rangeUp(b, pc, l, hi, rem, w, acc);
} else {
(uint256 dt, uint256 q, uint256 p2) = _cpUp(l, b.sqrtP, hi, rem, _tokensOf(b, pc), true);
if (dt > 0) {
_bandBuyBack(b, pc - P_BAND, dt, q);
b.sqrtP = p2;
rem -= q;
w.money += q;
w.tokens += dt;
w.fromResale += dt;
_charge(b, acc, q);
}
moved = dt > 0;
}
if (b.sqrtP == hi) continue;
if (!moved && rem > 0) {
// the slice `[p, hi)` holds no whole token (segment dust a rounding left under its top): the
// tokens stay, the walk looks further up; a range's sliver is paid for first (`_sliver`)
if (_noWholeToken(l, b.sqrtP, hi)) {
if (pc < P_BAND) {
bool stop;
(stop, rem) = _sliver(b, pc, l, hi, rem, w, acc);
if (stop) break;
}
b.sqrtP = hi;
continue;
}
}
if (!moved || rem == 0 || _tokensOf(b, pc) > 0) break;
continue; // the piece ran dry short of its top (dust): look further up
}
uint256 s2 = _nextUp(b);
if (s2 == NONE) break;
b.sqrtP = s2;
}
}
/// One flat step of `walkUp` (its own frame: keeps `walkUp` under the stack limit). Returns `(stop, rem)`: stop when
/// the money ran out at this price.
function _flatUpStep(Book memory b, uint256 pc, uint256 rem, WalkUp memory w, Fees.Acc memory acc)
private
pure
returns (bool, uint256)
{
uint256 s = _flatS(b, pc);
(bool ok, uint256 can) = Q.flatTokensForMoney(s, rem, false);
uint256 take = _min(_ov(ok, can), _tokensOf(b, pc));
if (take == 0) return (true, rem);
(bool ok2, uint256 c) = Q.flatMoneyForTokens(s, take, true);
uint256 cost = _money(_ov(ok2, c));
rem -= cost;
w.money += cost;
_charge(b, acc, cost);
w.tokens += take;
if (pc == P_FLOOR) {
// a buy-back at the F point: each pot gets its share of the money back (inside `floor`, as its parked money)
_floorBuyBack(b, cost, take);
b.floorTokens -= take;
b.floor += cost;
w.fromResale += take;
} else {
Range memory r = b.ranges[pc];
uint256 tb = _min(take, r.back);
uint256 costB = cost;
if (tb != take) {
(bool ok3, uint256 cb) = Q.flatMoneyForTokens(s, tb, true);
costB = _money(_ov(ok3, cb));
}
r.back -= tb;
r.askLeft -= take - tb;
if (r.kind == KIND_BONDING) r.place += cost; // the Bonding flat's resale only; no money rests after graduation
else {
if (s > b.sqrtLMax) b.sqrtLMax = s; // a flat issuance piece
_piece1(w, r, s, s, cost - costB, take - tb, pc);
}
w.fromResale += tb;
w.fromFirst += take - tb;
if (r.kind == KIND_BONDING && held(r) == 0 && !b.graduated) {
w.bondingMoney = _graduate(b);
w.graduatedNow = true;
}
}
return (_tokensOf(b, pc) > 0, rem); // the money ran out at this price
}
/// `floor_rebuy`'s parked part: C + K's parked tokens are bought back pro rata (`⌊cost·x_e ÷ x⌋` of the money back
/// to the parked money, `⌈take·x_e ÷ x⌉` of its tokens, capped), and of that K's part (`⌊back·x_k ÷ x_e⌋`,
/// `⌈gone·x_k ÷ x_e⌉` capped at K's and at `gone`).
function _floorBuyBack(Book memory b, uint256 cost, uint256 take) private pure {
uint256 ft0 = b.floorTokens;
uint256 xe = b.ckFloorTokens;
if (xe == 0) return;
uint256 back = Wd.mulDiv(cost, xe, ft0, false);
// `take ≤ ft0` (the F point's tokens), so `⌈take·x_e ÷ ft0⌉ ≤ x_e`: the Rust's cap at `x_e` never binds
uint256 gone = Wd.mulDiv(take, xe, ft0, true);
uint256 xk = b.kFloorTokens;
if (xk != 0) {
b.kAtF += Wd.mulDiv(back, xk, xe, false);
// `gone ≤ x_e`, so `⌈gone·x_k ÷ x_e⌉ ≤ x_k`: the Rust's cap at `x_k` never binds
b.kFloorTokens = xk - _min(Wd.mulDiv(gone, xk, xe, true), gone);
}
b.ckAtF += back;
b.ckFloorTokens = xe - gone;
}
/// `buy_first`: record a first-time slice of the buy for the split (the Bonding flat never enters it); a slice of the
/// same range as the last piece extends it (its top, money and tokens).
function _piece1(WalkUp memory w, Range memory r, uint256 lo, uint256 hi, uint256 money, uint256 tokens, uint256 i)
private
pure
{
if (r.kind == KIND_BONDING) return;
uint256 n = w.nPieces;
if (n > 0 && w.pieces[n - 1].range == i) {
Piece memory p = w.pieces[n - 1];
p.sqrtHi = hi;
p.money = _money(p.money + money);
p.tokens += tokens;
return;
}
w.pieces[w.nPieces++] = Piece(lo, hi, money, tokens, i);
}
/// A range's sliver `[p, hi)` with no whole token is first-time issuance: the buyer pays its money (rounded up,
/// against the trader) for no token, or the walk stops there (`stop`). Returns `(stop, rem)`.
function _sliver(Book memory b, uint256 i, uint256 l, uint256 hi, uint256 rem, WalkUp memory w, Fees.Acc memory acc)
private
pure
returns (bool, uint256)
{
(bool ok, uint256 q0) = Q.moneyBetween(l, b.sqrtP, hi, true);
uint256 q = _ov(ok, q0);
if (q > rem) return (true, rem);
_piece1(w, b.ranges[i], b.sqrtP, hi, q, 0, i);
rem -= q;
w.money += q;
_charge(b, acc, q);
if (hi > b.sqrtLMax) b.sqrtLMax = hi;
return (false, rem);
}
/// A buy-back from segment `i` (`t` tokens for `q`): F gets back the claim it paid for them.
function _bandBuyBack(Book memory b, uint256 i, uint256 t, uint256 q) private pure {
uint256 tok0 = b.bandTokens[i];
uint256 claim = b.bandFClaim[i];
if (claim != 0 && tok0 != 0) {
uint256 r = _min(q, _min(claim, Wd.mulDiv(claim, t, tok0, true)));
b.bandF[i] += r;
b.bandFClaim[i] = claim - r;
}
b.bandTokens[i] = tok0 - t;
b.bandMoney[i] += q;
}
/// The slice `[p, hi)` holds no whole token (a helper: keeps `walkUp` under the stack limit).
function _noWholeToken(uint256 l, uint256 p, uint256 hi) private pure returns (bool) {
(bool ok, uint256 t) = Q.tokensBetween(l, p, hi, false);
return _ov(ok, t) == 0;
}
/// `range_up`: its first-time tokens (a range's resale is the segments'). Returns `(moved, rem)`.
function _rangeUp(Book memory b, uint256 i, uint256 l, uint256 hi, uint256 rem, WalkUp memory w, Fees.Acc memory acc)
private
pure
returns (bool moved, uint256)
{
Range memory r = b.ranges[i];
if (rem > 0 && b.sqrtP < hi) {
uint256 p0 = b.sqrtP;
(uint256 dt2, uint256 q2, uint256 p3) = _cpUp(l, p0, hi, rem, r.askLeft, false);
if (dt2 > 0) {
r.askLeft -= dt2;
b.sqrtP = p3;
if (p3 > b.sqrtLMax) b.sqrtLMax = p3; // the highest price first-time issuance reached
rem -= q2;
w.money += q2;
w.tokens += dt2;
w.fromFirst += dt2;
moved = true;
_piece1(w, r, p0, p3, q2, dt2, i);
_charge(b, acc, q2);
}
}
return (moved, rem);
}
// ------------------------------------------------------------------------------------------------------------ walk down
/// `walk_down_acc`: take at most `tokens` from a seller, every step's money charged into `acc` at the price where
/// the step ends (`_charge`).
function walkDown(Book memory b, uint256 tokens, Fees.Acc memory acc) internal pure returns (WalkDown memory w) {
uint256 rem = tokens;
while (rem > 0) {
if (w.steps == MAX_WALK_STEPS) {
w.budgetHit = true;
break;
}
w.steps += 1;
uint256 pc = _flatDown(b);
if (pc != NONE) {
uint256 take = _flatDownStep(b, pc, rem, w, acc);
if (take == 0) break;
rem -= take;
continue;
}
pc = _cpPieceDown(b);
if (pc != NONE) {
(uint256 lo,) = _cpEdges(b, pc);
uint256 l = _lDown(b, pc, lo);
(uint256 dx, uint256 q, uint256 p2) = _cpDown(l, lo, b.sqrtP, rem, _moneyOf(b, pc));
if (dx == 0) {
// the slice `(lo, p]` pays nothing for all it holds (dust a rounding left over a sliver):
// the walk looks further down
(bool okAll, uint256 mAll) = Q.moneyBetween(l, lo, b.sqrtP, false);
if (_ov(okAll, mAll) == 0) {
(bool f5, uint256 s5) = _nextDown(b);
if (!f5) break;
b.sqrtP = s5;
continue;
}
break;
}
q = _sellToSegment(b, w, pc - P_BAND, q, dx, p2 == lo);
b.sqrtP = p2;
rem -= dx;
w.tokens += dx;
w.money += q;
_charge(b, acc, q);
if (p2 == lo || _moneyOf(b, pc) == 0) {
if (p2 != lo) {
// ran dry short of its bottom (dust): look further down
(bool f3, uint256 s3) = _nextDown(b);
if (!f3) break;
b.sqrtP = s3;
}
continue;
}
break;
}
(bool f4, uint256 s4) = _nextDown(b);
if (!f4) break;
b.sqrtP = s4;
}
}
/// A sell's step on the flat `pc` (the F point or a flat range): the tokens it takes (0 = it pays nothing: stop).
/// Its own function: the walk's loop is at via-IR's stack limit.
function _flatDownStep(Book memory b, uint256 pc, uint256 rem, WalkDown memory w, Fees.Acc memory acc)
private
pure
returns (uint256 take)
{
uint256 s = _flatS(b, pc);
uint256 money = _moneyOf(b, pc);
(bool ok, uint256 can) = Q.flatTokensForMoney(s, money, false);
take = _min(_ov(ok, can), rem);
uint256 q;
if (take != 0) {
(bool ok2, uint256 m) = Q.flatMoneyForTokens(s, take, false);
q = _min(_ov(ok2, m), money);
}
if (q == 0) return 0;
w.tokens += take;
w.money += q;
_charge(b, acc, q);
if (pc == P_FLOOR) {
_sellToFloor(b, w, q, take);
} else {
Range memory r = b.ranges[pc];
_takePlace(r, q);
r.back += take;
w.fromPlace += q;
}
}
/// A sell's step at the F point (`floor_sell_pots`): C's parked money pays first, then K's; the tokens each buys
/// (`⌊money at f⌋`, together at most `take`) are that pot's; F the rest. Its own function: the walk's loop is at
/// via-IR's stack limit.
function _sellToFloor(Book memory b, WalkDown memory w, uint256 q, uint256 take) private pure {
uint256 ce = _min(q, b.ckAtF - b.kAtF);
uint256 ke = _min(q - ce, b.kAtF);
uint256 xc;
if (ce != 0) {
(bool okc, uint256 t) = Q.flatTokensForMoney(b.sqrtF, ce, false);
xc = _min(_ov(okc, t), take);
}
uint256 xk;
if (ke != 0) {
(bool okk, uint256 t) = Q.flatTokensForMoney(b.sqrtF, ke, false);
xk = _min(_ov(okk, t), take - xc);
}
b.ckAtF -= ce + ke;
b.kAtF -= ke;
b.ckFloorTokens += xc + xk;
b.kFloorTokens += xk;
b.floor -= q;
b.floorTokens += take;
w.fromF += q;
}
/// A sell's step in segment `i`: F's part first (at f, capped by its money and the tokens' flat value); the
/// seller never takes F's share past its f per token: returns the step's money. A segment walked
/// to its bottom (`atBottom`) sends its rounding rest to F's point (F's share as F's, the rest as C + K's at f, K's part when it is K's piece).
function _sellToSegment(Book memory b, WalkDown memory w, uint256 i, uint256 q, uint256 dx, bool atBottom)
private
pure
returns (uint256)
{
(bool okf, uint256 fv) = Q.flatMoneyForTokens(b.sqrtF, dx, false);
uint256 dF = _min(q, _min(b.bandF[i], _ov(okf, fv)));
q = _min(q, b.bandMoney[i] - b.bandF[i] + dF);
b.bandF[i] -= dF;
b.bandFClaim[i] += dF;
b.bandMoney[i] -= q;
b.bandTokens[i] += dx;
if (i < b.nC) w.fromC += q;
else w.fromK += q;
if (atBottom && b.bandMoney[i] > 0) {
b.floor += b.bandMoney[i];
uint256 rest = b.bandMoney[i] - b.bandF[i];
b.ckAtF += rest;
(bool k, uint256 ks) = kSeg(b);
if (k && ks == i) b.kAtF += rest;
b.bandMoney[i] = 0;
b.bandF[i] = 0;
}
return q;
}
// ------------------------------------------------------------------------------------------------------------ trade
/// `Book::fees_now`: the legs' rates on the curve at the price now, where a trade STARTS (`Fees.Acc`'s `pre`).
function feesNow(Book memory b) internal pure returns (uint32[5] memory) {
return feesAt(b, b.sqrtP);
}
/// `Book::fees_at`: the legs' rates at `√p` in this book's state (`fees::rates_at`: the flat legs before
/// graduation, else the curve).
function feesAt(Book memory b, uint256 sqrtP) internal pure returns (uint32[5] memory) {
if (!b.graduated) return Fees.pregrad(); // `Fees.ratesAt(graduated, false, …)` inline
return Fees.ppmAt(b.feePpm, b.feeStartPpm, b.sqrtFeeA, b.sqrtFeeB, sqrtP);
}
/// `Book::fees_at_memo`: `feesAt` at the price now with the trade's memo (`Fees.ppmAtMemo`).
function _feesNowMemo(Book memory b, Fees.Acc memory acc) private pure returns (uint32[5] memory) {
if (!b.graduated) return Fees.pregrad();
return Fees.ppmAtMemo(b.feePpm, b.feeStartPpm, b.sqrtFeeA, b.sqrtFeeB, b.sqrtP, acc);
}
/// `Book::fee_acc`: a trade's charge from the price now, its memo kept for the walk.
function _feeAcc(Book memory b) private pure returns (Fees.Acc memory acc) {
acc.pre = _feesNowMemo(b, acc);
}
/// `Book::charge`: one walk step's money `q` into the trade's charge, at the rates where the step ends.
function _charge(Book memory b, Fees.Acc memory acc, uint256 q) private pure {
if (q > 0) Fees.add(acc, q, _feesNowMemo(b, acc));
}
function _same(uint32[5] memory x, uint32[5] memory y) private pure returns (bool) {
for (uint256 i; i < 5; ++i) {
if (x[i] != y[i]) return false;
}
return true;
}
/// `buy_inner`'s walk: what `ppm` leaves of `gross`, every step charged at the cheaper of `ppm` and
/// the rates where it ends; when a leg is cheaper where that walk ends (`Fees.cheaper`), what the gross has left
/// walks on ONCE at those rates (the steps counted on). No curve (or above it): one walk.
function _buyWalk(Book memory b, uint256 gross, uint256 budget, Fees.Acc memory acc)
private
pure
returns (WalkUp memory w)
{
uint32[5] memory ppm = acc.pre;
w.pieces = new Piece[](PIECES_MAX);
walkUpFrom(b, budget, w, acc);
uint32[5] memory c = Fees.cheaper(ppm, _feesNowMemo(b, acc));
if (!_same(c, ppm) && w.tokens > 0) {
// the first walk paid at most `ppm` a step: what it spent fits the gross; the re-fill's steps pay at most `c`
(, uint256 t0) = Fees.accLegs(acc);
uint256 spent = w.money + t0;
if (spent > gross) revert IFloorAmm.Overflow();
uint256 budget2 = Fees.netFromGross(gross - spent, c);
if (budget2 > 0) walkUpFrom(b, budget2, w, acc);
}
}
// ------------------------------------------------------------------------------------------------------------ trade
/// Circulating after a trade: `supply::s_circ` = `live − for_sale − bought_back − dead`, 0 if it
/// would be negative.
function circ(Book memory b, SplitRow memory row) internal pure returns (uint256) {
uint256 out = forSale(b) + boughtBack(b) + row.dead;
return row.supply > out ? row.supply - out : 0;
}
/// `trade::buy` up to the split: spend at most `gross` (fees on top of the book's amount); the unspent part is
/// refunded. A graduated book then runs the split and the C + K re-lay on the returned walk (`FloorSplitRelay.buy`).
function buyWalk(Book memory b, uint256 gross, uint256 minTokens)
internal
pure
returns (BookBuy memory r, WalkUp memory w)
{
Fees.Acc memory acc = _feeAcc(b);
uint256 budget = Fees.netFromGross(gross, acc.pre);
if (budget == 0) revert IFloorAmm.NothingToDo();
uint256 before = b.sqrtP;
w = _buyWalk(b, gross, budget, acc);
if (w.tokens == 0) {
if (tokensHeld(b) == 0) revert IFloorAmm.MathFailed(ERR_BOOK_EMPTY);
revert IFloorAmm.NothingToDo();
}
if (w.tokens < minTokens) revert IFloorAmm.SlippageExceeded();
(uint256[5] memory fees, uint256 total) = Fees.accLegs(acc);
uint256 paid = w.money + total;
if (paid > gross) revert IFloorAmm.Overflow();
b.floor = _money(b.floor + fees[0]); // the Backing Fee joins F's own in the trade itself
r.gross = gross;
r.net = w.money;
r.refund = gross - paid;
r.tokens = w.tokens;
r.fees = fees;
r.fromResale = w.fromResale;
r.fromFirst = w.fromFirst;
r.steps = w.steps;
r.budgetHit = w.budgetHit;
r.graduatedNow = w.graduatedNow;
r.bondingMoney = w.bondingMoney;
r.sqrtBefore = before;
r.sqrtAfter = b.sqrtP; // the re-lay never moves the price
}
/// `trade::sell` up to the re-lay: sell `tokens`; what the bid cannot take (or the step bound leaves) is `unfilled`.
/// f never moves. A graduated book then re-lays C + K (`FloorSplitRelay.sell`, in `FloorSellEngine`).
function sellWalk(Book memory b, uint256 tokens, uint256 minOut) internal pure returns (BookSell memory r) {
if (tokens == 0) revert IFloorAmm.NothingToDo();
uint256 before = b.sqrtP;
// every step at the cheaper of the rates where the sell starts and where the step ends, leg by leg (`Fees.Acc`)
Fees.Acc memory acc = _feeAcc(b);
WalkDown memory w = walkDown(b, tokens, acc);
(uint256[5] memory fees, uint256 total) = Fees.accLegs(acc);
if (w.tokens == 0 || w.money <= total) {
if (w.money == 0 && moneyHeld(b) == 0) revert IFloorAmm.MathFailed(ERR_BOOK_EMPTY);
revert IFloorAmm.NothingToDo();
}
uint256 out = w.money - total;
if (out < minOut) revert IFloorAmm.SlippageExceeded();
b.floor = _money(b.floor + fees[0]); // the Backing leg joins F's own at the end of the sell
r.tokensIn = tokens;
r.unfilled = tokens - w.tokens;
r.gross = w.money;
r.fees = fees;
r.out = out;
r.steps = w.steps;
r.sqrtBefore = before;
r.sqrtAfter = b.sqrtP;
r.fromF = w.fromF;
r.fromK = w.fromK;
r.fromC = w.fromC;
r.fromPlace = w.fromPlace;
}
}
src/v2/math/FloorFeesV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {FloorFixed} from "../../libraries/FloorFixed.sol";
import {FloorWideV2 as Wd} from "./FloorWideV2.sol";
/// FLOOR v2 fee legs: five legs (backing, team, platform, $FLOOR, holder) in ppm of the
/// book amount, each charged ⌈net × ppm / 10⁶⌉; on a buy the fees sit on top of `net`.
library FloorFeesV2 {
uint256 internal constant PPM = 1_000_000;
uint256 private constant ONE = 1 << 64;
/// `fees::PREGRAD_PPM` legs: before graduation every buy and sell pays Platform 0.40 % + $FLOOR
/// 0.10 %, flat, on top; Backing, Team and Holder 0.
uint32 internal constant PREGRAD_PLATFORM_PPM = 4_000;
uint32 internal constant PREGRAD_FLOOR_PPM = 1_000;
/// `fees::PREGRAD_PPM`: [0, 0, Platform, $FLOOR, 0].
function pregrad() internal pure returns (uint32[5] memory f) {
(f[2], f[3]) = (PREGRAD_PLATFORM_PPM, PREGRAD_FLOOR_PPM);
}
/// `fees::rates_at`: `pregrad()` while not `graduated`, unless `own` (a genesis book keeps its
/// row's curve: `Book.own_fees`); else the curve (`ppmAt`).
function ratesAt(
bool graduated,
bool own,
uint32[5] memory end,
uint32[5] memory start,
uint256 sqrtA,
uint256 sqrtB,
uint256 sqrtP
) internal pure returns (uint32[5] memory) {
if (!graduated && !own) return pregrad();
return ppmAt(end, start, sqrtA, sqrtB, sqrtP);
}
/// `fees::ppm_at`: the legs' rates at `√p` on a row's fee curve: `start` at or under `√a`, `end`
/// (the row's `fee_ppm`) at or over `√b`, between them even in log2 of the price: `w = ⌊(lg √b − lg √p)·2⁶⁴ ÷ (lg √b
/// − lg √a)⌋` (`FloorFixed.log2X64`), each leg `⌈(start·w + end·(2⁶⁴ − w)) ÷ 2⁶⁴⌉`. `√b == 0` is no curve.
function ppmAt(uint32[5] memory end, uint32[5] memory start, uint256 sqrtA, uint256 sqrtB, uint256 sqrtP)
internal
pure
returns (uint32[5] memory f)
{
if (sqrtB == 0 || sqrtP >= sqrtB) return end;
if (sqrtP <= sqrtA) return start;
return _curve(end, start, _lg(sqrtA), _lg(sqrtB), _lg(sqrtP));
}
/// `fees::ppm_at_cached`: `ppmAt` bit for bit, its `log2X64` results kept in `a` (`fees::LgMemo`: the knots once,
/// the last `(√p, lg √p)`), so none is computed twice in one trade (EVM gas only).
function ppmAtMemo(uint32[5] memory end, uint32[5] memory start, uint256 sqrtA, uint256 sqrtB, uint256 sqrtP, Acc memory a)
internal
pure
returns (uint32[5] memory)
{
if (sqrtB == 0 || sqrtP >= sqrtB) return end;
if (sqrtP <= sqrtA) return start;
if (a.memo & 1 == 0) (a.la, a.lb, a.memo) = (_lg(sqrtA), _lg(sqrtB), a.memo | 1);
if (a.memo & 2 == 0 || a.lastP != sqrtP) (a.lastP, a.lastL, a.memo) = (sqrtP, _lg(sqrtP), a.memo | 2);
return _curve(end, start, a.la, a.lb, a.lastL);
}
/// The legs between the knots from the three logs (`ppm_at`'s body).
function _curve(uint32[5] memory end, uint32[5] memory start, uint256 la, uint256 lb, uint256 lp)
private
pure
returns (uint32[5] memory f)
{
uint256 w;
if (lb > la) {
w = Wd.mulDiv(lb > lp ? lb - lp : 0, ONE, lb - la, false); // lp ≥ la: w ≤ 2⁶⁴
if (w > ONE) w = ONE;
}
for (uint256 i; i < 5; ++i) {
uint256 x = uint256(start[i]) * w + uint256(end[i]) * (ONE - w);
f[i] = uint32((x + ONE - 1) >> 64);
}
}
/// `fees::cheaper`: leg by leg, the lower of two rate sets.
function cheaper(uint32[5] memory a, uint32[5] memory b) internal pure returns (uint32[5] memory f) {
for (uint256 i; i < 5; ++i) f[i] = a[i] < b[i] ? a[i] : b[i];
}
/// `fees::FeeAcc`: a trade's legs charged step by step, each step's money `q`
/// at the cheaper, leg by leg, of the rates where the trade started (`pre`) and where the step ends; each leg
/// `⌈Σ q·rate ÷ 10⁶⌉` once (`whole` + a remainder under 10⁶, as the Rust). No curve: `legs(money, pre)` bit for bit.
struct Acc {
uint32[5] pre;
uint256[5] whole;
uint256[5] rem;
// `fees::LgMemo` (`ppmAtMemo`), never part of the charge: bit 1 the knots' logs, bit 2 the last price's
uint256 memo;
uint256 la;
uint256 lb;
uint256 lastP;
uint256 lastL;
}
function newAcc(uint32[5] memory pre) internal pure returns (Acc memory a) {
a.pre = pre;
}
/// `FeeAcc::add`: one step's money `q`, its legs at `min(pre, at)`.
function add(Acc memory a, uint256 q, uint32[5] memory at) internal pure {
(uint256 qh, uint256 ql) = (q / PPM, q % PPM);
for (uint256 i; i < 5; ++i) {
uint256 r = a.pre[i] < at[i] ? a.pre[i] : at[i];
uint256 lo = ql * r;
uint256 rem = a.rem[i] + lo % PPM;
a.whole[i] += qh * r + lo / PPM + rem / PPM;
a.rem[i] = rem % PPM;
}
}
/// `FeeAcc::legs` and their `fee_total`.
function accLegs(Acc memory a) internal pure returns (uint256[5] memory f, uint256 total) {
for (uint256 i; i < 5; ++i) {
f[i] = a.whole[i] + (a.rem[i] > 0 ? 1 : 0);
total += f[i];
}
}
/// The Rust's `log2_x64(x).unwrap_or(0)`: 0 at 0 (√ prices are < 2¹²⁸).
function _lg(uint256 x) private pure returns (uint256) {
return x == 0 ? 0 : FloorFixed.log2X64(x);
}
function legs(uint256 net, uint32[5] memory ppm) internal pure returns (uint256[5] memory f, uint256 total) {
for (uint256 i; i < 5; ++i) {
f[i] = (net * ppm[i] + PPM - 1) / PPM;
total += f[i];
}
}
/// What a buy of `net` costs: `net + Σ legs(net)`.
function grossForNet(uint256 net, uint32[5] memory ppm) internal pure returns (uint256 g) {
g = net; // `legs`' total, without its array (EIP-170: the book engine)
for (uint256 i; i < 5; ++i) {
g += (net * ppm[i] + PPM - 1) / PPM;
}
}
/// Port of `net_from_gross`: the largest `net` with `net + Σ legs(net) ≤ gross`, from ⌊gross·10⁶/(10⁶+Σppm)⌋ up,
/// then down (each ceil leg adds < 1 unit, so at most 5 steps).
function netFromGross(uint256 gross, uint32[5] memory ppm) internal pure returns (uint256 net) {
uint256 sum = uint256(ppm[0]) + ppm[1] + ppm[2] + ppm[3] + ppm[4];
net = gross * PPM / (PPM + sum);
while (net < gross && grossForNet(net + 1, ppm) <= gross) ++net;
while (net > 0 && grossForNet(net, ppm) > gross) --net;
}
}
src/v2/math/FloorSqrtV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {FloorWideV2 as Wd} from "./FloorWideV2.sol";
/// Port of `floor_math::v2::sqrt` (Uniswap-v3 range math on Q56.72 √prices). Each
/// function returns `(ok, v)` where Rust returns `Option`: `ok == false` is Rust's `None` (an overflow past u128 or a
/// zero denominator). Rounding: `up == true` is `Round::Up`.
library FloorSqrtV2 {
uint256 internal constant FRAC = 72;
uint256 internal constant ONE = 1 << 72;
uint256 internal constant SQRT_TAIL_END = 1 << 127;
uint256 private constant U128 = type(uint128).max;
function _fit(uint256 v) private pure returns (bool, uint256) {
return v > U128 ? (false, 0) : (true, v);
}
/// `l·(b−a) ÷ 2^72`.
function moneyBetween(uint256 l, uint256 a, uint256 b, bool up) internal pure returns (bool, uint256) {
if (b < a) return (false, 0);
return _fit(Wd.mulShr(l, b - a, FRAC, up));
}
/// `l·(b−a)·2^72 ÷ b ÷ a` (two roundings in the same direction, as the Rust).
function tokensBetween(uint256 l, uint256 a, uint256 b, bool up) internal pure returns (bool, uint256) {
if (a == 0 || b < a) return (false, 0);
uint256 t = Wd.mulDiv(l * (b - a), ONE, b, up);
return _fit(Wd.divR(t, a, up));
}
/// `p + ⌊money·2^72 ÷ l⌋`.
function sqrtAfterMoney(uint256 l, uint256 p, uint256 money) internal pure returns (bool, uint256) {
if (l == 0) return (false, 0);
(bool ok, uint256 dp) = _fit(Wd.mulDiv(money, ONE, l, false));
if (!ok) return (false, 0);
return _fit(p + dp);
}
/// `⌈l·p·2^72 ÷ (l·2^72 + tokens·p)⌉`, one rounding; none when the denominator passes 2^256 or is 0.
function sqrtAfterTokens(uint256 l, uint256 p, uint256 tokens) internal pure returns (bool, uint256) {
if (l > U128 || p > U128 || tokens > U128) return (false, 0);
uint256 tp = tokens * p;
uint256 den;
unchecked {
den = (l << FRAC) + tp;
}
if (den < tp || den == 0) return (false, 0);
return _fit(Wd.mulDiv(l * p, ONE, den, true)); // ≤ p: never past 2^256
}
/// `⌈l·p·2^72 ÷ (l·2^72 − tokens·p)⌉`, one rounding; none when the denominator reaches 0 or below.
function sqrtAfterBuyingTokens(uint256 l, uint256 p, uint256 tokens) internal pure returns (bool, uint256) {
if (l > U128 || p > U128 || tokens > U128) return (false, 0);
uint256 tp = tokens * p;
uint256 lq = l << FRAC;
if (tp >= lq) return (false, 0);
uint256 den = lq - tp;
uint256 lp = l * p;
// the quotient passes u128 iff lp ≥ den·2^56 (den < 2^200 here): refuse before mulDiv could overflow
if (lp >> 56 >= den) return (false, 0);
return _fit(Wd.mulDiv(lp, ONE, den, true));
}
/// `⌊tokens·a·b ÷ 2^72 ÷ (b−a)⌋` (= one floor over `2^72·(b−a)`).
function liquidityForTokens(uint256 a, uint256 b, uint256 tokens) internal pure returns (bool, uint256) {
if (b <= a) return (false, 0);
return _fit(Wd.mulDiv(tokens * a, b, (b - a) << FRAC, false));
}
/// `⌊money·2^72 ÷ (b−a)⌋`.
function liquidityForMoney(uint256 a, uint256 b, uint256 money) internal pure returns (bool, uint256) {
if (b <= a) return (false, 0);
return _fit(Wd.mulDiv(money, ONE, b - a, false));
}
/// `money·2^144 ÷ s ÷ s` (two roundings in the same direction).
function flatTokensForMoney(uint256 s, uint256 money, bool up) internal pure returns (bool, uint256) {
if (s == 0) return (false, 0);
// money < 2^128, so money·2^144 < 2^272: the first quotient can pass 2^256 only when the result passes u128
// (s ≥ 1 makes the second quotient ≥ the first ÷ s); guard it as the Rust's `to_u128` would refuse
if (money >= (1 << 112) && s < (money >> 112) + 1) return (false, 0);
uint256 t = Wd.mulDiv(money, ONE * ONE, s, up);
return _fit(Wd.divR(t, s, up));
}
/// `tokens·s·s ÷ 2^144`.
function flatMoneyForTokens(uint256 s, uint256 tokens, bool up) internal pure returns (bool, uint256) {
return _fit(Wd.mulShr(tokens * s, s, 2 * FRAC, up));
}
/// `⌊√(money·2^144 ÷ tokens)⌋`. Money must be < 2^112 (pots are u64 by the quote cap); larger refuses.
function sqrtOfRatio(uint256 money, uint256 tokens) internal pure returns (bool, uint256) {
if (tokens == 0 || money >= (1 << 112)) return (false, 0);
return (true, Math.sqrt((money << 144) / tokens));
}
/// `⌊s · ⌊√((10⁴ − bps)·2^144 ÷ 10⁴)⌋ ÷ 2^72⌋`.
function sqrtScaleDownBps(uint256 s, uint256 bps) internal pure returns (bool, uint256) {
if (bps > 10_000) return (false, 0);
uint256 k = Math.sqrt(((10_000 - bps) << 144) / 10_000);
return _fit(Wd.mulShr(s, k, FRAC, false));
}
/// `s² ÷ 2^80` (Q64.64), saturating at u128.
function priceX64(uint256 s) internal pure returns (uint256) {
uint256 v = (s * s) >> 80;
return v > U128 ? U128 : v;
}
}
src/v2/math/FloorSupplyV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// Port of `floor_math::v2::supply`: circulating `s` and `s_below` (never 0).
library FloorSupplyV2 {
/// `(minted − burned) − for_sale − bought_back − dead`; `ok == false` on underflow (Rust `Err(Overflow)`).
function circulating(uint256 minted, uint256 burned, uint256 forSale, uint256 boughtBack, uint256 dead)
internal
pure
returns (bool ok, uint256 s)
{
uint256 out = burned + forSale + boughtBack + dead;
if (out > minted) return (false, 0);
return (true, minted - out);
}
/// `s − X_C − X_K`, saturating, at least 1.
function sBelow(uint256 s, uint256 xc, uint256 xk) internal pure returns (uint256) {
s = s > xc ? s - xc : 0;
s = s > xk ? s - xk : 0;
return s == 0 ? 1 : s;
}
}
src/v2/math/FloorWideV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// OpenZeppelin `Math.mulDiv` (5.x) in one assembly block per entry: the same results and the same reverts
/// (`Panic(0x12)` for a zero denominator, `Panic(0x11)` for a quotient past 2^256 or a round-up past it), so a caller
/// swaps `Math.mulDiv(x, y, d, r)` for `mulDiv(x, y, d, up)` bit for bit. EVM gas only: no rounding enum,
/// no checked arithmetic, one division when `x·y` fits 256 bits, and the
/// power-of-two denominators (`mulShr`) as shifts.
library FloorWideV2 {
/// `⌊x·y ÷ d⌋` (`up`: `⌈x·y ÷ d⌉`), the full 512-bit product.
function mulDiv(uint256 x, uint256 y, uint256 d, bool up) internal pure returns (uint256 r) {
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0))
let p0 := mul(x, y)
let p1 := sub(sub(mm, p0), lt(mm, p0))
switch p1
case 0 {
if iszero(d) {
mstore(0x00, 0x4e487b71)
mstore(0x20, 0x12)
revert(0x1c, 0x24)
}
r := div(p0, d)
}
default {
if iszero(gt(d, p1)) {
mstore(0x00, 0x4e487b71)
mstore(0x20, add(0x11, iszero(d)))
revert(0x1c, 0x24)
}
let rem := mulmod(x, y, d)
p1 := sub(p1, gt(rem, p0))
p0 := sub(p0, rem)
let twos := and(d, sub(0, d))
let dd := div(d, twos)
p0 := div(p0, twos)
twos := add(div(sub(0, twos), twos), 1)
p0 := or(p0, mul(p1, twos))
let inv := xor(mul(3, dd), 2)
inv := mul(inv, sub(2, mul(dd, inv)))
inv := mul(inv, sub(2, mul(dd, inv)))
inv := mul(inv, sub(2, mul(dd, inv)))
inv := mul(inv, sub(2, mul(dd, inv)))
inv := mul(inv, sub(2, mul(dd, inv)))
inv := mul(inv, sub(2, mul(dd, inv)))
r := mul(p0, inv)
}
if up {
if mulmod(x, y, d) {
if iszero(not(r)) {
mstore(0x00, 0x4e487b71)
mstore(0x20, 0x11)
revert(0x1c, 0x24)
}
r := add(r, 1)
}
}
}
}
/// `mulDiv(x, y, 2^k, up)` for `k < 256`: `x·y >> k` on 512 bits, the same reverts.
function mulShr(uint256 x, uint256 y, uint256 k, bool up) internal pure returns (uint256 r) {
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0))
let p0 := mul(x, y)
let p1 := sub(sub(mm, p0), lt(mm, p0))
if iszero(gt(shl(k, 1), p1)) {
mstore(0x00, 0x4e487b71)
mstore(0x20, 0x11)
revert(0x1c, 0x24)
}
r := or(shl(sub(256, k), p1), shr(k, p0))
if up {
if and(p0, sub(shl(k, 1), 1)) {
if iszero(not(r)) {
mstore(0x00, 0x4e487b71)
mstore(0x20, 0x11)
revert(0x1c, 0x24)
}
r := add(r, 1)
}
}
}
}
/// `⌊x ÷ d⌋` (`up`: `⌈x ÷ d⌉`) = `mulDiv(x, 1, d, up)`.
function divR(uint256 x, uint256 d, bool up) internal pure returns (uint256 r) {
assembly ("memory-safe") {
if iszero(d) {
mstore(0x00, 0x4e487b71)
mstore(0x20, 0x12)
revert(0x1c, 0x24)
}
r := add(div(x, d), and(iszero(iszero(up)), gt(mod(x, d), 0)))
}
}
}
src/v2/storage/FloorBookStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {BANDS_MAX as BANDS} from "../FloorBandsV2.sol";
/// FLOOR v2 storage: the ERC-7201 namespace `floor.book.v2`; comments give the slot each group starts on.
/// Append-only once deployed: never reorder, retype or delete a field. The rewards block is `RewardsV2`, per launch id.
library FloorBookStorage {
/// keccak256(abi.encode(uint256(keccak256("floor.book.v2")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant LAYOUT_SLOT_V2 = 0xaee77e3860c28a89897abcebdda362a1c55b0b4528a99e0dd4371ca6c458ee00;
bytes32 internal constant LOCK_TSLOT_V2 = 0xaee77e3860c28a89897abcebdda362a1c55b0b4528a99e0dd4371ca6c458eef0;
uint256 internal constant RANGES_MAX = 48;
uint256 internal constant BANDS_MAX = BANDS;
uint256 internal constant MAX_WALK_STEPS = 24;
struct LaunchV2 {
// slot 0: token (20) + presetId..graduated (6) + presetVersion (4)
address token;
uint8 presetId;
uint8 msClass;
uint8 flags;
uint8 nRanges;
uint8 nBands;
uint8 graduated;
uint32 presetVersion;
// slot 1: quote (20) + createdAt (8)
address quote;
uint64 createdAt;
// slot 2: creator (20) + createdBlock (8)
address creator;
uint64 createdBlock;
// slot 3
bytes32 presetHash;
// slot 4: creatorUnlockAt (8) + row constants (18) + feePpm (20 → next slot)
uint64 creatorUnlockAt;
uint16 phiBps;
uint16 wcBps;
uint16 psiTailBps;
uint16 teamBuyShareBps;
uint16 teamSlotMaxBps;
uint16 platformMsBps;
uint16 floorMsBps;
uint32[5] feePpm;
/// Unused: nothing reads or writes them.
uint16[BANDS_MAX] bandWidthBps;
uint16[BANDS_MAX] bandShareBps;
// prices (Q56.72)
uint128 sqrtP0;
uint128 sqrtP;
uint128 sqrtF;
uint128 sqrtLMax;
// supply and pots (token math units; money is uint128 on EVM)
uint64 supply;
uint64 deadTokens;
uint128 f;
uint128[BANDS_MAX] bandMoney;
// Milestones
uint128[4] msBooked;
uint128[4] msPaid;
uint64 lastBlock;
uint64 lastTs;
// ranges (struct-of-arrays, index 0..47)
uint128[48] rngSqrtA;
uint128[48] rngSqrtB;
uint64[48] rngTokens;
/// With a data contract (`data` set) this holds the tokens sold (`tokens − askLeft`, 0 at create);
/// `FloorBookStore.load` / `commit` and the views turn it back.
uint64[48] rngAskLeft;
uint64[48] rngBack;
uint128[48] rngPlace;
uint16[48] rngTheta;
uint16[48] rngPsi;
uint8[48] rngKind;
uint8[48] rngClass;
// tokens F, K and C bought; the bands' edges (descending, band 0 = C on top, K = [sqrtF, bandEdge[nBands]])
uint64 floorTokens;
uint64[BANDS_MAX] bandTokens;
uint128[BANDS_MAX + 1] bandEdge;
// The split: segments `0 .. nC` are C, `nC .. nBands` K; F's money and F's claim per segment;
// C + K money parked at f inside `f`, and the tokens it bought at the F point.
uint8 nC;
uint16 ckBps; // the row's C + K target share of circulating value (copied at create)
uint64 ckFloorTokens;
uint128 ckAtF;
uint128[BANDS_MAX] bandF;
uint128[BANDS_MAX] bandFClaim;
/// The running total of burns seen (math units); `noteBurn` adds each fall of the token's live supply.
uint64 incinerated;
/// The launch's data contract (`FloorBookStore.deployData`, written once at create; 0 = none).
address data;
// Each range's `ms_cap_ppm` (copied at create; 0 = no cap).
uint32[48] rngMsCap;
// The fee curve (copied at create): the legs' start rates and the knots' √ on this launch's quote
// (`sqrtFeeB` 0 = no curve).
uint32[5] feeStartPpm;
uint128 sqrtFeeA;
uint128 sqrtFeeB;
// K own pot (appended at the K-pot upgrade, never moved; API.md "K own pot"): K's parts of `ckAtF` /
// `ckFloorTokens`; `kpot` false = a launch from before the upgrade until its first trade runs the upgrade (D10).
KPotV2 kpot;
}
/// K own pot (one slot, read and written whole by `FloorBookStore`): K's parts of `ckAtF` / `ckFloorTokens`; `on`
/// false = a launch from before the K-pot upgrade until its first trade runs the upgrade (D10), true = two pots.
struct KPotV2 {
uint128 kAtF;
uint64 kFloorTokens;
bool on;
}
struct Layout {
mapping(uint256 => LaunchV2) launches;
/// The governance skip list the launch token reads (`holderSkipped`).
mapping(address => bool) holderSkip;
/// The Holder Fee goes to the holder index (true, the default) or the holder bucket.
bool holderFeeToIndex;
/// The launch's rewards block, by launch id.
mapping(uint256 => RewardsV2) rewards;
/// Every unit of `asset` held for v2 launches (pots, places, Milestones, every owed, the book's tokens).
/// Moved by exactly what enters or leaves; a new liability must move it.
mapping(address => uint256) held;
/// The last v2 launch id (ids start at 1; 0 = none).
uint256 launchCount;
/// The launch token → its launch id (`noteBurn`'s caller check; 0 = not a v2 launch token).
mapping(address => uint256) launchOfToken;
/// A v2 preset id → its canonical RowV2 bytes and the version count of its writes.
mapping(uint256 => bytes) presetRow;
mapping(uint256 => uint32) presetRowVersion;
/// The id the next `addPreset` must name (0 = nothing added yet: the first id is 1; the retired id 2 is skipped).
uint8 nextPresetId;
/// A row's listing state and its hash (`PresetCodecV2.rowHash`), by preset id.
mapping(uint256 => PresetMetaV2) presetMeta;
/// `pairId(id)` → the launch id, written once at create (0 = not a launch's pair id).
mapping(bytes32 => uint256) launchOfPair;
}
/// A v2 registry row's listing state (the bytes and version count are `presetRow` / `presetRowVersion`).
struct PresetMetaV2 {
bool enabled;
bool deleted;
bytes32 rowHash;
}
/// A launch's rewards block (money `uint128`, tokens math units). Members are wallets by place
/// (place 0 the creator); `slotWeightPpb` all 0 = no paid weights (the team rest is the creator's).
struct RewardsV2 {
uint128 creatorOwed;
uint128 platformOwed;
uint128 cutOwed; // the $FLOOR leg
uint128 holderOwed; // credited with `addReward`, debited by each bit-512 payout
uint128 slotOwedTotal;
uint64 teamShareBuyDay; // ⌊ts ÷ 86,400⌋ + 1 of the last `teamShareBuy` (0 = never)
uint128[10] slotOwed;
uint32[10] slotWeightPpb;
address[10] slotMember;
address[3] creatorRef;
uint128[3] creatorRefOwed;
uint64[10] slotBoughtOwed; // tokens bought with a Team Share, math units (claim bit 256)
uint64 slotBoughtTotal;
// The Team Buy's tokens held for the creator (math units, locked until `LaunchV2.creatorUnlockAt`, claim bit 128)
// and the Team Slot rate chosen at create.
uint64 teamBuyOwed;
uint16 slotRateBps;
/// The Team Buy split at its unlock by `slotWeightPpb` (math units, dust to place 0), per place, not yet claimed.
uint64[10] teamBuyPart;
/// Each place's share units; `slotWeightPpb` = `FloorRewards.slotWeights(slotShare)`.
uint64[10] slotShare;
uint64 slotShareTotal;
/// A pending member's handle (kind 1; `slotMember[i]` stays 0 until a bind).
bytes32[10] slotHandle;
}
/// The launch's pair id: `keccak256(abi.encode(FloorAmm, id))`, `address(this)` being the FloorAmm every hop runs as
/// (Uniswap v4's `PoolId` shape). Partners list the launch under it; the SDK's `evmPairId` derives the same.
function pairId(uint256 id) internal view returns (bytes32) {
return keccak256(abi.encode(address(this), id));
}
function layout() internal pure returns (Layout storage l) {
assembly ("memory-safe") {
l.slot := LAYOUT_SLOT_V2
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.