Verified contractExactMIT
DepositLaunch
Address0x8d1e102513f749531e4e620e5712cb0bf41df18c
- Balance
0 ETH
- Transactions
103
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- paris
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,362,672
- Creation transaction
- 0xf17974587f…4a24299363
24 files
- contracts/proto/DepositLaunch.solmain30.71 KB
- @openzeppelin/contracts/access/AccessControl.sol7.05 KB
- @openzeppelin/contracts/access/IAccessControl.sol3.26 KB
- @openzeppelin/contracts/access/Ownable.sol3.1 KB
- @openzeppelin/contracts/interfaces/draft-IERC6093.sol6.53 KB
- @openzeppelin/contracts/token/ERC20/ERC20.sol11.14 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol5.77 KB
- @openzeppelin/contracts/utils/Address.sol6.26 KB
- @openzeppelin/contracts/utils/Context.sol963 B
- @openzeppelin/contracts/utils/ReentrancyGuard.sol3.24 KB
- @openzeppelin/contracts/utils/introspection/ERC165.sol911 B
- @openzeppelin/contracts/utils/introspection/IERC165.sol869 B
- contracts/IReserveOracle.sol1.3 KB
- contracts/KeelHook.sol26.12 KB
- contracts/OlympusToken.sol1.26 KB
- contracts/StakedToken.sol7 KB
- contracts/Staking.sol15.56 KB
- contracts/Treasury.sol52.92 KB
- contracts/lib/FullMath.sol2.47 KB
- contracts/lib/TickMath.sol3.39 KB
- contracts/proto/DepositLaunchCheck.sol9.76 KB
contracts/proto/DepositLaunch.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../OlympusToken.sol";
import "../Treasury.sol";
import "../KeelHook.sol"; // the V4 types only
import "../lib/FullMath.sol";
import "../lib/TickMath.sol";
import "./DepositLaunchCheck.sol";
// ============================================================
// DepositLaunch.sol (13 Oct 2026, the founder: "a keel prototype ...
// no NFTs, a really low mcap proof of concept ... something trustless,
// and requires low funding")
//
// Keel's core with the ship sale replaced by a public deposit window.
// Nobody seeds it. Nobody holds a key after it opens.
//
// ARMED FIRST
// Deposits open only once arm() has read from the chain that the
// deploy gave every key up: the token's roles are held by exactly the
// expected contracts and nobody else (the token's roles are listable,
// ProtoToken), this contract holds the Treasury's RESERVE_MANAGER and
// owns the hook and the pool's contract, the Treasury is finalized with
// one reserve token and every slot wired as expected, the bonds and the
// locks have no owner and no other door, the deploy key holds no admin
// role, and the pool pieces all name the same pool. A deploy that died
// halfway, or handed a power to a second wallet, can never take a
// deposit. (The Treasury's own roles cannot be listed on chain; each
// one a hidden wallet could hold is checked harmless here where it can
// be, and scripts/proto/verify-roles.js replays every grant from the
// deploy block for the rest.)
//
// THE WINDOW
// From START to END anyone may deposit the reserve dollar (USDC), up
// to MAX_PER_WALLET each. There is no race: the window always runs to
// END. If more than MAX_RAISE comes in, everyone is filled pro rata and
// gets the rest back with their tokens (the review, 13 Oct: a cap that
// closed the window when full let 30 wallets of one bot take it all
// in the first minute).
//
// IF IT FAILS
// Under MIN_RAISE at END: every depositor takes their money back,
// whenever they like. And if the launch has not happened REFUND_AFTER
// past END for any reason at all, the same. The first refund in that
// second case closes the launch for good.
//
// THE LAUNCH, one transaction, anyone may send it, from END
// 1. min(deposits, MAX_RAISE) into the Treasury as reserves;
// 2. the supply created once: reserves / (1.3 x $1.00), so the floor
// opens at exactly $1.00 (a hair above, from rounding down);
// 3. DEPOSITORS_BPS of it kept here for the depositors, by dollars
// deposited; FOUNDER_BPS kept here for the founder, vesting;
// ANCHOR_BPS locked for good in the lock contract (below); the rest
// to the pool's contract (KeelLiquidity);
// 4. the pool priced at OPEN_TICK (about 2x the floor, fixed at
// deploy and checked below), the launch fee switched on, and the
// pool's share seeded into one permanent position from there up;
// 5. every power given up: MINTER, RESERVE_MANAGER, and the ownership
// of the hook and of KeelLiquidity (renounced, to nobody).
//
// THE ANCHOR LOCK (the review, 13 Oct)
// The lockers' dollars that arrive while nobody is locked went, whole,
// to whoever locked next, even a lock of one wei made a block later,
// and launch day is when the most of them arrive. So the launch locks
// ANCHOR_BPS of the supply for good, owned by this contract: the
// lockers' weight is never zero. What the anchor earns is not kept:
// sweep() sends it to SINK (the slice router), whose push() puts it
// back through the split, three quarters of it into reserves.
//
// AFTER
// claim(holder): anyone sends a depositor their tokens and, if the
// window was oversubscribed, the dollars that were not used.
// founderClaim(): anyone sends the founder what has vested: nothing
// until FOUNDER_CLIFF after the launch, then a straight line from the
// launch to all of it at FOUNDER_VEST_END.
// Or in equal steps (FOUNDER_STEPS, 15 Oct: 14, 30, 60 and 90 days).
//
// WHAT IT CANNOT DO
// No owner, no admin, no other way out for the dollars or the tokens.
// ============================================================
interface IKeelLiquidityDL {
function seed(int24 lower, int24 upper, uint128 liquidity) external;
function seeded() external view returns (bool);
function renounceOwnership() external;
function owner() external view returns (address);
function KEEL() external view returns (address);
function key() external view returns (address, address, uint24, int24, address);
}
interface IProtoHookDL {
function TREASURY() external view returns (address);
function KEEL() external view returns (address);
function RESERVE() external view returns (address);
function POOL_MANAGER() external view returns (address);
function owner() external view returns (address);
function liquidity() external view returns (address);
function poolSet() external view returns (bool);
function poolFee() external view returns (uint24);
function poolTickSpacing() external view returns (int24);
function setLaunch(uint64 start, uint32 siteOnly, uint16 startBPS, uint16 kneeBPS, uint32 kneeSeconds, uint32 endSeconds) external;
function renounceOwnership() external;
}
interface ILocksDL {
function lock(uint256 amount, uint256 term) external returns (uint256);
function setPermanent(uint256 id, bool on) external;
function claim(uint256 id) external;
function minTerm() external view returns (uint256);
function owner() external view returns (address);
function DIVIDEND_TOKEN() external view returns (address);
}
interface IBondsDL { // ProtoBonds: no owner, every term immutable
function TREASURY() external view returns (address);
function RESERVE() external view returns (address);
function LOCKS() external view returns (address);
function ORACLE() external view returns (address);
}
interface IPadGateDL { function allowed(address who) external view returns (bool); }
interface IWETHDL { function deposit() external payable; function withdraw(uint256) external; }
interface IPoolManagerDL {
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24);
}
contract DepositLaunch is ReentrancyGuard {
using SafeERC20 for IERC20;
// ── fixed at deploy ──
OlympusToken public immutable TOKEN;
Treasury public immutable TREASURY;
IERC20 public immutable RESERVE;
IProtoHookDL public immutable HOOK;
IKeelLiquidityDL public immutable LIQUIDITY;
IPoolManagerDL public immutable PM;
ILocksDL public immutable LOCKS;
IBondsDL public immutable BONDS;
address public immutable SINK;
address public immutable KEEL_FUND; // where the Treasury's "node" slice may go: Keel's share, or nobody
address public immutable PAD_FUND; // a launchpad launch (16 Oct 2026): its PadLockers (made by Hollow's PadLockersFactory), paid PAD_BPS of the raise
uint256 public immutable PAD_BPS; // at most 5%, taken before the supply is sized: the backing stays 1.3x
// the launchpad's HLO lockers (16 Oct 2026): PAD_FUND is then a PadLockers contract bound to this window
uint256 public immutable LOCKERS_BPS; // of the supply, minted to PAD_FUND for the registered lockers, at most 10%
uint256 public immutable HEAD_SECONDS; // the window's first seconds are for registered lockers only, at most a day
DepositLaunchCheck public immutable CHECK; // made in the constructor: arm()'s reading of the keys
address public immutable FOUNDER;
address public immutable DEPLOYER;
uint256 public immutable START;
uint256 public immutable END;
uint256 public immutable MIN_RAISE; // raw reserve units
uint256 public immutable MAX_RAISE; // the most the launch uses; any more comes back pro rata
uint256 public immutable MAX_PER_WALLET;
// the early close (13 Oct 2026, the founder: "if it fills quickly it should just launch ... about
// 1-2 hours after 1 eth is in there"): once FILL_AT has come in, the window closes FILL_DELAY later
uint256 public immutable FILL_AT; // 0 = never closes early
uint256 public immutable FILL_DELAY;
uint256 public filledAt; // when FILL_AT was first reached, 0 until then
uint256 public constant REFUND_AFTER = 14 days;
uint256 public immutable DEPOSITORS_BPS;
uint256 public immutable FOUNDER_BPS;
uint256 public immutable ANCHOR_BPS; // the rest goes to the pool
uint256 public immutable FOUNDER_CLIFF; // seconds after the launch
uint256 public immutable FOUNDER_VEST_END; // seconds after the launch
// OR in steps (15 Oct 2026, the founder: "14, 30, 60, 90 best for the 10% vest"): equal parts at
// up to four times after the launch, in order; 0 = no step. Steps and the line never both.
// packed: step i (seconds after the launch) in bits 64i..64i+63
uint256 public immutable FOUNDER_STEPS;
bool public immutable KEEL_IS_0;
uint24 public immutable POOL_FEE;
int24 public immutable TICK_SPACING;
int24 public immutable OPEN_TICK; // the position's bound AT the opening price
int24 public immutable FAR_TICK; // its other bound, toward a higher price
uint256 public immutable OPEN_MULTIPLE_X18; // the opening price over the $1.00 floor, at least
uint16 public immutable LAUNCH_START_BPS;
uint16 public immutable LAUNCH_KNEE_BPS;
uint32 public immutable LAUNCH_KNEE_SECONDS;
uint32 public immutable LAUNCH_END_SECONDS;
uint256 public immutable OPENING_FLOOR; // the floor at the launch, in the reserve per whole token, 18 decimals
bool public immutable NATIVE; // the reserve is WETH: deposits take ETH, refunds and claims pay ETH
// ── state ──
bool public armed;
mapping(address => uint256) public deposited;
uint256 public totalDeposited;
uint256 public depositorCount;
bool public launched;
bool public failed; // a refund has been taken: the launch is closed for good
uint256 public launchedAt;
uint256 public used; // the dollars the launch put in the vault
uint256 public supply; // created at the launch
uint256 public depositorTokens; // kept here for the depositors
uint256 public founderTokens; // kept here for the founder, vesting
uint256 public founderClaimed;
uint256 public anchorLock; // the permanent lock's id
mapping(address => bool) public claimed;
struct Addrs { address token; address treasury; address reserve; address hook; address liquidity; address pm; address locks; address bonds; address sink; address keelFund; address founder; address padFund; }
struct Window { uint256 start; uint256 end; uint256 minRaise; uint256 maxRaise; uint256 maxPerWallet; uint256 fillAt; uint256 fillDelay; uint256 padBPS; uint256 headSeconds; }
struct Shares { uint256 depositorsBPS; uint256 founderBPS; uint256 anchorBPS; uint256 founderCliff; uint256 founderVestEnd; uint256[4] founderSteps; uint256 lockersBPS; }
struct Pool { uint24 fee; int24 tickSpacing; int24 openTick; int24 farTick; uint256 openMultipleX18; uint256 openingFloor; bool native; }
struct LaunchFee { uint16 startBPS; uint16 kneeBPS; uint32 kneeSeconds; uint32 endSeconds; }
event Armed();
event Filled(uint256 total, uint256 closesAt);
event Deposited(address indexed who, uint256 amount, uint256 total);
event Refunded(address indexed who, uint256 amount);
event Launched(uint256 used, uint256 supply, uint256 toDepositors, uint256 toFounder, uint256 toAnchor, uint256 toPool, uint256 floor, uint160 sqrtPriceX96, uint128 liquidity);
event Claimed(address indexed who, uint256 tokens, uint256 dollarsBack);
event FounderClaimed(uint256 amount);
event Swept(uint256 amount);
constructor(Addrs memory a, Window memory w, Shares memory s, Pool memory p, LaunchFee memory f) {
require(a.token != address(0) && a.treasury != address(0) && a.reserve != address(0) && a.hook != address(0)
&& a.liquidity != address(0) && a.pm != address(0) && a.locks != address(0) && a.bonds != address(0) && a.sink != address(0)
&& a.founder != address(0), "Zero address");
require(w.start < w.end && w.end - w.start <= 30 days, "Window: start before end, 30 days at most");
require(w.minRaise > 0 && w.minRaise <= w.maxRaise && w.maxPerWallet > 0, "Raise limits");
require(s.depositorsBPS >= 5000 && s.founderBPS <= 1000 && s.anchorBPS > 0 && s.anchorBPS <= 100 && s.lockersBPS <= 1000
&& s.depositorsBPS + s.founderBPS + s.anchorBPS + s.lockersBPS <= 9000, "Shares");
require(s.founderCliff <= s.founderVestEnd && s.founderVestEnd <= 4 * 365 days, "Founder vesting");
require(s.founderSteps[0] == 0 || (s.founderVestEnd == 0 && s.founderSteps[0] <= 4 * 365 days), "Founder steps");
for (uint256 i = 1; i < 4; i++)
require(s.founderSteps[i] == 0 || (s.founderSteps[i - 1] > 0 && s.founderSteps[i] > s.founderSteps[i - 1] && s.founderSteps[i] <= 4 * 365 days), "Founder steps");
require(f.startBPS <= 9000 && f.kneeBPS <= f.startBPS && f.kneeSeconds < f.endSeconds && f.endSeconds <= 7 days, "Launch fee");
require(IKeelLiquidityDL(a.liquidity).KEEL() == a.token, "Not this token's pool contract");
require(IProtoHookDL(a.hook).TREASURY() == a.treasury && IProtoHookDL(a.hook).KEEL() == a.token
&& IProtoHookDL(a.hook).RESERVE() == a.reserve && IProtoHookDL(a.hook).POOL_MANAGER() == a.pm, "Not this token's hook");
require(ILocksDL(a.locks).DIVIDEND_TOKEN() == a.reserve, "Not this token's locks");
TOKEN = OlympusToken(a.token); TREASURY = Treasury(a.treasury); RESERVE = IERC20(a.reserve);
HOOK = IProtoHookDL(a.hook); LIQUIDITY = IKeelLiquidityDL(a.liquidity); PM = IPoolManagerDL(a.pm);
LOCKS = ILocksDL(a.locks); BONDS = IBondsDL(a.bonds); SINK = a.sink; KEEL_FUND = a.keelFund; FOUNDER = a.founder; DEPLOYER = msg.sender;
START = w.start; END = w.end; MIN_RAISE = w.minRaise; MAX_RAISE = w.maxRaise; MAX_PER_WALLET = w.maxPerWallet;
require(w.fillAt == 0 || (w.fillAt >= w.minRaise && w.fillDelay <= 7 days), "Early close: at or over the minimum, 7 days at most");
FILL_AT = w.fillAt; FILL_DELAY = w.fillDelay;
require(w.padBPS <= 500 && (w.padBPS == 0 || a.padFund != address(0)), "Pad fee");
PAD_FUND = a.padFund; PAD_BPS = w.padBPS;
require(w.headSeconds <= 1 days && w.headSeconds < w.end - w.start && ((s.lockersBPS == 0 && w.headSeconds == 0 && w.padBPS == 0) || a.padFund != address(0)), "Lockers");
LOCKERS_BPS = s.lockersBPS; HEAD_SECONDS = w.headSeconds;
CHECK = new DepositLaunchCheck();
DEPOSITORS_BPS = s.depositorsBPS; FOUNDER_BPS = s.founderBPS; ANCHOR_BPS = s.anchorBPS;
FOUNDER_CLIFF = s.founderCliff; FOUNDER_VEST_END = s.founderVestEnd;
FOUNDER_STEPS = s.founderSteps[0] | (s.founderSteps[1] << 64) | (s.founderSteps[2] << 128) | (s.founderSteps[3] << 192);
LAUNCH_START_BPS = f.startBPS; LAUNCH_KNEE_BPS = f.kneeBPS; LAUNCH_KNEE_SECONDS = f.kneeSeconds; LAUNCH_END_SECONDS = f.endSeconds;
bool keelIs0 = a.token < a.reserve;
KEEL_IS_0 = keelIs0;
require(p.tickSpacing > 0 && p.openTick % p.tickSpacing == 0 && p.farTick % p.tickSpacing == 0, "Ticks off the spacing");
// a higher KEEL price is a higher tick when KEEL is currency0, a lower one when it is currency1
require(keelIs0 ? p.farTick > p.openTick : p.farTick < p.openTick, "Far tick on the wrong side");
require(p.openMultipleX18 >= 1.5e18 && p.openMultipleX18 <= 5e18, "Open multiple 1.5x to 5x");
POOL_FEE = p.fee; TICK_SPACING = p.tickSpacing; OPEN_TICK = p.openTick; FAR_TICK = p.farTick;
OPEN_MULTIPLE_X18 = p.openMultipleX18;
require(p.openingFloor > 0, "No opening floor");
OPENING_FLOOR = p.openingFloor;
NATIVE = p.native;
// The opening price must be the multiple of the $1.00 floor, rounded up
// onto the spacing: never under it, at most about one spacing over.
uint8 rd = IERC20Metadata(a.reserve).decimals();
uint256 open = priceAt(_openSqrt(p.openTick, keelIs0), keelIs0, rd);
uint256 target = FullMath.mulDiv(p.openMultipleX18, p.openingFloor, 1e18);
require(open >= target && open <= FullMath.mulDiv(target, 10200, 10000), "Open tick is not the opening price");
// No ceiling (20 Oct 2026, the founder: "Why would we cap upside"): the hook refuses a swap that ends outside
// this one position, so its far bound is the highest price the pool can ever trade at. It may run to the
// edge of the tick range, a price no market reaches.
uint256 far = priceAt(TickMath.getSqrtRatioAtTick(p.farTick), keelIs0, rd);
require(far >= open * 2, "Range: at least 2x the open");
}
// ── armed: the deploy gave every key up ──
/// Why arm() would refuse right now, or "Ready".
function armCheck() public view returns (string memory) {
return CHECK.check(address(this));
}
function arm() external {
require(!armed, "Armed already");
string memory why = armCheck();
require(keccak256(bytes(why)) == keccak256("Ready"), why);
armed = true;
emit Armed();
}
// ── the window ──
function deposit(uint256 amount) external nonReentrant {
_take(msg.sender, amount);
RESERVE.safeTransferFrom(msg.sender, address(this), amount);
}
/// The same, paid in ETH (the reserve is WETH): wrapped here, nothing else differs.
function depositEth() external payable nonReentrant {
require(NATIVE, "This window takes the reserve token");
_take(msg.sender, msg.value);
IWETHDL(address(RESERVE)).deposit{value: msg.value}();
}
function _take(address from, uint256 amount) internal {
require(armed, "Not armed: the deploy has not given every key up");
require(block.timestamp >= START, "Not open yet");
require(block.timestamp < closesAt(), "The window has closed");
require(amount > 0, "Zero");
if (block.timestamp < START + HEAD_SECONDS) require(IPadGateDL(PAD_FUND).allowed(from), "Lockers first");
require(deposited[from] + amount <= MAX_PER_WALLET, "Over the limit a wallet");
if (deposited[from] == 0) depositorCount++;
deposited[from] += amount;
totalDeposited += amount;
emit Deposited(from, amount, totalDeposited);
if (filledAt == 0 && FILL_AT != 0 && totalDeposited >= FILL_AT) {
filledAt = block.timestamp;
emit Filled(totalDeposited, closesAt());
}
}
/// Pays the reserve out: as ETH when the reserve is WETH (as WETH if `to` cannot take ETH).
function _pay(address to, uint256 amt) internal {
if (!NATIVE) { RESERVE.safeTransfer(to, amt); return; }
IWETHDL(address(RESERVE)).withdraw(amt);
(bool ok, ) = to.call{value: amt}("");
if (!ok) { IWETHDL(address(RESERVE)).deposit{value: amt}(); RESERVE.safeTransfer(to, amt); }
}
receive() external payable { require(msg.sender == address(RESERVE), "Only the WETH contract"); }
/// When the window closes: END, or FILL_DELAY after FILL_AT came in, whichever is first.
function closesAt() public view returns (uint256) {
if (filledAt == 0) return END;
// the early close never starts inside the lockers' head start (the 16 Oct audit: lockers could
// fill and close the window before the public was let in)
uint256 from = filledAt > START + HEAD_SECONDS ? filledAt : START + HEAD_SECONDS;
uint256 early = from + FILL_DELAY;
return early < END ? early : END;
}
/// Whether refunds are open: under the minimum at the end, or no launch
/// REFUND_AFTER past the end, or a refund already taken.
function refundsOpen() public view returns (bool) {
if (launched) return false;
if (failed) return true;
if (block.timestamp < closesAt()) return false;
return totalDeposited < MIN_RAISE || block.timestamp >= closesAt() + REFUND_AFTER;
}
function refund() external nonReentrant {
require(refundsOpen(), "No refunds: the launch is on");
uint256 amt = deposited[msg.sender];
require(amt > 0, "Nothing to refund");
failed = true;
deposited[msg.sender] = 0;
_pay(msg.sender, amt);
emit Refunded(msg.sender, amt);
}
/// Whether launch() would go through now, and if not, why.
function ready() public view returns (bool, string memory) {
if (launched) return (false, "Launched");
if (failed) return (false, "Refunds taken: closed");
if (!armed) return (false, "Not armed");
if (block.timestamp < closesAt()) return (false, "The window is open");
if (totalDeposited < MIN_RAISE) return (false, "Under the minimum: refunds");
if (block.timestamp >= closesAt() + REFUND_AFTER) return (false, "Too late: refunds");
return (true, "Ready");
}
// ── the launch ──
function launch() external nonReentrant {
(bool ok, string memory why) = ready();
require(ok, why);
require(TOKEN.totalSupply() == 0 && !LIQUIDITY.seeded(), "Already minted or open");
launched = true;
launchedAt = block.timestamp;
// 1. the dollars into reserves: up to the cap; any more is refunded pro rata
uint256 u = totalDeposited < MAX_RAISE ? totalDeposited : MAX_RAISE;
used = u;
uint256 pad = (u * PAD_BPS) / 10000; // the launchpad's cut, to the burner, before the vault
if (pad > 0) RESERVE.safeTransfer(PAD_FUND, pad);
RESERVE.forceApprove(address(TREASURY), u - pad);
TREASURY.seedReserves(address(RESERVE), u - pad);
// 2. the supply, once, at a $1.00 floor
uint256 s = (TREASURY.totalReserves() * 1e18 * 1e18) / (OPENING_FLOOR * TREASURY.MIN_BACKING_RATIO());
require(s > 0, "Nothing to mint");
supply = s;
depositorTokens = (s * DEPOSITORS_BPS) / 10000;
founderTokens = (s * FOUNDER_BPS) / 10000;
uint256 anchor = (s * ANCHOR_BPS) / 10000;
uint256 lockers = (s * LOCKERS_BPS) / 10000; // the launchpad's HLO lockers, through PAD_FUND
uint256 toPool = s - depositorTokens - founderTokens - anchor - lockers;
TOKEN.mint(address(this), depositorTokens + founderTokens + anchor);
if (lockers > 0) TOKEN.mint(PAD_FUND, lockers);
TOKEN.mint(address(LIQUIDITY), toPool);
// the 1.3x rule, in the Treasury's own unit (minFloor: a whole ETH for Hollow, less for a billions-scale launch)
require(TOKEN.totalSupply() <= TREASURY.supplyCeiling(), "Under 1.3x backing");
require(TREASURY.priceFloor() >= OPENING_FLOOR, "Floor under the opening floor");
TREASURY.ratchet();
// 3. the anchor lock: the lockers' weight is never zero
IERC20(address(TOKEN)).forceApprove(address(LOCKS), anchor);
uint256 id = LOCKS.lock(anchor, LOCKS.minTerm());
LOCKS.setPermanent(id, true);
anchorLock = id;
// 4. the pool: priced, the launch fee on, seeded, in this transaction
PoolKey memory key = poolKey();
uint160 sqrtP = _openSqrt(OPEN_TICK, KEEL_IS_0);
PM.initialize(key, sqrtP);
HOOK.setLaunch(uint64(block.timestamp), 0, LAUNCH_START_BPS, LAUNCH_KNEE_BPS, LAUNCH_KNEE_SECONDS, LAUNCH_END_SECONDS);
(int24 lower, int24 upper) = KEEL_IS_0 ? (OPEN_TICK, FAR_TICK) : (FAR_TICK, OPEN_TICK);
uint128 liq = liquidityFor(toPool, TickMath.getSqrtRatioAtTick(lower), TickMath.getSqrtRatioAtTick(upper));
LIQUIDITY.seed(lower, upper, liq);
require(LIQUIDITY.seeded(), "Not seeded");
// 5. every power given up
TOKEN.renounceRole(TOKEN.MINTER_ROLE(), address(this));
TREASURY.renounceRole(TREASURY.RESERVE_MANAGER_ROLE(), address(this));
HOOK.renounceOwnership();
LIQUIDITY.renounceOwnership();
emit Launched(u, s, depositorTokens, founderTokens, anchor, toPool, TREASURY.priceFloor(), sqrtP, liq);
}
// ── after ──
/// What `who` is owed: tokens by dollars deposited, and the dollars the
/// launch did not use, if the window was oversubscribed.
function owed(address who) public view returns (uint256 tokens, uint256 dollarsBack) {
uint256 d = deposited[who];
if (!launched || claimed[who] || d == 0) return (0, 0);
tokens = (depositorTokens * d) / totalDeposited;
dollarsBack = (d * (totalDeposited - used)) / totalDeposited;
}
/// Sends `who` what they are owed. Anyone may send it; it only pays `who`.
function claim(address who) external nonReentrant {
address[] memory to = new address[](1);
to[0] = who;
_claim(who, to);
}
/// Claims your own tokens into wallets you name, in equal parts, none over 5% of the
/// launch supply (15 Oct 2026, the founder). Only you can send it; any ETH back comes to you.
function claimTo(address[] calldata to) external nonReentrant {
(uint256 t, ) = owed(msg.sender);
require(to.length > 0 && (t / to.length) * 20 <= supply, "Over 5% a wallet");
_claim(msg.sender, to);
}
function _claim(address who, address[] memory to) internal {
(uint256 t, uint256 back) = owed(who);
require(t > 0 || back > 0, "Nothing to claim");
claimed[who] = true;
uint256 n = to.length;
for (uint256 i; i < n; i++) if (t > 0) IERC20(address(TOKEN)).safeTransfer(to[i], i + 1 < n ? t / n : t - (t / n) * (n - 1));
if (back > 0) _pay(who, back);
emit Claimed(who, t, back);
}
function founderVested() public view returns (uint256) {
if (!launched) return 0;
uint256 t = block.timestamp - launchedAt;
uint256 steps = FOUNDER_STEPS;
if (steps > 0) { // equal parts, one at each step
uint256 n;
uint256 k;
for (; steps > 0; steps >>= 64) { n++; if (t >= uint64(steps)) k++; }
return (founderTokens * k) / n;
}
if (t < FOUNDER_CLIFF) return 0;
if (t >= FOUNDER_VEST_END || FOUNDER_VEST_END == 0) return founderTokens;
return (founderTokens * t) / FOUNDER_VEST_END;
}
/// Sends the founder what has vested. Anyone may send it.
function founderClaim() external nonReentrant {
uint256 amt = founderVested() - founderClaimed;
require(amt > 0, "Nothing vested");
founderClaimed += amt;
IERC20(address(TOKEN)).safeTransfer(FOUNDER, amt);
emit FounderClaimed(amt);
}
/// The anchor lock's dollars, to SINK, back into the split. Anyone may send it.
function sweep() external nonReentrant returns (uint256 got) {
require(launched, "Not launched");
uint256 before = RESERVE.balanceOf(address(this));
LOCKS.claim(anchorLock);
got = RESERVE.balanceOf(address(this)) - before;
RESERVE.safeTransfer(SINK, got);
emit Swept(got);
}
// ── views ──
function poolKey() public view returns (PoolKey memory) {
(address c0, address c1) = KEEL_IS_0 ? (address(TOKEN), address(RESERVE)) : (address(RESERVE), address(TOKEN));
return PoolKey(Currency.wrap(c0), Currency.wrap(c1), POOL_FEE, TICK_SPACING, address(HOOK));
}
/// Everything the site shows, in one call.
function status() external view returns (
uint256 start, uint256 end, uint256 total, uint256 minRaise, uint256 maxRaise, uint256 perWallet,
uint256 depositors, bool isLaunched, bool refunds, uint256 at, bool isArmed, uint256 usedRaise
) {
return (START, closesAt(), totalDeposited, MIN_RAISE, MAX_RAISE, MAX_PER_WALLET, depositorCount, launched, refundsOpen(), launchedAt, armed, used);
}
/// Dollars per whole token at a sqrt price, 18 decimals (KeelLiquidity.poolPrice's arithmetic).
function priceAt(uint160 sqrtP, bool keelIs0, uint8 reserveDecimals) public pure returns (uint256) {
uint256 scale = 10 ** (36 - uint256(reserveDecimals));
uint256 sp = uint256(sqrtP);
if (keelIs0) return FullMath.mulDiv(FullMath.mulDiv(sp, sp, 1 << 96), scale, 1 << 96);
return FullMath.mulDiv(FullMath.mulDiv(scale, 1 << 96, sp), 1 << 96, sp);
}
/// The sqrt price to initialise at: KEEL as currency0 one unit under the
/// tick, so [OPEN_TICK, FAR_TICK] sits wholly above the price and holds
/// only KEEL; as currency1 exactly at it, so [FAR_TICK, OPEN_TICK] sits
/// at or below it and holds only KEEL (scripts/lib/pool-price.js openAtTick).
function _openSqrt(int24 tick, bool keelIs0) internal pure returns (uint160) {
uint160 sp = TickMath.getSqrtRatioAtTick(tick);
return keelIs0 ? sp - 1 : sp;
}
/// The largest liquidity whose KEEL need, rounded up as the PoolManager
/// rounds, fits in `amount` (scripts/lib/pool-price.js liquidityForAmount).
function liquidityFor(uint256 amount, uint160 sa, uint160 sb) public view returns (uint128) {
uint256 a = sa; uint256 b = sb;
uint256 L = KEEL_IS_0
? FullMath.mulDiv(FullMath.mulDiv(amount, a, 1 << 96), b, b - a)
: FullMath.mulDiv(amount, 1 << 96, b - a);
for (uint256 i = 0; i < 8 && L > 0 && _need(L, a, b) > amount; i++) L--;
require(L > 0 && _need(L, a, b) <= amount && L <= type(uint128).max, "Liquidity out of range");
return uint128(L);
}
function _need(uint256 L, uint256 a, uint256 b) internal view returns (uint256) {
if (KEEL_IS_0) {
uint256 x = FullMath.mulDiv(L << 96, b - a, b);
if (mulmod(L << 96, b - a, b) > 0) x++;
return x / a + (x % a > 0 ? 1 : 0);
}
uint256 y = FullMath.mulDiv(L, b - a, 1 << 96);
return y + (mulmod(L, b - a, 1 << 96) > 0 ? 1 : 0);
}
}
@openzeppelin/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
@openzeppelin/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
@openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
@openzeppelin/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
contracts/IReserveOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// ============================================================
// IReserveOracle.sol
//
// USD price for reserve assets.
//
// The Treasury values every reserve unit at exactly $1.00. That is
// correct while every approved reserve is a sound dollar stablecoin
// and silently wrong the moment one is not: a depegged asset keeps
// counting at face value, the floor reports backing that does not
// exist, and redeemers draw against reserves that are not there.
//
// This is the only path by which redemption can drain the treasury.
// Sell pressure cannot — payout is always reserves/1.3, so 23.1% is
// mathematically unreachable. Reserve QUALITY is the exception.
//
// Implement with Chainlink USDC/USD, DAI/USD and equivalents. Those
// feeds exist and are well maintained; do not hand-roll this.
// ============================================================
interface IReserveOracle {
/// USD price of one whole token, 18 decimals. $1.00 == 1e18.
/// MUST revert on a stale or unset feed rather than returning 0.
function priceUSD(address token) external view returns (uint256);
/// False if the feed is missing, stale, or otherwise untrusted.
function healthy(address token) external view returns (bool);
}
contracts/KeelHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
// ============================================================
// KeelHook.sol
//
// A Uniswap V4 hook that does three things the token itself never
// has to:
//
// 1. ASYMMETRIC FEES. Buys pay the pool's LP fee only. Sells pay an
// extra slice on top, taken by the hook. The token is a plain
// ERC-20 with no transfer logic - every wallet, aggregator and
// bridge treats it as ordinary, because it is.
//
// 2. FEE ROUTING. The sell slice goes straight to Treasury.collectFees,
// where it splits like every other dollar of revenue and the
// remainder becomes reserves. Leaving raises the floor for whoever
// stays, on the DEX exactly as it does on redemption.
//
// 3. A TWAP. afterSwap records a price observation. The oracle reads
// a time-weighted average from these rather than a single spot
// value, which closes the manipulation window the spot-only V4
// oracle had to leave open.
//
// WHAT IT CANNOT DO
// Touch reserves. Pause the pool. Change the fee above the cap. Take
// anything from a buy. The hook's only power is to skim a bounded
// slice from sells and forward it.
//
// DEPLOYMENT
// V4 encodes hook permissions in the address. This contract needs
// the BEFORE_INITIALIZE, AFTER_SWAP and AFTER_SWAP_RETURNS_DELTA bits
// set (low 14 bits 0x2044), which means mining a CREATE2 salt until
// the address has them. The deploy script does this; see
// scripts/mine-hook-salt.js.
//
// VERIFY BEFORE MAINNET
// The IPoolManager and BalanceDelta interfaces below match v4-core
// at the commit noted. Confirm against the PoolManager actually
// deployed on Robinhood Chain before pointing real liquidity at it.
// ============================================================
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Treasury.sol";
// ── Minimal V4 surface ──────────────────────────────────────
// Only what this hook uses. Pinned to v4-core interfaces; the full
// dependency is heavy and most of it is irrelevant here.
type Currency is address;
type BalanceDelta is int256;
type BeforeSwapDelta is int256;
type PoolId is bytes32;
struct PoolKey {
Currency currency0;
Currency currency1;
uint24 fee;
int24 tickSpacing;
address hooks;
}
struct SwapParams {
bool zeroForOne;
int256 amountSpecified;
uint160 sqrtPriceLimitX96;
}
interface IPoolManager {
function take(Currency currency, address to, uint256 amount) external;
function extsload(bytes32 slot) external view returns (bytes32);
}
interface IQuotronBridge {
function notifyReceived(uint256 amount) external;
}
library BalanceDeltaLib {
function amount0(BalanceDelta d) internal pure returns (int128) {
return int128(BalanceDelta.unwrap(d) >> 128);
}
function amount1(BalanceDelta d) internal pure returns (int128) {
return int128(BalanceDelta.unwrap(d));
}
}
contract KeelHook is Ownable {
using SafeERC20 for IERC20;
using BalanceDeltaLib for BalanceDelta;
IPoolManager public immutable POOL_MANAGER;
Treasury public immutable TREASURY;
address public immutable KEEL;
address public immutable RESERVE;
/// Extra fee on sells, in basis points of the stablecoin received.
/// Taken by the hook from the swap output and forwarded to the
/// Treasury. Buys pay nothing here.
uint256 public sellFeeBPS = 300; // 3%
uint256 public constant MAX_SELL_FEE_BPS = 500; // 5%
/// A further slice of sells to the Quotrons ecosystem, via the
/// bridge. Off by default; on once the bridge is deployed. Capped
/// well below the treasury slice - this is a contribution, not a
/// competing claim on the floor.
address public quotronBridge;
uint256 public quotronFeeBPS = 0;
uint256 public constant MAX_QUOTRON_FEE_BPS = 100; // 1%
uint256 public totalToQuotrons;
// ── TWAP ────────────────────────────────────────────────
//
// A ring of (timestamp, tickCumulative) observations, the same
// shape V3 uses. consult(window) integrates over it.
struct Observation { uint32 blockTimestamp; int56 tickCumulative; bool initialized; }
Observation[1024] public observations;
uint16 public observationIndex;
uint16 public observationCardinality = 128;
// The ring keeps one observation per OBSERVATION_GAP seconds at most
// (3 Oct 2026 audit). It used to take one per swap-second, so 129
// swaps inside half an hour, from busy trading or dust swaps every
// 14 seconds, lapped the 30-minute window: the oracle went not-ready
// and bonds closed exactly when the market ran. The running total
// (accCum at accTs) is kept exact on every swap; the ring stores
// snapshots of it, so 128 slots always span at least 2,032 seconds.
uint32 public constant OBSERVATION_GAP = 16;
int56 public accCum;
uint32 public accTs;
int24 public lastTick;
bool public started; // true from the first real swap
uint24 public poolFee; // the one pool, by tier (setPool)
int24 public poolTickSpacing;
bool public poolSet;
uint256 public totalFeesForwarded;
uint256 public sellCount;
// ── The launch, in two phases (2 Oct 2026) ──────────────
//
// Phase one, from `launchStart` for `siteOnlySeconds`: the hook
// accepts a swap only when the PoolManager's caller is Keel's own
// router, so the site is the only door; the router adds the
// fleet-first window and the per-wallet cap. Phase two, from
// `openAt()`: any sender, and a launch fee on top of the standing
// one that opens at `launchStartBPS`, falls in a straight line to
// `launchKneeBPS` at `launchKneeSeconds`, then in a straight line
// to nothing at `launchEndSeconds`. On a sell the fee is the
// reserve asset and goes through Treasury.collectFees like every
// fee dollar; on a buy it is KEEL and is burned through
// Treasury.burnSupply, so a sniper's first-minute buy hands most
// of it to every holder. Set once, before the pool opens; the
// curve can never be raised afterwards. Phase 0 is "no launch set":
// nothing gated, nothing extra taken, which is what every test
// and the fork proof run under.
address public router;
uint64 public launchStart;
uint32 public siteOnlySeconds;
uint16 public launchStartBPS;
uint16 public launchKneeBPS;
uint32 public launchKneeSeconds;
uint32 public launchEndSeconds;
bool public launchSet;
uint256 public constant MAX_LAUNCH_FEE_BPS = 9000; // 90%
uint256 public totalLaunchFees; // reserve asset, through the split
uint256 public totalLaunchBurned; // KEEL burned on launch-day buys
// ── The creator fee ─────────────────────────────────────
//
// A share of every SELL to the founder split, on top of the
// standing fee: 1% at most, only ever lowerable, decaying in a
// straight line to nothing over `creatorSunsetSeconds` from the
// moment the pool opens (or from when it was set, if no launch is
// scheduled). Disclosed on the Verify page and the Record. Never
// scales with the launch curve.
uint16 public creatorFeeBPS;
address public creatorRecipient;
uint32 public creatorSunsetSeconds;
uint64 public creatorFrom;
uint256 public constant MAX_CREATOR_FEE_BPS = 100; // 1%
uint256 public totalToCreator;
/// `_owner` is explicit because this contract is deployed through a
/// CREATE2 factory to land at a salt-mined address. Inside the
/// constructor msg.sender is the FACTORY, and Ownable(msg.sender)
/// made the factory the owner - a contract with no admin path, so
/// setSellFeeBPS and setQuotronBridge were unreachable forever, and
/// the very first call to either in deploy.js reverted with
/// OwnableUnauthorizedAccount. Keel's fork test never noticed
/// because it never set the fee; Solum's did.
constructor(address _pm, address _treasury, address _keel, address _reserve, address _owner)
Ownable(_owner)
{
require(_pm != address(0) && _treasury != address(0)
&& _keel != address(0) && _reserve != address(0), "Zero address");
POOL_MANAGER = IPoolManager(_pm);
TREASURY = Treasury(_treasury);
KEEL = _keel;
RESERVE = _reserve;
// the observation ring starts at the FIRST REAL SWAP (_observe),
// not here: a genesis entry at tick 0 blended into the first
// half hour of trading as a price of one raw unit per raw unit
}
// ── Permissions ─────────────────────────────────────────
//
// V4 reads these bits from the hook ADDRESS, not from this
// function; the function exists so the deploy script can assert
// the mined address matches.
/// Returns (beforeInitialize, afterSwap, afterSwapReturnDelta).
/// Every other V4 permission is false. The deploy script asserts
/// the mined address encodes exactly these three bits: low 14 bits
/// 0x2044 (1<<13 | 1<<6 | 1<<2).
function getHookPermissions() external pure returns (bool, bool, bool) {
return (true, true, true);
}
// ── Who opens the pool (4 Oct 2026) ─────────────────────
/// Called by the PoolManager before any pool naming this hook is
/// initialised. Only the owner may initialise one. Without this,
/// anyone could initialise the empty KEEL pool at a price of their
/// choosing before seed-pool.js runs, and seed-pool.js would then
/// refuse to seed (the pool is not where the launch opens it): the
/// launch frozen by one transaction. With it, the price is set by
/// the same key, in the same run, that sets the launch and seeds.
/// Solum initialises at deploy, as the owner, so it is unaffected.
function beforeInitialize(address sender, PoolKey calldata key, uint160) external view returns (bytes4) {
require(msg.sender == address(POOL_MANAGER), "Only PoolManager");
require(key.hooks == address(this), "Not this hook");
require(sender == owner(), "Only the owner opens the pool");
return this.beforeInitialize.selector;
}
// ── The hook ────────────────────────────────────────────
/// Called by the PoolManager after every swap in this pool.
///
/// Determines direction. If KEEL went in and stablecoin came out,
/// it is a sell: take sellFeeBPS of the stablecoin output, forward
/// it to the Treasury, and return a delta telling the PoolManager
/// the swapper receives that much less.
///
/// Records a price observation either way.
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata
) external returns (bytes4, int128) {
require(msg.sender == address(POOL_MANAGER), "Only PoolManager");
// Only the KEEL pool may write this hook's state. Anyone can
// initialise a pool of any two tokens naming this hook; without
// this check a swap in such a pool would write its tick into the
// TWAP ring (2 Oct review, H1).
require(key.hooks == address(this), "Not this hook");
{
address c0 = Currency.unwrap(key.currency0); address c1 = Currency.unwrap(key.currency1);
require((c0 == KEEL && c1 == RESERVE) || (c0 == RESERVE && c1 == KEEL), "Not the KEEL pool");
if (poolSet) require(key.fee == poolFee && key.tickSpacing == poolTickSpacing, "Not the KEEL pool");
}
// phase one: the site is the only door
if (phase() == 1) require(sender == router && router != address(0), "Phase one: through the site only");
_observe(key);
// A sell is KEEL in, reserve out. zeroForOne means currency0 in.
bool isSell = (Currency.unwrap(key.currency0) == KEEL) ? params.zeroForOne : !params.zeroForOne;
(Currency unspec, uint256 gross) = _unspecified(key, params, delta);
if (gross == 0) return (this.afterSwap.selector, 0);
uint256 total = _charge(unspec, isSell, gross);
return (this.afterSwap.selector, int128(uint128(total)));
}
/// The hook may only adjust the UNSPECIFIED currency: the output of
/// an exact-input swap, the input of an exact-output one. The fee
/// is taken there, in whichever asset that is. The router always
/// swaps exact input, so a sell pays in dollars and a buy pays in
/// KEEL; a direct exact-output swap pays in the other asset, the
/// same value either way.
function _unspecified(PoolKey calldata key, SwapParams calldata params, BalanceDelta delta)
internal pure returns (Currency unspec, uint256 gross)
{
bool unspecIs0 = (params.amountSpecified < 0) ? !params.zeroForOne : params.zeroForOne;
int128 amt = unspecIs0 ? delta.amount0() : delta.amount1();
gross = amt < 0 ? uint256(uint128(-amt)) : uint256(uint128(amt));
unspec = unspecIs0 ? key.currency0 : key.currency1;
}
/// fee, launch fee, creator fee, Quotron fee, on `gross`.
function _fees(bool isSell, uint256 gross) internal view returns (uint256[4] memory f) {
f[0] = isSell ? (gross * sellFeeBPS) / 10000 : 0;
f[1] = (gross * launchFeeBPS()) / 10000;
f[2] = isSell ? (gross * creatorFeeNowBPS()) / 10000 : 0;
f[3] = (isSell && quotronBridge != address(0)) ? (gross * quotronFeeBPS) / 10000 : 0;
}
/// Take the fees out of the PoolManager and send each where it
/// goes. Paid in the reserve asset: the standing and launch fees
/// through the Treasury's split, the creator's slice to the founder
/// split, the Quotron slice to the bridge. Paid in KEEL: everything
/// burns, and the floor rises for every holder.
function _charge(Currency unspec, bool isSell, uint256 gross) internal returns (uint256 total) {
uint256[4] memory f = _fees(isSell, gross);
total = f[0] + f[1] + f[2] + f[3];
if (total == 0) return 0;
require(total < gross, "Fee exceeds the swap");
POOL_MANAGER.take(unspec, address(this), total);
if (Currency.unwrap(unspec) == KEEL) {
IERC20(KEEL).forceApprove(address(TREASURY), total);
TREASURY.burnSupply(total);
totalLaunchBurned += total;
emit LaunchFeeTaken(isSell, total, true);
} else {
if (f[0] + f[1] > 0) {
IERC20(RESERVE).forceApprove(address(TREASURY), f[0] + f[1]);
TREASURY.collectFees(RESERVE, f[0] + f[1]);
totalFeesForwarded += f[0];
totalLaunchFees += f[1];
if (f[1] > 0) emit LaunchFeeTaken(isSell, f[1], false);
}
if (f[2] > 0) {
IERC20(RESERVE).safeTransfer(creatorRecipient, f[2]);
totalToCreator += f[2];
emit CreatorFeeTaken(f[2]);
}
if (f[3] > 0) {
IERC20(RESERVE).safeTransfer(quotronBridge, f[3]);
IQuotronBridge(quotronBridge).notifyReceived(f[3]);
totalToQuotrons += f[3];
emit QuotronContribution(f[3]);
}
}
if (isSell) { sellCount++; emit SellFeeTaken(f[0], TREASURY.priceFloor()); }
}
// ── The launch schedule ─────────────────────────────────
/// 0: no launch set, or not started. 1: site only. 2: open.
/// Once the launch is set, the minutes before launchStart are phase
/// one too (3 Oct 2026 audit): seed-pool.js sets the start a few
/// minutes ahead and then seeds, and phase 0 there let any sender
/// buy the whole pool straight from the PoolManager. The router
/// keeps its own fleet window and cap for that stretch.
function phase() public view returns (uint8) {
if (!launchSet) return 0;
if (block.timestamp < uint256(launchStart) + siteOnlySeconds) return 1;
return 2;
}
function openAt() public view returns (uint256) { return launchSet ? uint256(launchStart) + siteOnlySeconds : 0; }
/// The launch fee right now, in basis points: the curve from the
/// moment the pool opens to everyone.
function launchFeeBPS() public view returns (uint256) {
if (phase() != 2) return 0;
uint256 t = block.timestamp - openAt();
if (t >= launchEndSeconds) return 0;
if (t < launchKneeSeconds) {
return launchStartBPS - ((uint256(launchStartBPS) - launchKneeBPS) * t) / launchKneeSeconds;
}
return launchKneeBPS - (uint256(launchKneeBPS) * (t - launchKneeSeconds)) / (launchEndSeconds - launchKneeSeconds);
}
/// The creator fee right now, in basis points, after its sunset.
function creatorFeeNowBPS() public view returns (uint256) {
if (creatorFeeBPS == 0 || creatorRecipient == address(0)) return 0;
uint256 from = creatorFrom;
if (launchSet) from = openAt();
if (block.timestamp <= from) return creatorFeeBPS;
uint256 t = block.timestamp - from;
if (creatorSunsetSeconds == 0 || t >= creatorSunsetSeconds) return creatorSunsetSeconds == 0 ? creatorFeeBPS : 0;
return creatorFeeBPS - (uint256(creatorFeeBPS) * t) / creatorSunsetSeconds;
}
/// The site's router, set once. Phase one admits nothing else.
function setRouter(address r) external onlyOwner {
require(router == address(0), "Already set");
require(r != address(0), "Zero address");
router = r;
emit RouterSet(r);
}
/// The whole schedule, set once, before the pool opens. Nothing
/// here can be raised, extended or moved afterwards.
function setLaunch(uint64 start, uint32 siteOnly, uint16 startBPS, uint16 kneeBPS, uint32 kneeSeconds, uint32 endSeconds)
external onlyOwner
{
require(!launchSet, "Launch already set");
require(start >= block.timestamp, "Start is in the past");
require(startBPS <= MAX_LAUNCH_FEE_BPS, "Above the 90% cap");
require(kneeBPS <= startBPS, "Knee above the start");
require(kneeSeconds < endSeconds, "Knee after the end");
// bounds (3 Oct 2026 audit): the gate and the fee curve cannot be
// set to freeze the pool for years
require(start <= block.timestamp + 1 days, "Start more than a day out");
require(siteOnly <= 7 days && endSeconds <= 7 days, "Schedule longer than a week");
launchStart = start; siteOnlySeconds = siteOnly;
launchStartBPS = startBPS; launchKneeBPS = kneeBPS; launchKneeSeconds = kneeSeconds; launchEndSeconds = endSeconds;
launchSet = true;
emit LaunchSet(start, uint256(start) + siteOnly, startBPS, kneeBPS, kneeSeconds, endSeconds);
}
/// The creator fee: at most 1%, and once set it can only go down.
/// The recipient and the sunset are fixed with the first set.
function setCreatorFee(uint16 bps, address recipient, uint32 sunsetSeconds) external onlyOwner {
require(bps <= MAX_CREATOR_FEE_BPS, "Above the 1% cap");
if (creatorRecipient != address(0)) {
require(bps <= creatorFeeBPS, "Can only be lowered");
require(recipient == creatorRecipient && sunsetSeconds == creatorSunsetSeconds, "Recipient and sunset are fixed");
} else {
require(recipient != address(0), "Zero recipient");
creatorRecipient = recipient;
creatorSunsetSeconds = sunsetSeconds;
creatorFrom = uint64(block.timestamp);
}
emit CreatorFeeSet(creatorFeeBPS, bps, recipient, sunsetSeconds);
creatorFeeBPS = bps;
}
// ── Observations ────────────────────────────────────────
function _observe(PoolKey calldata key) internal {
int24 tick = _currentTick(key);
uint32 nowTs = uint32(block.timestamp);
if (!started) {
observations[0] = Observation(nowTs, 0, true);
observationIndex = 0;
accCum = 0; accTs = nowTs;
lastTick = tick;
started = true;
return;
}
// the running total, exact: the tick that held since the last
// swap, for as long as it held
if (nowTs > accTs) {
accCum += int56(lastTick) * int56(uint56(nowTs - accTs));
accTs = nowTs;
}
lastTick = tick;
// a snapshot into the ring, at most one per OBSERVATION_GAP
Observation storage last = observations[observationIndex];
if (nowTs - last.blockTimestamp < OBSERVATION_GAP) return;
uint16 next = (observationIndex + 1) % observationCardinality;
observations[next] = Observation(nowTs, accCum, true);
observationIndex = next;
}
/// Reads slot0 of the pool via extsload. The slot layout is
/// v4-core's; confirm against the deployed PoolManager.
function _currentTick(PoolKey calldata key) internal view returns (int24) {
bytes32 poolId = keccak256(abi.encode(key));
bytes32 slot = keccak256(abi.encode(poolId, uint256(6))); // _pools mapping slot
bytes32 packed = POOL_MANAGER.extsload(slot);
// slot0: sqrtPriceX96 (160) | tick (24) | protocolFee (24) | lpFee (24)
return int24(int256(uint256(packed) >> 160));
}
/// Time-weighted average tick over `window` seconds.
function consultTick(uint32 window) public view returns (int24) {
require(window > 0, "Zero window");
Observation storage newest = observations[observationIndex];
require(newest.initialized, "No observations");
uint32 target = uint32(block.timestamp) - window;
// Walk back to the first observation at or before target.
uint16 i = observationIndex;
Observation storage older = newest;
for (uint16 n = 0; n < observationCardinality; n++) {
i = i == 0 ? observationCardinality - 1 : i - 1;
Observation storage o = observations[i];
if (!o.initialized) break;
older = o;
if (o.blockTimestamp <= target) break;
}
require(older.blockTimestamp < newest.blockTimestamp, "Insufficient history");
// the ring must reach back to the target; a short ring would
// otherwise return a shorter average and call it the window
require(older.blockTimestamp <= target, "Window not covered");
// now, from the exact running total rather than the newest snapshot
int56 newestCum = accCum + int56(lastTick) * int56(uint56(uint32(block.timestamp) - accTs));
uint32 span = uint32(block.timestamp) - older.blockTimestamp;
return int24((newestCum - older.tickCumulative) / int56(uint56(span)));
}
/// True once there is enough history to serve `window`.
function ready(uint32 window) external view returns (bool) {
if (!started) return false;
Observation storage newest = observations[observationIndex];
if (!newest.initialized) return false;
uint16 i = observationIndex;
for (uint16 n = 0; n < observationCardinality; n++) {
i = i == 0 ? observationCardinality - 1 : i - 1;
Observation storage o = observations[i];
if (!o.initialized) return false;
if (uint32(block.timestamp) - o.blockTimestamp >= window) return true;
}
return false;
}
// ── Admin ───────────────────────────────────────────────
/// The one pool this hook serves, by fee tier: set once at deploy,
/// so a second KEEL/USDG pool at another tier naming this hook
/// cannot write the ring either.
function setPool(uint24 fee, int24 tickSpacing) external onlyOwner {
require(!poolSet, "Pool already set");
poolFee = fee; poolTickSpacing = tickSpacing; poolSet = true;
emit PoolSet(fee, tickSpacing);
}
function setQuotronBridge(address b, uint256 bps) external onlyOwner {
require(bps <= MAX_QUOTRON_FEE_BPS, "Above cap");
quotronBridge = b;
quotronFeeBPS = b == address(0) ? 0 : bps;
emit QuotronBridgeSet(b, quotronFeeBPS);
}
function setSellFeeBPS(uint256 bps) external onlyOwner {
require(bps <= MAX_SELL_FEE_BPS, "Above cap");
emit SellFeeSet(sellFeeBPS, bps);
sellFeeBPS = bps;
}
event SellFeeTaken(uint256 amount, uint256 newFloor);
event QuotronContribution(uint256 amount);
event QuotronBridgeSet(address indexed bridge, uint256 bps);
event SellFeeSet(uint256 from, uint256 to);
event RouterSet(address indexed router);
event PoolSet(uint24 fee, int24 tickSpacing);
event LaunchSet(uint64 start, uint256 openAt, uint16 startBPS, uint16 kneeBPS, uint32 kneeSeconds, uint32 endSeconds);
event LaunchFeeTaken(bool sell, uint256 amount, bool burned);
event CreatorFeeSet(uint16 from, uint16 to, address indexed recipient, uint32 sunsetSeconds);
event CreatorFeeTaken(uint256 amount);
}
contracts/OlympusToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// ============================================================
// OlympusToken.sol v2 — No fixed hard cap
//
// Supply is governed dynamically by the Treasury's backing
// ratio ceiling (1.3x minimum). The Treasury contract enforces
// the ceiling on every mint — this contract simply executes.
// ============================================================
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract OlympusToken is ERC20, AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
constructor(
string memory name,
string memory symbol,
uint256 initialSupply
) ERC20(name, symbol) {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
if (initialSupply > 0) _mint(msg.sender, initialSupply);
}
function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
_mint(to, amount);
}
function burn(address from, uint256 amount) external onlyRole(BURNER_ROLE) {
_burn(from, amount);
}
}
contracts/StakedToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// ============================================================
// StakedToken.sol v3 — $sSLM
//
// PATCH NOTE (v2 -> v3):
// v2 wrote directly to _rawBalances and only emitted a
// Transfer event. ERC20's internal _balances were never
// touched, and _update() blocked every non-mint/burn move.
// Result: Staking.claim() reverted with "non-transferable"
// and no user could ever receive sSLM.
//
// v3 routes ALL movement through a single overridden
// _update() that operates on raw balances only. super._update
// is never called, so ERC20's _balances are unused by design.
// Transfers are permitted only when the staking contract is
// one of the two parties — sSLM remains non-transferable
// between users, which was the original intent.
// ============================================================
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./OlympusToken.sol";
interface IStakedTokenHook {
/// Called before any sSLM balance moves. Either address may be
/// zero, for a mint or a burn.
function settleOnTransfer(address from, address to) external;
}
contract StakedToken is ERC20, Ownable {
OlympusToken public immutable baseToken;
address public stakingContract;
// ── DIVIDEND SETTLEMENT ─────────────────────────────────
//
// Staking pays a second stream in the reserve asset, accounted
// per RAW balance. That accounting only works if a holder's
// ledger is settled BEFORE their raw balance changes.
//
// Staking settles on its own mints and burns. It cannot settle a
// transfer it never sees - and sSLM does move: BondDepository is
// an operator and hands a vested position straight to the bond
// buyer. Without this hook that buyer's dividend debt stays at
// zero, so they can immediately claim every dividend the protocol
// has ever accrued, pro-rata on a balance they have held for one
// block, out of the pool owed to existing stakers.
//
// So every balance change tells Staking first.
IStakedTokenHook public dividendHook;
/// Contracts permitted to hold and move sSLM. Needed so bond
/// payouts can vest as a staked position rather than sitting
/// idle. sSLM remains non-transferable between ordinary users.
mapping(address => bool) public isOperator;
// Index starts at 1e9 ("1.0") and grows with each rebase.
// Displayed balance = rawBalance * index / 1e9
uint256 public index = 1e9;
mapping(address => uint256) private _rawBalances;
uint256 private _totalRawSupply;
constructor(
address _baseToken,
string memory name,
string memory symbol
) ERC20(name, symbol) Ownable(msg.sender) {
baseToken = OlympusToken(_baseToken);
}
function setStakingContract(address _staking) external onlyOwner {
require(stakingContract == address(0), "Already set");
require(_staking != address(0), "Zero address");
stakingContract = _staking;
}
/// Set once, to the Staking contract. Permanent for the same
/// reason setStakingContract is: a hook that can be repointed is
/// a hook that can be repointed at an attacker's contract, and it
/// is called on every transfer.
function setDividendHook(address h) external onlyOwner {
require(address(dividendHook) == address(0), "Already set");
require(h != address(0), "Zero address");
dividendHook = IStakedTokenHook(h);
emit DividendHookSet(h);
}
function setOperator(address op, bool ok) external onlyOwner {
isOperator[op] = ok;
emit OperatorSet(op, ok);
}
modifier onlyStaking() {
require(msg.sender == stakingContract, "Only staking contract");
_;
}
// ── Mint / burn ─────────────────────────────────────────
// Both route through _mint/_burn -> _update, so raw balance
// accounting happens in exactly one place.
function mint(address to, uint256 amount) external onlyStaking {
_mint(to, amount);
}
function burn(address from, uint256 amount) external onlyStaking {
_burn(from, amount);
}
// ── Rebase ──────────────────────────────────────────────
function rebase(uint256 profit, uint256 totalStaked) external onlyStaking {
if (totalStaked == 0 || profit == 0) return;
index = index + (index * profit) / totalStaked;
emit Rebase(index, profit);
}
// ── Balance views driven by index ───────────────────────
function balanceOf(address account) public view override returns (uint256) {
return (_rawBalances[account] * index) / 1e9;
}
function totalSupply() public view override returns (uint256) {
return (_totalRawSupply * index) / 1e9;
}
function rawBalanceOf(address account) external view returns (uint256) {
return _rawBalances[account];
}
// ── Single accounting path ──────────────────────────────
// Mint: from == address(0)
// Burn: to == address(0)
// Transfer: only if staking contract is sender or receiver
function _update(address from, address to, uint256 value) internal override {
if (from != address(0) && to != address(0)) {
require(
from == stakingContract || to == stakingContract ||
isOperator[msg.sender] || isOperator[from] || isOperator[to],
"sToken: non-transferable"
);
}
// Bank what each side has accrued at the CURRENT balance,
// before that balance changes. Skipped when no hook is set,
// which is how the contract behaves in isolation and in the
// tests that predate dividends.
if (address(dividendHook) != address(0)) {
dividendHook.settleOnTransfer(from, to);
}
uint256 raw = (value * 1e9) / index;
require(raw > 0 || value == 0, "sToken: amount too small");
if (from == address(0)) {
_totalRawSupply += raw;
} else {
require(_rawBalances[from] >= raw, "sToken: insufficient balance");
_rawBalances[from] -= raw;
}
if (to == address(0)) {
_totalRawSupply -= raw;
} else {
_rawBalances[to] += raw;
}
emit Transfer(from, to, value);
}
event Rebase(uint256 newIndex, uint256 profit);
event OperatorSet(address indexed op, bool allowed);
event DividendHookSet(address indexed hook);
}
contracts/Staking.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// ============================================================
// Staking.sol - Stake base tokens, receive sTokens + rebases
//
// - Rebases only happen if the treasury can back new tokens
// - Rebase rate is capped (no infinite APY exploit)
// - Warmup period prevents flash-loan attacks
// - Revenue comes from bond profits, not pure inflation
// ============================================================
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./OlympusToken.sol";
import "./StakedToken.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./Treasury.sol";
contract Staking is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
OlympusToken public immutable TOKEN;
StakedToken public immutable sTOKEN;
address public treasury;
address public bondDepository;
struct Epoch {
uint256 duration;
uint256 number;
uint256 endTime;
uint256 distribute;
}
Epoch public epoch;
// ── HOW OFTEN, AND HOW MUCH ─────────────────────────────
//
// The cap is PER EPOCH, so it only means something alongside the
// epoch length. At eight-hour epochs, 0.5% each was about 1.5% a
// day. Shorten the epoch without shortening the cap and the same
// figure becomes an absurd rate; lengthen it and the payout
// crawls.
//
// Nothing here mints. Treasury.bondDeposit already minted the
// profit and checked it against the 1.3x ceiling, so this only
// decides how SMOOTHLY an amount that already exists is released.
// A short epoch with a proportionally smaller cap pays out the
// same total, just continuously - which is the point.
//
// MAX_REBASE_RATE is the hard ceiling on what governance may set,
// not the setting itself.
uint256 public constant MAX_REBASE_RATE = 50; // 0.5% per epoch, ever
uint256 public rebaseRateBPS = 50;
uint256 public warmupPeriod = 1;
struct Claim {
uint256 deposit;
uint256 gons;
uint256 expiry;
bool lock;
}
mapping(address => Claim) public warmupInfo;
constructor(
address _token,
address _sToken,
address _treasury,
uint256 _epochDuration,
uint256 _firstEpochTime
) Ownable(msg.sender) {
TOKEN = OlympusToken(_token);
sTOKEN = StakedToken(_sToken);
treasury = _treasury;
epoch = Epoch({
duration: _epochDuration,
number: 0,
endTime: _firstEpochTime,
distribute: 0
});
}
function stake(uint256 amount, address recipient) external nonReentrant {
require(amount > 0, "Cannot stake 0");
rebase();
TOKEN.transferFrom(msg.sender, address(this), amount);
_accountedSLM += amount;
// Store the position in INDEX units, not nominal tokens.
//
// Previously both fields held the nominal amount and claim()
// returned `deposit`. If a rebase landed during warmup, the
// sSLM held here grew but the claimer still received their
// original figure - the difference stranded in the contract,
// attributable to nobody. `gons` existed for this and was
// never used.
uint256 raw = (amount * 1e9) / sTOKEN.index();
Claim memory info = warmupInfo[recipient];
warmupInfo[recipient] = Claim({
deposit: info.deposit + amount,
gons: info.gons + raw,
expiry: epoch.number + warmupPeriod,
lock: false
});
sTOKEN.mint(address(this), amount);
emit Staked(recipient, amount);
}
function claim(address recipient) external nonReentrant {
if (address(dividendToken) != address(0)) _settle(recipient);
Claim memory info = warmupInfo[recipient];
require(info.gons > 0, "Nothing to claim");
require(epoch.number >= info.expiry, "Warmup not complete");
// Convert the index-adjusted position back at the CURRENT
// index, so a rebase during warmup accrues to the staker
// rather than being left behind.
uint256 value = (info.gons * sTOKEN.index()) / 1e9;
delete warmupInfo[recipient];
IERC20(address(sTOKEN)).transfer(recipient, value);
emit Claimed(recipient, value);
}
function unstake(uint256 amount, bool trigger) external nonReentrant {
require(amount > 0, "Cannot unstake 0");
if (address(dividendToken) != address(0)) _settle(msg.sender);
if (trigger) rebase();
sTOKEN.burn(msg.sender, amount);
require(TOKEN.balanceOf(address(this)) >= amount, "Insufficient liquidity");
_accountedSLM = _accountedSLM > amount ? _accountedSLM - amount : 0;
TOKEN.transfer(msg.sender, amount);
emit Unstaked(msg.sender, amount);
}
/// Advance every epoch that has passed, not just one.
///
/// It used to advance a single epoch per call. With eight-hour
/// epochs that was almost invisible; with epochs short enough to
/// feel continuous it would fall permanently behind, because the
/// clock only ever moved forward by one step however long nobody
/// called it.
///
/// Bounded, so a contract left alone for a year cannot be made
/// unusable by the cost of catching up. Anything beyond the bound
/// is caught up by calling again.
uint256 public constant MAX_CATCHUP = 200;
function rebase() public {
for (uint256 i = 0; i < MAX_CATCHUP; i++) {
if (epoch.endTime > block.timestamp) break;
_advance();
}
}
function _advance() internal {
{
epoch.number++;
epoch.endTime = epoch.endTime + epoch.duration;
uint256 totalStaked = sTOKEN.totalSupply();
if (totalStaked > 0 && epoch.distribute > 0) {
uint256 maxDistribute = (totalStaked * rebaseRateBPS) / 10000;
uint256 toDistribute = epoch.distribute > maxDistribute
? maxDistribute
: epoch.distribute;
// NO MINT HERE.
//
// Treasury.bondDeposit already minted `profit` to this
// contract and validated it against the 1.3x ceiling.
// Minting again would create supply with no reserves
// behind it, lower the floor on every rebase, and push
// the protocol through its own backing invariant with
// no check to stop it.
//
// Carry the remainder forward instead of discarding it,
// so a rebase capped at 0.5% pays out over more epochs
// rather than burning the excess.
epoch.distribute -= toDistribute;
sTOKEN.rebase(toDistribute, totalStaked);
emit EpochRebase(epoch.number, toDistribute, totalStaked);
} else {
emit EpochRebase(epoch.number, 0, totalStaked);
}
}
}
function queueDistribution(uint256 amount) external {
require(msg.sender == treasury, "Only treasury");
epoch.distribute += amount;
emit DistributionQueued(amount);
}
/// One-time link to the bond depository.
///
/// DELIBERATELY PERMANENT, like setStaking on the Treasury. A
/// depository that can be repointed is a depository that can be
/// repointed at an attacker's contract, and there is no timelock
/// here to make that visible in advance. The cost is that a
/// broken depository cannot be swapped - it would need a full
/// redeployment. That trade is taken knowingly.
function setBondDepository(address _bd) external onlyOwner {
require(bondDepository == address(0), "Already set");
require(_bd != address(0), "Zero address");
bondDepository = _bd;
}
/// Stake on behalf of a vesting bond position.
///
/// No warmup: the five-day vest is already a longer lock than
/// warmup provides, so the flash-loan protection warmup exists
/// for is redundant here. Caller must have transferred `amount`
/// of SLM to this contract first - checked, not trusted.
function stakeFor(address to, uint256 amount) external {
require(msg.sender == bondDepository, "Only bond depository");
if (address(dividendToken) != address(0)) _settle(to);
require(amount > 0, "Cannot stake 0");
require(
TOKEN.balanceOf(address(this)) >= _accountedSLM + amount,
"SLM not received"
);
_accountedSLM += amount;
rebase();
sTOKEN.mint(to, amount);
emit Staked(to, amount);
}
/// SLM this contract has accepted against sSLM claims. Used to
/// verify a bond payout actually arrived before minting sSLM.
uint256 private _accountedSLM;
// ══ Staker dividends ══════════════════════════════════════
//
// Rebase pays the staker share of each bond mint, so it pays
// nothing when bonds are closed - and bonds close whenever the
// premium is thin. This is the second stream: a slice of fee
// revenue, paid in the reserve asset, independent of bonding.
//
// Accounted per RAW balance rather than per sSLM, because sSLM
// grows on rebase while raw does not. Using sSLM would let a
// rebase silently redistribute unclaimed dividends.
//
// Pull-based: no loop over holders, no gas that scales with
// participation. A position opened today has no claim on
// revenue that arrived yesterday.
Treasury public treasuryC;
IERC20 public dividendToken;
uint256 public accPerRaw; // scaled 1e18
uint256 public totalDividends;
mapping(address => uint256) public divDebt;
mapping(address => uint256) public divOwed;
function setDividends(address _treasury, address _token) external onlyOwner {
require(address(dividendToken) == address(0), "Already set");
treasuryC = Treasury(_treasury);
dividendToken = IERC20(_token);
}
/// Pull the accumulated staker slice and credit it across every
/// raw unit staked. Permissionless - the funds can only ever
/// reach stakers.
function distributeDividends() external nonReentrant returns (uint256 amount) {
require(address(dividendToken) != address(0), "Dividends not wired");
// Warmup positions are held by this contract, not by a
// staker. Counting them would dilute every dividend into a
// balance nobody can ever claim from.
uint256 rawTotal = (sTOKEN.totalSupply() * 1e9) / sTOKEN.index();
uint256 rawHere = _rawOf(address(this));
rawTotal = rawTotal > rawHere ? rawTotal - rawHere : 0;
require(rawTotal > 0, "Nothing staked");
address t = address(dividendToken);
amount = treasuryC.stakerAllocation(t);
require(amount > 0, "Nothing to distribute");
uint256 before = dividendToken.balanceOf(address(this));
treasuryC.claimStakerAllocation(t, amount);
uint256 got = dividendToken.balanceOf(address(this)) - before;
accPerRaw += (got * 1e18) / rawTotal;
totalDividends += got;
emit DividendsDistributed(got, accPerRaw);
}
function _rawOf(address a) internal view returns (uint256) {
return (sTOKEN.balanceOf(a) * 1e9) / sTOKEN.index();
}
/// Move anything newly accrued into the owed ledger. Called
/// before any change to a holder's raw balance.
///
/// Skips this contract's own holdings. sSLM minted into warmup
/// sits here until claim(), and it is not a staker's position -
/// crediting it would move dividends into a balance that has no
/// way to withdraw them.
function _settle(address a) internal {
if (a == address(0) || a == address(this)) return;
uint256 raw = _rawOf(a);
uint256 acc = accPerRaw;
if (raw > 0 && acc > divDebt[a]) {
divOwed[a] += ((acc - divDebt[a]) * raw) / 1e18;
}
divDebt[a] = acc;
}
/// Called by the sSLM contract before any balance moves, so a
/// transfer settles both sides. Without it a holder who RECEIVES
/// sSLM by transfer - which is exactly what a bond redemption is -
/// keeps a dividend debt of zero and can immediately claim the
/// protocol's entire dividend history on a balance they have held
/// for one block.
function settleOnTransfer(address from, address to) external {
require(msg.sender == address(sTOKEN), "Only the staked token");
_settle(from);
_settle(to);
}
function pendingDividends(address a) external view returns (uint256) {
uint256 raw = _rawOf(a);
uint256 extra = (accPerRaw > divDebt[a] && raw > 0)
? ((accPerRaw - divDebt[a]) * raw) / 1e18 : 0;
return divOwed[a] + extra;
}
function claimDividends() external nonReentrant returns (uint256 amount) {
_settle(msg.sender);
amount = divOwed[msg.sender];
require(amount > 0, "Nothing pending");
divOwed[msg.sender] = 0;
dividendToken.safeTransfer(msg.sender, amount);
emit DividendsClaimed(msg.sender, amount);
}
event DividendsDistributed(uint256 amount, uint256 newAccPerRaw);
event DividendsClaimed(address indexed to, uint256 amount);
/// How long an epoch lasts, and how much may be released in each.
///
/// The two move together: halve the duration and the rate should
/// halve too, or the payout doubles. Setting them in one call
/// makes that hard to forget.
function setEpoch(uint256 duration, uint256 rateBPS) external onlyOwner {
require(duration >= 1 minutes && duration <= 7 days, "Duration out of range");
require(rateBPS > 0 && rateBPS <= MAX_REBASE_RATE, "Rate out of range");
rebase(); // settle the old cadence first
epoch.duration = duration;
rebaseRateBPS = rateBPS;
emit EpochSet(duration, rateBPS);
}
/// Epochs that have passed and not yet been applied. Zero means
/// the rebase is up to date.
function pendingEpochs() external view returns (uint256 n) {
if (epoch.endTime > block.timestamp) return 0;
n = ((block.timestamp - epoch.endTime) / epoch.duration) + 1;
if (n > MAX_CATCHUP) n = MAX_CATCHUP;
}
function setWarmupPeriod(uint256 _warmup) external onlyOwner {
require(_warmup <= 5, "Max 5 epochs");
warmupPeriod = _warmup;
}
function setTreasury(address _treasury) external onlyOwner {
require(_treasury != address(0), "Invalid address");
treasury = _treasury;
}
event Staked(address indexed user, uint256 amount);
event Claimed(address indexed user, uint256 amount);
event Unstaked(address indexed user, uint256 amount);
event EpochRebase(uint256 indexed epoch, uint256 distributed, uint256 totalStaked);
event DistributionQueued(uint256 amount);
event EpochSet(uint256 duration, uint256 rateBPS);
}
contracts/Treasury.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// ============================================================
// Treasury.sol v3 - Dynamic supply ceiling + burn mechanisms
//
// PATCH NOTES (v2 -> v3):
// 1. _normalizeDecimals() was a no-op returning its input.
// A 6-decimal USDC deposit of $100,000 registered as
// 0.0000000001 in totalReserves, destroying the backing
// ratio. Now scales any ERC20 to 18 decimals.
// 2. bondRedemptionBurn() burned from address(this) - the
// Treasury holds no SLM, so it always reverted. Now burns
// from the caller (BondDepository), which does hold the
// unvested payout.
// 3. Added burnFromCaller path used by BondDepository so the
// 1% redemption burn is actually reachable.
//
// SUPPLY MODEL (unchanged):
// maxSupply = totalReserves * 1e18 / MIN_BACKING_RATIO (1.3)
// ============================================================
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./OlympusToken.sol";
import "./Staking.sol";
import "./IReserveOracle.sol";
interface IOracleLock { function locked() external view returns (bool); }
contract Treasury is AccessControl, ReentrancyGuard {
using SafeERC20 for IERC20;
bytes32 public constant BOND_DEPOSITOR_ROLE = keccak256("BOND_DEPOSITOR");
bytes32 public constant RESERVE_MANAGER_ROLE = keccak256("RESERVE_MANAGER");
bytes32 public constant BURN_EXECUTOR_ROLE = keccak256("BURN_EXECUTOR");
bytes32 public constant FEE_COLLECTOR_ROLE = keccak256("FEE_COLLECTOR");
OlympusToken public immutable TOKEN;
Staking public staking;
mapping(address => bool) public isReserveToken;
address[] public reserveTokens;
uint256 public totalReserves;
/// Each token's recorded contribution to totalReserves, 18dp.
/// Needed so a delisted asset can be removed without guessing.
mapping(address => uint256) public reserveBalance;
// ── Reserve quality ─────────────────────────────────────
// Redemption cannot drain the treasury; a broken reserve can.
// The oracle is optional: without it every reserve is valued at
// par, which is the behaviour that already shipped.
IReserveOracle public reserveOracle;
uint256 public constant DEPEG_THRESHOLD = 0.95e18;
uint256 public constant MAX_SHORTFALL_BPS = 200;
// ── DELISTING, AND WHY IT IS SLOW ───────────────────────
//
// removeReserveToken is the ONE path exempt from the floor
// ratchet. It has to be: backing that is not worth what it claims
// was never really backing, and pretending otherwise is how a
// depeg becomes an unpayable promise.
//
// But it was instant, and rescueDelisted then sent the whole
// balance to any address the caller named. So with one approved
// reserve - which is what Solum has - a stablecoin dipping to
// $0.949 for a single block let whoever holds the admin key strip
// the recorded value from totalReserves, reset the high-water
// floor, and walk away with tokens still worth 95 cents. The
// protocol's one rule, defeated by a five percent wobble and one
// transaction.
//
// So delisting is now two steps with a day between them, and the
// price must still be broken when the second one lands. Real
// depegs last; the March 2023 USDC break was three days. Wobbles
// do not.
//
// And what comes out goes to an address set in advance, in the
// open, not one chosen at the moment of the call.
// ── WHAT MAY BE A RESERVE ───────────────────────────────
//
// totalReserves is a DOLLAR figure. collectFees and seedReserves
// scale a deposit by its decimals and add it at par - one token,
// one dollar - and redeem() pays out against that same figure.
//
// So an asset that is not worth a dollar cannot be a reserve. Add
// a tokenised stock at $300 and the Treasury records $1 of backing
// per token while redemption hands out one token per dollar
// claimed: the floor becomes fiction and the treasury empties at
// three hundred to one. Add $SLM itself and the backing is
// circular, which is the same thing said faster.
//
// Yield, tokenised equities and anything else that moves belong
// OUTSIDE this figure - earning on the earmarked slices, or in a
// separate vault whose profits arrive here as dollars through
// collectFees, the way RevenueAdapter already works. See
// docs/solum-treasury-strategy.md.
uint256 public constant MIN_RESERVE_PRICE = 0.98e18;
uint256 public constant MAX_RESERVE_PRICE = 1.02e18;
uint256 public constant DELIST_DELAY = 24 hours;
mapping(address => uint256) public depegFlaggedAt;
address public recoveryAddress;
uint256 public constant MIN_BACKING_RATIO = 13e17; // 1.3x
// The least the floor may be, in the reserve per whole token, 18 decimals (16 Oct 2026, Hollow's
// launchpad). 1e18 is the rule as it always was: every token backed by at least 1.3 whole units
// of the reserve. A launchpad token sized in billions sets it lower ONCE, before any supply exists
// (setMinFloor); the 1.3x rule then counts in that unit. Keel and Solum never call it.
uint256 public minFloor = 1e18;
uint256 public swapFeeBurnBPS = 0;
uint256 public constant MAX_BURN_BPS = 5000;
uint256 public constant BOND_REDEMPTION_BURN_BPS = 100; // 1%
uint256 public totalBurned;
uint256 public excessReserves;
// ── Swap fee intake ─────────────────────────────────────
// Fees accrue in a creator-fee wallet on the DEX. A collector
// sweeps them here. A slice is earmarked for agent gas; the
// rest becomes reserves and lifts the floor.
//
// CRITICAL: the agent slice is tracked SEPARATELY and never
// added to totalReserves. Money earmarked to leave must never
// back the floor, or every keeper withdrawal would silently
// lower it.
uint256 public agentAllocationBPS = 300; // 3%, per architecture spec
// 25% rather than 10%. In the engine configuration the "agent" is the
// operator running the bots that produce every dollar of revenue, and
// a slice that keeps them running is worth more than a slice that
// optimises reserves. The combined 40% cap still bounds the total.
uint256 public constant MAX_AGENT_ALLOCATION_BPS = 2500; // 10% ceiling
// ── Node dividend ───────────────────────────────────────
// A slice of fee revenue for Swarm Node holders, segregated on
// arrival exactly like the agent gas allocation.
//
// WHY IT CANNOT COME FROM THE TREASURY:
// The ratchet sets highWaterFloor to the current floor on every
// accretive action, so withdrawableReserves() is permanently
// zero. There is no spendable surplus in this protocol - every
// dollar of reserves is holding the floor up.
//
// So a dividend has to be taken BEFORE fees become reserves.
// Money that never backed the floor cannot lower it by leaving.
//
// THE TRADE IS EXACT AND VISIBLE:
// Floor growth is turnover x fee x premium-multiple. Every
// basis point routed to nodes is a basis point off that. At 10%
// the floor compounds at 6.4%/yr instead of 7.2%.
//
// Worth it only if node holders drive more than 10% additional
// volume - turnover being the other multiplier. That is the
// argument for the mechanism, and it is a bet, not a certainty.
uint256 public nodeAllocationBPS = 0; // off until nodes exist
uint256 public constant MAX_NODE_ALLOCATION_BPS = 2500; // 25% ceiling
address public nodeDistributor;
mapping(address => uint256) public nodeAllocation; // token => raw owed
// ── Staker dividend ─────────────────────────────────────
// Staking's only yield used to be the staker share of each bond
// mint, which meant no bonds paid no yield - and bonds close
// whenever the premium is thin. This gives staking a revenue
// source that does not depend on bond activity.
//
// Segregated on arrival like the others. Money that never backed
// the floor cannot lower it by leaving.
uint256 public stakerAllocationBPS = 0; // off until switched on
// ── Founder allocation ──────────────────────────────────
//
// A slice of fee revenue to the founders, paid in the reserve
// asset. Segregated on arrival like every other slice, so it
// never counts as backing and redemption can never reach it.
//
// Sits inside the same 40% combined cap. Capped on its own at 5%,
// because a founder fee above that is a founder fee that someone
// will reasonably ask about, and the answer should be "no".
uint256 public founderAllocationBPS = 0;
uint256 public constant MAX_FOUNDER_ALLOCATION_BPS = 500;
address public founderRecipient;
mapping(address => uint256) public founderAllocation;
uint256 public constant MAX_STAKER_ALLOCATION_BPS = 2500;
// ── Finalize ────────────────────────────────────────────
// The admin key can, until this is called, re-cut the revenue
// split, move the founder recipient and swap the reserve oracle.
// finalize() ends all six of those, and adding a reserve token,
// permanently. There is no
// function that sets this back; the tests prove the ABI has none.
// What stays adjustable afterwards is listed on the Verify tab:
// redemption fee and cap within their bounds, the burn share, the
// recovery address, and the two one-shot distributor setters.
bool public finalized;
/// After finalize() the admin can no longer hand out the roles that
/// mint (BOND_DEPOSITOR), reduce reserves (BURN_EXECUTOR) or move
/// them (RESERVE_MANAGER). A key that could still grant itself
/// BOND_DEPOSITOR after finalize could mint at exactly 1.3x the
/// floor with no premium (2 Oct review, M4). FEE_COLLECTOR stays
/// grantable: a new collector can only add money.
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
if (finalized) {
require(role != BOND_DEPOSITOR_ROLE && role != BURN_EXECUTOR_ROLE && role != RESERVE_MANAGER_ROLE, "Finalized");
}
_grantRole(role, account);
}
modifier notFinalized() {
require(!finalized, "Finalized");
_;
}
address public stakerDistributor;
mapping(address => uint256) public stakerAllocation;
mapping(address => uint256) public agentAllocation; // token => raw units owed to agent ops
uint256 public totalFeesCollected; // normalised, lifetime, reserves portion only
constructor(address _token) {
TOKEN = OlympusToken(_token);
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/// Anyone may push the ratchet up. Permissionless by design -
/// recording that the floor rose must never depend on an admin.
function ratchet() external {
_ratchet();
}
// ── Swap Fee Collection ─────────────────────────────────
// The path by which agent trading revenue reaches the floor.
// Caller must hold FEE_COLLECTOR_ROLE and have approved this
// contract for `amount` of `token`.
function collectFees(address token, uint256 amount)
external onlyRole(FEE_COLLECTOR_ROLE) nonReentrant
{
require(isReserveToken[token], "Not approved reserve");
require(amount > 0, "Nothing to collect");
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
_split(token, amount);
_updateExcessReserves();
_ratchet();
}
/// The split every revenue dollar goes through: the agent, node,
/// staker and founder slices are set aside first, the rest is
/// backing. Shared by collectFees and the premium on a bond. The
/// tokens must already be in this contract.
function _split(address token, uint256 amount) internal {
uint256 toAgents = (amount * agentAllocationBPS) / 10000;
uint256 toNodes = (amount * nodeAllocationBPS) / 10000;
uint256 toStakers = (amount * stakerAllocationBPS) / 10000;
uint256 toFounders = (amount * founderAllocationBPS) / 10000;
uint256 toReserves = amount - toAgents - toNodes - toStakers - toFounders;
if (toAgents > 0) agentAllocation[token] += toAgents;
if (toNodes > 0) nodeAllocation[token] += toNodes;
if (toStakers > 0) stakerAllocation[token] += toStakers;
if (toFounders > 0) founderAllocation[token] += toFounders;
uint256 normalised = _normalizeDecimals(token, toReserves);
totalReserves += normalised;
reserveBalance[token] += normalised;
totalFeesCollected += normalised;
emit FeesCollected(token, amount, toReserves, toAgents, toNodes);
}
/// Keeper pulls the earmarked agent slice to fund gas.
/// Cannot touch reserves - draws only from agentAllocation,
/// so the backing ratio is arithmetically untouched.
/// Once set, the only contract that may draw the agent slice. The
/// RevenueAdapter, which pays it to the operator and nowhere else.
/// Without it any RESERVE_MANAGER could send the slice anywhere,
/// which made finalizeOperator() a promise the Treasury did not keep.
address public agentWithdrawer;
function setAgentWithdrawer(address w) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(agentWithdrawer == address(0), "Already set");
require(w != address(0), "Zero address");
agentWithdrawer = w;
emit AgentWithdrawerSet(w);
}
function withdrawAgentAllocation(address token, address to, uint256 amount)
external onlyRole(RESERVE_MANAGER_ROLE) nonReentrant
{
require(agentWithdrawer == address(0) || msg.sender == agentWithdrawer, "Only the agent withdrawer");
require(to != address(0), "Zero address");
require(amount > 0, "Nothing to withdraw");
require(amount <= agentAllocation[token], "Exceeds agent allocation");
agentAllocation[token] -= amount;
IERC20(token).safeTransfer(to, amount);
emit AgentAllocationWithdrawn(token, to, amount);
}
/// The node distributor pulls the accumulated slice and splits it
/// among holders. Set once; a distributor that can be swapped is
/// a distributor that can be pointed anywhere.
function setNodeDistributor(address d) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(nodeDistributor == address(0), "Already set");
require(d != address(0), "Zero address");
nodeDistributor = d;
emit NodeDistributorSet(d);
}
function setNodeAllocationBPS(uint256 bps) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(bps <= MAX_NODE_ALLOCATION_BPS, "Max 25%");
require(agentAllocationBPS + bps <= 3000, "Agent + node above 30%");
require(agentAllocationBPS + bps + stakerAllocationBPS + founderAllocationBPS <= 4000,
"Allocations above 40%");
emit NodeAllocationSet(nodeAllocationBPS, bps);
nodeAllocationBPS = bps;
}
/// Only the distributor may draw it, and only from the segregated
/// slice. Reserves are untouchable through this path, so the floor
/// is arithmetically unaffected.
function claimNodeAllocation(address token, uint256 amount)
external nonReentrant
{
require(msg.sender == nodeDistributor, "Only node distributor");
require(amount > 0, "Nothing to claim");
require(amount <= nodeAllocation[token], "Exceeds node allocation");
nodeAllocation[token] -= amount;
IERC20(token).safeTransfer(nodeDistributor, amount);
emit NodeAllocationClaimed(token, amount);
}
function setStakerDistributor(address d) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(stakerDistributor == address(0), "Already set");
require(d != address(0), "Zero address");
stakerDistributor = d;
emit StakerDistributorSet(d);
}
function setStakerAllocationBPS(uint256 bps) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(bps <= MAX_STAKER_ALLOCATION_BPS, "Max 25%");
require(agentAllocationBPS + nodeAllocationBPS + founderAllocationBPS + bps <= 4000,
"Allocations above 40%");
emit StakerAllocationSet(stakerAllocationBPS, bps);
stakerAllocationBPS = bps;
}
function setFounderAllocationBPS(uint256 bps) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(bps <= MAX_FOUNDER_ALLOCATION_BPS, "Max 5%");
require(agentAllocationBPS + nodeAllocationBPS + stakerAllocationBPS + bps <= 4000,
"Allocations above 40%");
emit FounderAllocationSet(founderAllocationBPS, bps);
founderAllocationBPS = bps;
}
/// Where the founder slice goes. A FounderSplit contract if there
/// is more than one founder; a wallet if there is one.
function setFounderRecipient(address r) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(r != address(0), "Zero address");
emit FounderRecipientSet(founderRecipient, r);
founderRecipient = r;
}
/// Send the accumulated founder slice to the recipient.
/// Permissionless: nobody gains from calling it except the
/// founders, who are collecting what they are already owed.
function claimFounderAllocation(address token) external nonReentrant {
require(founderRecipient != address(0), "No founder recipient");
uint256 amount = founderAllocation[token];
require(amount > 0, "Nothing to claim");
founderAllocation[token] = 0;
IERC20(token).safeTransfer(founderRecipient, amount);
emit FounderAllocationClaimed(token, founderRecipient, amount);
}
function claimStakerAllocation(address token, uint256 amount)
external nonReentrant
{
require(msg.sender == stakerDistributor, "Only staker distributor");
require(amount > 0, "Nothing to claim");
require(amount <= stakerAllocation[token], "Exceeds staker allocation");
stakerAllocation[token] -= amount;
IERC20(token).safeTransfer(stakerDistributor, amount);
emit StakerAllocationClaimed(token, amount);
}
function setAgentAllocationBPS(uint256 bps) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(bps <= MAX_AGENT_ALLOCATION_BPS, "Max 25%");
require(bps + nodeAllocationBPS + stakerAllocationBPS + founderAllocationBPS <= 4000,
"Allocations above 40%");
emit AgentAllocationSet(agentAllocationBPS, bps);
agentAllocationBPS = bps;
}
// ── Bond Deposit ────────────────────────────────────────
// Caller (BondDepository) must hold reserveAmount and have
// approved this contract. See BondDepository.deposit().
//
// Where a bond's dollars go (2 Oct 2026). The part that backs the
// minted tokens at 1.3x the floor as it stood before the bond goes
// straight to reserves, before the mint, so the floor cannot move
// down by construction. Everything above that is the premium, and
// it goes through the same split as every revenue dollar: founders,
// nodes, lockers, and the rest to reserves. A bond that only filled
// the vault would raise the floor and pay lockers nothing; this way
// lockers and the nodes earn from every bond. The depository quotes
// the mint on the whole deposit against the 1.3x ceiling, and the
// ceiling is checked again here on what actually landed.
//
// No floor, no bond (4 Oct 2026 review, H1). Before Keel's genesis
// the floor and its high-water mark are 0, so the backing for a mint
// priced at that floor was $0 and the only limit was the 1.3x
// ceiling: whoever could grant BOND_DEPOSITOR could mint the whole
// ceiling for nothing, brick KeelGenesis and redeem the ticket money
// out. A bond now needs a floor that has been recorded first.
function bondDeposit(
address reserveToken,
uint256 reserveAmount,
uint256 tokensMinted,
uint256 profit
) external onlyRole(BOND_DEPOSITOR_ROLE) nonReentrant reservesSound floorMustHold {
_floorExists();
require(isReserveToken[reserveToken], "Not approved reserve");
require(tokensMinted + profit > 0, "Nothing to do");
IERC20(reserveToken).safeTransferFrom(msg.sender, address(this), reserveAmount);
// backing for the mint, at the floor before this bond
uint256 minted = tokensMinted + profit;
uint256 backing = (minted * priceFloor() / 1e18) * MIN_BACKING_RATIO / 1e18; // 18-dec
uint256 backingRaw = _denormalizeDecimals(reserveToken, backing);
if (backingRaw > reserveAmount) backingRaw = reserveAmount; // all of it, if the quote was that tight
uint256 premiumRaw = reserveAmount - backingRaw;
uint256 _n1 = _normalizeDecimals(reserveToken, backingRaw);
totalReserves += _n1;
reserveBalance[reserveToken] += _n1;
if (premiumRaw > 0) _split(reserveToken, premiumRaw);
uint256 newSupply = TOKEN.totalSupply() + minted;
uint256 maxAllowable = supplyCeiling();
require(newSupply <= maxAllowable, "Would breach 1.3x backing ceiling");
if (tokensMinted > 0) TOKEN.mint(msg.sender, tokensMinted);
if (profit > 0 && address(staking) != address(0)) {
TOKEN.mint(address(staking), profit);
staking.queueDistribution(profit);
}
_updateExcessReserves();
_ratchet();
emit BondDeposit(reserveToken, reserveAmount, tokensMinted, profit);
emit BondPremium(reserveToken, backingRaw, premiumRaw);
}
// ── Burn 1: Swap Fee Buyback & Burn ─────────────────────
function executeSwapFeeBurn(
address reserveToken,
uint256 reserveAmount,
uint256 tokenAmount
) external onlyRole(BURN_EXECUTOR_ROLE) nonReentrant floorMustHold {
_floorExists();
require(swapFeeBurnBPS > 0, "Burn rate not set by governance");
require(tokenAmount > 0, "Nothing to burn");
require(isReserveToken[reserveToken], "Not approved reserve");
TOKEN.burn(msg.sender, tokenAmount);
totalBurned += tokenAmount;
uint256 val = _normalizeDecimals(reserveToken, reserveAmount);
require(val <= totalReserves, "Exceeds reserves");
totalReserves -= val;
reserveBalance[reserveToken] = reserveBalance[reserveToken] > val ? reserveBalance[reserveToken] - val : 0;
_updateExcessReserves();
_ratchet();
emit TokensBurned(tokenAmount, "Swap fee buyback");
}
// ── Burn 2: Bond Redemption 1% Burn ─────────────────────
// PATCHED: burns from msg.sender (BondDepository), which
// holds the unvested payout. v2 burned from address(this).
function bondRedemptionBurn(uint256 payoutAmount)
external
onlyRole(BOND_DEPOSITOR_ROLE)
nonReentrant
returns (uint256 burnAmount, uint256 deliverAmount)
{
burnAmount = (payoutAmount * BOND_REDEMPTION_BURN_BPS) / 10000;
deliverAmount = payoutAmount - burnAmount;
if (burnAmount > 0) {
TOKEN.burn(msg.sender, burnAmount);
totalBurned += burnAmount;
_updateExcessReserves();
emit TokensBurned(burnAmount, "Bond redemption 1%");
}
}
// ── Burn 3: NFT Mint Proceeds Buyback & Burn ────────────
/// Burn supply without touching reserves.
///
/// Permissionless by design. The caller must first approve this
/// contract for the amount, and it burns their own tokens. There
/// is no attack here: destroying supply while reserves stay put
/// can only raise the floor, so anyone willing to pay for it is
/// doing every other holder a favour.
///
/// Used by the inventory escrow when captured supply cannot be
/// sold, and available to anyone else who wants it.
function burnSupply(uint256 amount) external nonReentrant {
require(amount > 0, "Nothing to burn");
IERC20(address(TOKEN)).safeTransferFrom(msg.sender, address(this), amount);
TOKEN.burn(address(this), amount);
totalBurned += amount;
_updateExcessReserves();
_ratchet();
emit TokensBurned(amount, "Supply burn");
}
function nftMintBurn(
address reserveToken,
uint256 reserveAmount,
uint256 tokenAmount
) external onlyRole(BURN_EXECUTOR_ROLE) nonReentrant {
require(tokenAmount > 0, "Nothing to burn");
require(isReserveToken[reserveToken], "Not approved reserve");
TOKEN.burn(msg.sender, tokenAmount);
totalBurned += tokenAmount;
IERC20(reserveToken).safeTransferFrom(msg.sender, address(this), reserveAmount);
uint256 _n2 = _normalizeDecimals(reserveToken, reserveAmount);
totalReserves += _n2;
reserveBalance[reserveToken] += _n2;
_updateExcessReserves();
_ratchet();
emit TokensBurned(tokenAmount, "NFT mint buyback");
}
// Burn 4 (expired bonds) was REMOVED.
//
// It was never reachable: BondDepository has no expiry logic and
// notes stay redeemable indefinitely. Dead privileged code is an
// audit finding whether or not it can be called.
//
// Expiry was not implemented instead, deliberately. A protocol
// whose central claim is that you can always exit should not have
// a mechanism that confiscates unclaimed tokens.
//
// Three burn paths remain: bond redemption, swap fee buyback and
// NFT mint. The documents should say three, not four.
// ── Redemption ──────────────────────────────────────────
// Burn $SLM, receive reserves at the price floor.
//
// WHY THIS EXISTS:
// Without it the floor is an accounting figure, not a price
// anyone is obliged to pay. Nothing stops the market trading
// below it, and the only defence is an agent with finite
// capital. With it, any discount to the floor is a risk-free
// arbitrage and the floor enforces itself.
//
// WHY IT STRENGTHENS THE PROTOCOL:
// Backing per token is reserves/supply. The floor is
// reserves/(supply * 1.3). Redemption therefore pays out LESS
// than the token's share of reserves, and the difference stays
// behind backing fewer tokens. Every redemption raises the
// floor for everyone who stays.
//
// The consequence is that last out wins, not first out. The
// usual bank-run incentive is inverted.
//
// NO PAUSE, BY DESIGN:
// Redemption is deliberately not pausable and not gated by any
// role. A floor that can be switched off during stress is not
// a floor. This is the one function that must work when
// everything else is on fire.
uint256 public redemptionFeeBPS = 50; // 0.5%, retained by treasury
uint256 public constant MAX_REDEMPTION_FEE_BPS = 200;
uint256 public maxRedemptionBPS = 100; // 1% of supply per call
uint256 public redemptionCooldown = 1 hours;
uint256 public totalRedeemed;
mapping(address => uint256) public lastRedemption;
/// Burn `amount` of $SLM and receive `reserveToken` at the floor.
///
/// SPLIT-EXTRACTION DEFENCE: because each burn nudges the floor
/// up, redeeming in many small calls would extract more than one
/// large call. Three limits close that: the whole amount is
/// priced off the floor as it stood at the start of this call,
/// a per-call size cap bounds the advantage to ~0.12%, and the
/// 0.5% fee exceeds it. Splitting loses money.
function redeem(address reserveToken, uint256 amount)
external nonReentrant floorMustHold returns (uint256 payout)
{
require(isReserveToken[reserveToken], "Not approved reserve");
require(amount > 0, "Nothing to redeem");
require(
block.timestamp >= lastRedemption[msg.sender] + redemptionCooldown,
"Redemption cooldown"
);
uint256 supply = TOKEN.totalSupply();
require(supply > 0, "No supply");
require(
amount <= (supply * maxRedemptionBPS) / 10000,
"Exceeds max redemption per call"
);
// Snapshot the floor BEFORE burning. The entire amount prices
// off this one value, so a large call is never worse than
// several small ones.
uint256 floorPrice = priceFloor();
require(floorPrice > 0, "No floor established");
uint256 gross = (amount * floorPrice) / 1e18;
uint256 fee = (gross * redemptionFeeBPS) / 10000;
uint256 net = gross - fee; // fee never leaves - it backs the floor
// Only reserves may be paid out. The agent gas allocation is
// earmarked and must never be reachable through this path.
uint256 raw = _denormalizeDecimals(reserveToken, net);
uint256 available = IERC20(reserveToken).balanceOf(address(this))
- agentAllocation[reserveToken]
- nodeAllocation[reserveToken]
- stakerAllocation[reserveToken]
- founderAllocation[reserveToken];
require(raw <= available, "Insufficient reserve token liquidity");
require(net <= totalReserves, "Insufficient reserves");
lastRedemption[msg.sender] = block.timestamp;
TOKEN.burn(msg.sender, amount);
totalBurned += amount;
totalReserves -= net;
reserveBalance[reserveToken] = reserveBalance[reserveToken] > net ? reserveBalance[reserveToken] - net : 0;
totalRedeemed += amount;
_updateExcessReserves();
_ratchet();
IERC20(reserveToken).safeTransfer(msg.sender, raw);
emit Redeemed(msg.sender, reserveToken, amount, raw, fee, priceFloor());
return raw;
}
/// What a redemption would pay right now, before executing.
function quoteRedemption(address reserveToken, uint256 amount)
external view returns (uint256 payout, uint256 fee)
{
uint256 floorPrice = priceFloor();
uint256 gross = (amount * floorPrice) / 1e18;
fee = (gross * redemptionFeeBPS) / 10000;
payout = _denormalizeDecimals(reserveToken, gross - fee);
}
// KNOWN AND ACCEPTED: SPLIT ADVANTAGE
//
// Redeeming in several small calls pays slightly more than one
// large call, because each burn lifts the floor before the next
// one prices against it. Measured advantage:
//
// 1% of supply -> 0.10% 5% of supply -> 0.54%
// 2% of supply -> 0.12% 10% of supply -> 1.20%
//
// The redemption fee does NOT defend against this. It is charged
// on both paths and cancels out. Only integral pricing -
// reserves * [1 - ((supply-n)/supply)^(1/1.3)]
// is split-invariant, and that needs fractional exponentiation.
// A fixed-point math library inside the one function that can
// never be paused is a worse risk than a 0.12% advantage.
//
// So it is bounded instead: a 2% size cap holds the advantage
// near 0.12%, and the per-address cooldown rate-limits it.
//
// Note this is not a drain. Both paths raise the floor. It is a
// small edge for sophisticated redeemers over naive ones, and
// it is documented rather than hidden.
uint256 public constant MIN_REDEMPTION_FEE_BPS = 50; // 0.5%
uint256 public constant MAX_REDEMPTION_SIZE_BPS = 200; // 2% of supply
function setRedemptionFeeBPS(uint256 bps) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(bps >= MIN_REDEMPTION_FEE_BPS, "Below split-extraction floor");
require(bps <= MAX_REDEMPTION_FEE_BPS, "Max 2%");
emit RedemptionFeeSet(redemptionFeeBPS, bps);
redemptionFeeBPS = bps;
}
function setMaxRedemptionBPS(uint256 bps) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(bps >= 10, "Min 0.1% of supply");
require(bps <= MAX_REDEMPTION_SIZE_BPS, "Above split-extraction ceiling");
maxRedemptionBPS = bps;
}
// ── Views ───────────────────────────────────────────────
function supplyCeiling() public view returns (uint256) {
return (totalReserves * 1e36) / (MIN_BACKING_RATIO * minFloor);
}
/// Once, before any supply exists: the floor's least value (see minFloor).
function setMinFloor(uint256 f) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(TOKEN.totalSupply() == 0 && highWaterFloor == 0, "Supply exists");
require(f > 0 && f <= 1e18, "Min floor out of range");
minFloor = f;
emit MinFloorSet(f);
}
function mintableHeadroom() public view returns (uint256) {
uint256 ceiling = supplyCeiling();
uint256 current = TOKEN.totalSupply();
return ceiling > current ? ceiling - current : 0;
}
function backingRatio() public view returns (uint256) {
uint256 supply = TOKEN.totalSupply();
if (supply == 0) return type(uint256).max;
return (totalReserves * 1e18) / supply;
}
/// USD of reserves behind each $SLM. Identical to backingRatio()
/// - kept because protocol_state.py and the technical overview
/// both call it by this name.
function backingPerToken() external view returns (uint256) {
return backingRatio();
}
// Price floor = reserves / (supply * 1.3), 18 decimals.
function priceFloor() public view returns (uint256) {
uint256 supply = TOKEN.totalSupply();
if (supply == 0) return 0;
return (totalReserves * 1e18 * 1e18) / (supply * MIN_BACKING_RATIO);
}
function netSupplyPressure() public view returns (int256) {
uint256 totalEverMinted = TOKEN.totalSupply() + totalBurned;
if (totalBurned >= totalEverMinted) return int256(totalBurned - totalEverMinted);
return -int256(totalEverMinted - totalBurned);
}
// ── Governance ──────────────────────────────────────────
function setSwapFeeBurnBPS(uint256 _bps) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_bps <= MAX_BURN_BPS, "Max 50%");
emit SwapFeeBurnUpdated(swapFeeBurnBPS, _bps);
swapFeeBurnBPS = _bps;
}
// ── Initial Funding ─────────────────────────────────────
// Capitalises the treasury WITHOUT minting any tokens.
function seedReserves(address reserveToken, uint256 amount)
external onlyRole(RESERVE_MANAGER_ROLE) nonReentrant
{
require(isReserveToken[reserveToken], "Not approved reserve");
require(amount > 0, "Nothing to seed");
IERC20(reserveToken).safeTransferFrom(msg.sender, address(this), amount);
uint256 _n3 = _normalizeDecimals(reserveToken, amount);
totalReserves += _n3;
reserveBalance[reserveToken] += _n3;
_updateExcessReserves();
_ratchet();
emit ReservesSeeded(reserveToken, amount);
}
// ── Reserve Management ──────────────────────────────────
// ── The ratchet ─────────────────────────────────────────
//
// highWaterFloor records the highest floor the protocol has ever
// reached. It only ever moves up.
//
// Without it, "the floor cannot fall" was false. excessReserves
// is defined as everything above 1.3x backing - which is exactly
// all accumulated floor growth. A single withdraw() call could
// take it and reset the floor to its opening value, erasing
// months of accretion. Markets could not do this. An admin could.
//
// With it, withdrawal is bounded by arithmetic rather than by
// policy. Reserves above the high-water mark can be deployed;
// reserves holding the floor up cannot be touched by anyone,
// including whoever holds every role.
uint256 public highWaterFloor;
/// Global invariant. Any function that can reduce reserves must
/// carry this. Guarding one function at a time is how the first
/// version left executeSwapFeeBurn able to walk straight past the
/// ratchet: it decremented totalReserves with no transfer and no
/// check, and the floor fell.
modifier floorMustHold() {
_;
require(priceFloor() >= highWaterFloor, "Floor ratchet violated");
}
/// Every path that mints, or takes reserves off the books, needs a
/// recorded floor (4 Oct 2026 review, H1). Before one exists (Keel
/// before genesis: no KEEL, a $0 floor) the ratchet guards nothing,
/// because a $0 floor always holds. Redemption needs a floor too,
/// and checks it itself.
function _floorExists() internal view {
require(highWaterFloor > 0, "No floor yet");
}
/// Called after any operation that can move the floor.
function _ratchet() internal {
uint256 f = priceFloor();
if (f > highWaterFloor) {
highWaterFloor = f;
emit FloorRatcheted(f);
}
}
/// Reserves that may leave without dropping the floor below its
/// all-time high. This is the real withdrawable figure - always
/// less than or equal to excessReserves.
function withdrawableReserves() public view returns (uint256) {
uint256 supply = TOKEN.totalSupply();
// No KEEL yet (Keel's genesis, 4 Oct 2026): every reserve dollar
// is waiting to back the supply created when trading opens, so
// none of it is withdrawable. This used to return all of it.
if (supply == 0) return 0;
// reserves needed to hold highWaterFloor
uint256 needed = (highWaterFloor * supply * MIN_BACKING_RATIO) / 1e36;
return totalReserves > needed ? totalReserves - needed : 0;
}
function withdraw(address reserveToken, uint256 amount)
external onlyRole(RESERVE_MANAGER_ROLE) nonReentrant floorMustHold
{
_floorExists();
require(isReserveToken[reserveToken], "Not a reserve token");
uint256 value = _normalizeDecimals(reserveToken, amount);
require(value <= excessReserves, "Insufficient excess reserves");
require(value <= withdrawableReserves(), "Would lower the floor");
totalReserves -= value;
reserveBalance[reserveToken] = reserveBalance[reserveToken] > value ? reserveBalance[reserveToken] - value : 0;
_updateExcessReserves();
IERC20(reserveToken).safeTransfer(msg.sender, amount);
emit Withdrawal(reserveToken, amount);
}
// ── Admin ───────────────────────────────────────────────
function setStaking(address _staking) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(address(staking) == address(0), "Already set");
staking = Staking(_staking);
}
/// One way. After this, no key can change the revenue split, the
/// founder recipient or the reserve oracle. The event records the
/// split that was frozen so the Record can show it.
function finalize() external onlyRole(DEFAULT_ADMIN_ROLE) {
require(!finalized, "Already finalized");
require(founderAllocationBPS == 0 || founderRecipient != address(0), "Founder recipient unset");
// a wired reserve oracle must be locked first, or its owner could
// still fake a depeg after finalize (3 Oct 2026 audit)
if (address(reserveOracle) != address(0)) {
(bool ok, bytes memory r) = address(reserveOracle).staticcall(abi.encodeWithSelector(IOracleLock.locked.selector));
require(ok && r.length == 32 && abi.decode(r, (bool)), "Lock the reserve oracle first");
}
finalized = true;
emit Finalized(msg.sender, agentAllocationBPS, nodeAllocationBPS,
stakerAllocationBPS, founderAllocationBPS, founderRecipient);
}
/// Wire the reserve price oracle. Optional - without it every
/// reserve is valued at par, which is the behaviour that shipped.
function setReserveOracle(address o) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
reserveOracle = IReserveOracle(o);
emit ReserveOracleSet(o);
}
/// True value of reserves at oracle prices, against what the
/// treasury has recorded. A shortfall means an approved asset has
/// lost its peg and the floor is overstated.
function reserveHealth()
external view
returns (uint256 recorded, uint256 actual, uint256 shortfallBps)
{
recorded = totalReserves;
actual = _actualReserveValue();
if (recorded == 0 || actual >= recorded) return (recorded, actual, 0);
shortfallBps = ((recorded - actual) * 10000) / recorded;
}
function _actualReserveValue() internal view returns (uint256 v) {
if (address(reserveOracle) == address(0)) return totalReserves;
for (uint256 i = 0; i < reserveTokens.length; i++) {
address t = reserveTokens[i];
if (!isReserveToken[t]) continue;
uint256 bal = reserveBalance[t];
if (bal == 0) continue;
if (!reserveOracle.healthy(t)) { v += bal; continue; }
v += (bal * reserveOracle.priceUSD(t)) / 1e18;
}
}
/// Blocks new issuance while reserves are materially impaired.
/// Minting against phantom backing is how a depeg becomes a drain.
modifier reservesSound() {
if (address(reserveOracle) != address(0)) {
uint256 actual = _actualReserveValue();
if (totalReserves > actual) {
require(
((totalReserves - actual) * 10000) / totalReserves <= MAX_SHORTFALL_BPS,
"Reserves impaired"
);
}
}
_;
}
/// Delist an asset that has provably lost its peg.
///
/// Requires the oracle to show it below DEPEG_THRESHOLD. Without
/// that proof this cannot be called at all - otherwise it would
/// be a drain vector, since a delisted token becomes rescuable.
///
/// Removing impaired backing legitimately lowers the floor, so
/// this is the one path deliberately exempt from the ratchet. The
/// high-water mark is reset to the post-removal floor: the floor
/// was never real at the old level.
/// Step one. Records that an approved reserve is trading below the
/// threshold. Changes nothing else, and anyone may call it - a
/// depeg is a public fact and there is no reason to make the
/// protocol wait for an admin to notice.
function flagDepeg(address token) external {
require(isReserveToken[token], "Not a reserve token");
require(address(reserveOracle) != address(0), "No oracle - cannot prove depeg");
require(reserveOracle.healthy(token), "Oracle unhealthy for token");
uint256 p = reserveOracle.priceUSD(token);
require(p < DEPEG_THRESHOLD, "Token is not depegged");
require(depegFlaggedAt[token] == 0, "Already flagged");
depegFlaggedAt[token] = block.timestamp;
emit DepegFlagged(token, p, block.timestamp + DELIST_DELAY);
}
/// Clears the flag once the price has recovered, so a wobble
/// cannot leave a standing licence to delist. Permissionless.
function clearDepeg(address token) external {
require(depegFlaggedAt[token] != 0, "Not flagged");
require(address(reserveOracle) != address(0), "No oracle");
require(reserveOracle.healthy(token), "Oracle unhealthy for token");
require(reserveOracle.priceUSD(token) >= DEPEG_THRESHOLD, "Still depegged");
depegFlaggedAt[token] = 0;
emit DepegCleared(token);
}
function removeReserveToken(address token) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(isReserveToken[token], "Not a reserve token");
require(address(reserveOracle) != address(0), "No oracle - cannot prove depeg");
require(depegFlaggedAt[token] != 0, "Flag the depeg first");
require(block.timestamp >= depegFlaggedAt[token] + DELIST_DELAY,
"Delist delay has not passed");
require(reserveOracle.healthy(token), "Oracle unhealthy for token");
require(reserveOracle.priceUSD(token) < DEPEG_THRESHOLD,
"Token recovered - clearDepeg and start again");
uint256 removed = reserveBalance[token];
isReserveToken[token] = false;
reserveBalance[token] = 0;
depegFlaggedAt[token] = 0;
totalReserves = totalReserves > removed ? totalReserves - removed : 0;
_updateExcessReserves();
highWaterFloor = priceFloor(); // the old mark was never backed
emit ReserveTokenRemoved(token, removed, highWaterFloor);
}
/// Where a delisted asset goes. Set once, in advance, in public.
///
/// It used to be an argument to rescueDelisted, chosen at the
/// moment of the call. Naming it beforehand does not stop a
/// determined admin - nothing in a single-key protocol does - but
/// it does mean the destination is a matter of record before
/// there is anything to take, and it can be a multisig while the
/// admin key is not one yet.
function setRecoveryAddress(address r) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(recoveryAddress == address(0), "Already set");
require(r != address(0), "Zero address");
recoveryAddress = r;
emit RecoveryAddressSet(r);
}
/// Recover a delisted asset so it can be swapped for a sound one.
/// Only reachable after removeReserveToken, which itself requires
/// a flagged depeg that has lasted a day.
///
/// What is owed to nodes, stakers, founders and the agent keeper
/// is NOT reserves and is not the admin's to move. It stays.
function rescueDelisted(address token)
external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant
{
require(!isReserveToken[token], "Still an approved reserve");
require(token != address(TOKEN), "Cannot rescue SLM");
require(recoveryAddress != address(0), "No recovery address set");
uint256 bal = IERC20(token).balanceOf(address(this));
uint256 owed = agentAllocation[token] + nodeAllocation[token]
+ stakerAllocation[token] + founderAllocation[token];
require(bal > owed, "Nothing beyond what is already owed");
uint256 amount = bal - owed;
IERC20(token).safeTransfer(recoveryAddress, amount);
emit DelistedRescued(token, recoveryAddress, amount);
}
function addReserveToken(address token) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(!isReserveToken[token], "Already added");
require(token != address(0), "Zero address");
require(token != address(TOKEN), "$SLM cannot back itself");
require(IERC20Metadata(token).decimals() <= 18, "Over 18 decimals");
// Once there is an oracle, prove the thing is a dollar before
// counting it as one. Before there is an oracle this cannot be
// checked, which is the argument for wiring the oracle at
// deploy rather than later.
if (address(reserveOracle) != address(0)) {
require(reserveOracle.healthy(token), "Oracle cannot price this token");
uint256 p = reserveOracle.priceUSD(token);
require(p >= MIN_RESERVE_PRICE && p <= MAX_RESERVE_PRICE,
"Not a dollar asset - reserves are counted at par");
}
isReserveToken[token] = true;
reserveTokens.push(token);
emit ReserveTokenAdded(token);
}
// ── Internal ────────────────────────────────────────────
function _updateExcessReserves() internal {
uint256 needed = (TOKEN.totalSupply() * MIN_BACKING_RATIO * minFloor) / 1e36;
excessReserves = totalReserves > needed ? totalReserves - needed : 0;
}
// PATCHED: scales any reserve token to 18 decimals.
function _normalizeDecimals(address token, uint256 amount)
internal view returns (uint256)
{
uint8 dec = IERC20Metadata(token).decimals();
if (dec == 18) return amount;
return amount * (10 ** (18 - dec));
}
/// Inverse of _normalizeDecimals - converts an 18-decimal
/// internal figure back into the token's own units for transfer.
function _denormalizeDecimals(address token, uint256 amount)
internal view returns (uint256)
{
uint8 dec = IERC20Metadata(token).decimals();
if (dec == 18) return amount;
return amount / (10 ** (18 - dec));
}
event MinFloorSet(uint256 minFloor);
event DepegFlagged(address indexed token, uint256 priceUSD, uint256 delistableAt);
event DepegCleared(address indexed token);
event RecoveryAddressSet(address indexed to);
event BondDeposit(address indexed reserveToken, uint256 amount, uint256 minted, uint256 profit);
event BondPremium(address indexed reserveToken, uint256 backing, uint256 premium);
event ReservesSeeded(address indexed token, uint256 amount);
event Withdrawal(address indexed token, uint256 amount);
event ReserveTokenAdded(address indexed token);
event TokensBurned(uint256 amount, string reason);
event SwapFeeBurnUpdated(uint256 oldBPS, uint256 newBPS);
event FeesCollected(address indexed token, uint256 total, uint256 toReserves, uint256 toAgents, uint256 toNodes);
event AgentAllocationWithdrawn(address indexed token, address indexed to, uint256 amount);
event AgentAllocationSet(uint256 oldBPS, uint256 newBPS);
event NodeAllocationSet(uint256 oldBPS, uint256 newBPS);
event NodeDistributorSet(address indexed distributor);
event NodeAllocationClaimed(address indexed token, uint256 amount);
event StakerAllocationSet(uint256 oldBPS, uint256 newBPS);
event StakerDistributorSet(address indexed distributor);
event StakerAllocationClaimed(address indexed token, uint256 amount);
event FounderAllocationSet(uint256 oldBPS, uint256 newBPS);
event FounderRecipientSet(address indexed from, address indexed to);
event FounderAllocationClaimed(address indexed token, address indexed to, uint256 amount);
event ReserveOracleSet(address indexed oracle);
event AgentWithdrawerSet(address indexed withdrawer);
event Finalized(address indexed by, uint256 agentBPS, uint256 nodeBPS, uint256 stakerBPS, uint256 founderBPS, address founderRecipient);
event ReserveTokenRemoved(address indexed token, uint256 removedValue, uint256 newHighWater);
event DelistedRescued(address indexed token, address indexed to, uint256 amount);
event Redeemed(address indexed holder, address indexed token, uint256 slmBurned, uint256 payout, uint256 fee, uint256 newFloor);
event RedemptionFeeSet(uint256 oldBPS, uint256 newBPS);
event FloorRatcheted(uint256 newHighWaterFloor);
}
contracts/lib/FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
/// @title Contains 512-bit math functions
/// @notice VENDORED from @uniswap/v3-core/contracts/libraries/FullMath.sol
///
/// Changes from the original, and ONLY these:
/// - pragma raised from `>=0.4.0 <0.8.0` to ^0.8.19
/// - bodies wrapped in `unchecked`
///
/// The unchecked blocks are required, not cosmetic. This library
/// relies deliberately on 256-bit overflow wrapping; under 0.8's
/// default checked arithmetic it would revert on correct inputs.
///
/// Diff this against the original before audit. It should differ by
/// exactly the two items above.
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
uint256 prod0;
uint256 prod1;
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256
require(denominator > prod1);
// 512 by 256 division
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
uint256 twos = (0 - denominator) & denominator;
assembly {
denominator := div(denominator, twos)
prod0 := div(prod0, twos)
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
uint256 inv = (3 * denominator) ^ 2;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
result = prod0 * inv;
return result;
}
}
}
contracts/lib/TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
/// @title Math library for computing sqrt prices from ticks
/// @notice VENDORED from @uniswap/v3-core/contracts/libraries/TickMath.sol
///
/// Changes from the original, and ONLY these:
/// - pragma raised from `>=0.5.0 <0.8.0` to ^0.8.19
/// - getSqrtRatioAtTick body wrapped in `unchecked`
/// - getTickAtSqrtRatio omitted (unused here)
///
/// Do not "simplify" the magic constants. They are a precomputed
/// binary expansion of 1.0001^tick and every one is load-bearing.
library TickMath {
int24 internal constant MIN_TICK = -887272;
int24 internal constant MAX_TICK = -MIN_TICK;
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
uint160 internal constant MAX_SQRT_RATIO =
1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(int256(MAX_TICK)), "T");
uint256 ratio = absTick & 0x1 != 0
? 0xfffcb933bd6fad37aa2d162d1a594001
: 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// shift from Q128.128 to Q128.96, rounding up
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
}
contracts/proto/DepositLaunchCheck.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "../OlympusToken.sol";
import "../Treasury.sol";
import "../KeelHook.sol"; // the V4 types only
// ============================================================
// DepositLaunchCheck.sol (16 Oct 2026)
//
// The deposit window's "is every key gone?" reading, moved out of
// DepositLaunch so the window has room for the launchpad's lockers. The
// window CREATES this contract in its own constructor (its code is part of
// the window's own deploy), so nobody can hand the window a checker that
// says "Ready" when it is not. It reads the window's public settings and
// the chain, and says why arm() would refuse, or "Ready". Unchanged from
// DepositLaunch.armCheck, plus the launchpad's lockers (16 Oct): when the
// window has a locker share or a lockers-first head start, its PAD_FUND
// must be a lockers contract bound to this very window.
// ============================================================
interface IWindowCK {
function TOKEN() external view returns (OlympusToken);
function TREASURY() external view returns (Treasury);
function RESERVE() external view returns (address);
function HOOK() external view returns (address);
function LIQUIDITY() external view returns (address);
function LOCKS() external view returns (address);
function BONDS() external view returns (address);
function SINK() external view returns (address);
function KEEL_FUND() external view returns (address);
function DEPLOYER() external view returns (address);
function PAD_FUND() external view returns (address);
function PAD_BPS() external view returns (uint256);
function LOCKERS_BPS() external view returns (uint256);
function HEAD_SECONDS() external view returns (uint256);
function OPENING_FLOOR() external view returns (uint256);
function POOL_FEE() external view returns (uint24);
function TICK_SPACING() external view returns (int24);
function poolKey() external view returns (PoolKey memory);
}
interface IHookCK {
function owner() external view returns (address);
function liquidity() external view returns (address);
function poolSet() external view returns (bool);
function poolFee() external view returns (uint24);
function poolTickSpacing() external view returns (int24);
}
interface ILiquidityCK {
function owner() external view returns (address);
function key() external view returns (address, address, uint24, int24, address);
}
interface ILocksCK {
function owner() external view returns (address);
function creditFacility() external view returns (address);
function bondDepository() external view returns (address);
}
interface IBondsCK {
function TREASURY() external view returns (address);
function RESERVE() external view returns (address);
function LOCKS() external view returns (address);
function ORACLE() external view returns (address);
}
interface IOracleCK { function HOOK() external view returns (address); }
interface IEnumerableCK { function getRoleMemberCount(bytes32 role) external view returns (uint256); }
interface IPadCK { function LAUNCH() external view returns (address); function FACTORY() external view returns (address); }
interface IPadFactoryCK { function made(address) external view returns (bool); }
interface IPadDepCK { function padDepository() external view returns (address); }
interface IPadHookCK { function padFeeBPS() external view returns (uint256); function padFund() external view returns (address); }
contract DepositLaunchCheck {
/// The hook's pad fee, or 0 for a hook without one.
function _padFee(address hook) internal view returns (uint256) {
try IPadHookCK(hook).padFeeBPS() returns (uint256 b) { return b; } catch { return 0; }
}
/// The locks' second depositor (a launch's lockers' contract), or 0 for locks without the slot.
function _padDep(address locks) internal view returns (address) {
try IPadDepCK(locks).padDepository() returns (address a) { return a; } catch { return address(0); }
}
/// Why window `w`'s arm() would refuse right now, or "Ready".
function check(address w) external view returns (string memory) {
IWindowCK L = IWindowCK(w);
OlympusToken TOKEN = L.TOKEN();
Treasury TREASURY = L.TREASURY();
bytes32 ADMIN = 0x00;
if (TOKEN.totalSupply() != 0) return "Supply is not zero";
// the token's roles, counted: exactly the window and the Treasury mint, only the Treasury burns, nobody administers
IEnumerableCK e = IEnumerableCK(address(TOKEN));
bytes32 M = TOKEN.MINTER_ROLE();
if (e.getRoleMemberCount(ADMIN) != 0) return "The token has an admin";
if (e.getRoleMemberCount(M) != 2 || !TOKEN.hasRole(M, w) || !TOKEN.hasRole(M, address(TREASURY))) return "The token's minters are not exactly the window and the Treasury";
if (e.getRoleMemberCount(TOKEN.BURNER_ROLE()) != 1 || !TOKEN.hasRole(TOKEN.BURNER_ROLE(), address(TREASURY))) return "The token's burner is not only the Treasury";
// the Treasury: one reserve, every slot as built, the burn-from-reserves path shut
if (TREASURY.reserveTokens(0) != L.RESERVE()) return "The reserve is not USDC";
try TREASURY.reserveTokens(1) returns (address) { return "The Treasury has a second reserve"; } catch {}
if (address(TREASURY.staking()) != address(0) || address(TREASURY.reserveOracle()) != address(0))
return "A Treasury slot is wired to something unexpected";
// the node slice: Keel's share (13 Oct, the founder: Hollow funds Keel's vault), to KEEL_FUND only, or off
address keelFund = L.KEEL_FUND();
if (TREASURY.nodeDistributor() != keelFund || (keelFund == address(0) && TREASURY.nodeAllocationBPS() != 0))
return "The Treasury's Keel share goes somewhere unexpected";
address locks = L.LOCKS();
if (TREASURY.agentWithdrawer() != L.SINK() || TREASURY.stakerDistributor() != locks) return "The Treasury's slices go somewhere unexpected";
if (TREASURY.swapFeeBurnBPS() != 0) return "The Treasury can burn from reserves";
// the locks and the bonds: no owner, no other door
if (ILocksCK(locks).creditFacility() != address(0)) return "The locks have a credit facility";
IBondsCK B = IBondsCK(L.BONDS());
if (ILocksCK(locks).bondDepository() != address(B)) return "The locks name another bond depository";
// the vault's least floor (16 Oct 2026, a billions-scale launch): never above the opening floor
if (TREASURY.minFloor() > L.OPENING_FLOOR()) return "The vault's least floor is above the opening floor";
address pd = _padDep(locks);
if (pd != address(0) && pd != L.PAD_FUND()) return "The locks name another depositor";
address hook = L.HOOK();
if (B.TREASURY() != address(TREASURY) || B.RESERVE() != L.RESERVE() || B.LOCKS() != locks
|| IOracleCK(B.ORACLE()).HOOK() != hook) return "The bonds are not this protocol's";
if (!TREASURY.hasRole(TREASURY.RESERVE_MANAGER_ROLE(), w)) return "The window cannot seed the vault";
if (!TREASURY.finalized()) return "The Treasury is not finalized";
address dep = L.DEPLOYER();
if (TREASURY.hasRole(ADMIN, dep) || TREASURY.hasRole(TREASURY.RESERVE_MANAGER_ROLE(), dep)) return "The deploy key holds a Treasury role";
address liq = L.LIQUIDITY();
if (IHookCK(hook).owner() != w || ILiquidityCK(liq).owner() != w) return "The window does not own the pool pieces";
if (ILocksCK(locks).owner() != address(0)) return "The locks still have an owner";
if (!IHookCK(hook).poolSet() || IHookCK(hook).poolFee() != L.POOL_FEE() || IHookCK(hook).poolTickSpacing() != L.TICK_SPACING()) return "The hook names another pool";
if (IHookCK(hook).liquidity() != liq) return "The hook admits other liquidity";
(address c0, address c1, uint24 fee, int24 sp, address h) = ILiquidityCK(liq).key();
PoolKey memory k = L.poolKey();
if (c0 != Currency.unwrap(k.currency0) || c1 != Currency.unwrap(k.currency1) || fee != k.fee || sp != k.tickSpacing || h != k.hooks)
return "The pool's contract names another pool";
// the launchpad (16 Oct 2026; tightened by the 16 Oct audit): any pad fee, locker share or head start
// means the pad fund is a PadLockers made by a factory, bound to this very window, and the hook's
// sell fee pays that same contract. Which factory is Hollow's, the site checks by its address.
uint256 hookPad = _padFee(hook);
if (L.PAD_BPS() > 0 || L.LOCKERS_BPS() > 0 || L.HEAD_SECONDS() > 0 || hookPad > 0) {
address pf = L.PAD_FUND();
if (pf.code.length == 0) return "The pad fund is not a lockers contract";
try IPadCK(pf).LAUNCH() returns (address bound) {
if (bound != w) return "The lockers are bound to another window";
} catch { return "The pad fund is not a lockers contract"; }
try IPadCK(pf).FACTORY() returns (address f) {
if (f.code.length == 0) return "The lockers name no factory";
try IPadFactoryCK(f).made(pf) returns (bool m) { if (!m) return "The factory did not make these lockers"; }
catch { return "The lockers name no factory"; }
} catch { return "The pad fund is not a lockers contract"; }
if (hookPad > 0 && IPadHookCK(hook).padFund() != pf) return "The hook's pad fee pays elsewhere";
if (L.LOCKERS_BPS() > 0 && pd != pf) return "The locks do not take the lockers' share";
}
return "Ready";
}
}
Compiler settingsShow
{
"viaIR": true,
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.