Verified contractPartialMIT
QSimpleLaunch
Address0x34ac8c4e6ca3d5b70a5321b648d0db9451c060cc
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,386,563
- Creation transaction
- 0xb712d93491…7850e3c2a6
28 files
- src-l200/prototypes/simple-launch/src/QSimpleLaunch.solmain38 KB
- src-l200/prototypes/launch-revenue/FeeDelta.sol775 B
- src-l200/prototypes/launch-revenue/LaunchFeePolicy.sol639 B
- src-l200/prototypes/simple-launch/src/QSimpleBlocks.sol33.02 KB
- src-l200/prototypes/simple-launch/src/QSimpleToken2.sol2.42 KB
- src-l200/prototypes/simple-launch/src/SimpleLaunchImpls.sol863 B
- src-l200/vendor/uniswap-v4-core/src/interfaces/IExtsload.sol1.02 KB
- src-l200/vendor/uniswap-v4-core/src/interfaces/IExttload.sol699 B
- src-l200/vendor/uniswap-v4-core/src/interfaces/IHooks.sol8.3 KB
- src-l200/vendor/uniswap-v4-core/src/interfaces/IPoolManager.sol13.45 KB
- src-l200/vendor/uniswap-v4-core/src/interfaces/IProtocolFees.sol2.49 KB
- src-l200/vendor/uniswap-v4-core/src/interfaces/callback/IUnlockCallback.sol488 B
- src-l200/vendor/uniswap-v4-core/src/interfaces/external/IERC20Minimal.sol3.04 KB
- src-l200/vendor/uniswap-v4-core/src/interfaces/external/IERC6909Claims.sol3.16 KB
- src-l200/vendor/uniswap-v4-core/src/libraries/BitMath.sol2.61 KB
- src-l200/vendor/uniswap-v4-core/src/libraries/CustomRevert.sol5.17 KB
- src-l200/vendor/uniswap-v4-core/src/libraries/FixedPoint128.sol297 B
- src-l200/vendor/uniswap-v4-core/src/libraries/FullMath.sol5.46 KB
- src-l200/vendor/uniswap-v4-core/src/libraries/LiquidityMath.sol742 B
- src-l200/vendor/uniswap-v4-core/src/libraries/Position.sol4.81 KB
- src-l200/vendor/uniswap-v4-core/src/libraries/SafeCast.sol2.27 KB
- src-l200/vendor/uniswap-v4-core/src/libraries/StateLibrary.sol16.03 KB
- src-l200/vendor/uniswap-v4-core/src/libraries/TickMath.sol12.38 KB
- src-l200/vendor/uniswap-v4-core/src/types/BalanceDelta.sol2.34 KB
- src-l200/vendor/uniswap-v4-core/src/types/BeforeSwapDelta.sol1.47 KB
- src-l200/vendor/uniswap-v4-core/src/types/Currency.sol5.46 KB
- src-l200/vendor/uniswap-v4-core/src/types/PoolId.sol539 B
- src-l200/vendor/uniswap-v4-core/src/types/PoolKey.sol805 B
src-l200/prototypes/simple-launch/src/QSimpleLaunch.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {BalanceDelta, BalanceDeltaLibrary} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary, toBeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {LaunchFeePolicy} from "../../launch-revenue/LaunchFeePolicy.sol";
import {FeeDelta} from "../../launch-revenue/FeeDelta.sol";
import {QSimpleBlocks} from "./QSimpleBlocks.sol";
import {SimpleLaunchImpls} from "./SimpleLaunchImpls.sol";
import {QSimpleToken2} from "./QSimpleToken2.sol";
interface ISimpleToken {
function balanceOf(address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
}
interface IVaultMaker {
function make(address token, address quote) external returns (address);
}
interface IWrappedNative {
function deposit() external payable;
}
interface IPQCreator { function registerFromFactory(bytes32 id, address wallet, bytes32 pk) external; }
/// @title QSimpleLaunch
/// @notice One-transaction token launch on Uniswap v4. In one call it creates a fixed-supply token, opens a
/// Uniswap v4 pool for it against the chain's quote token and puts the whole supply into that pool as a single
/// token-only position from the start price to the top of the price range, so trading starts with no buy-side
/// money from anyone. The position has the shape of a bonding curve (constant liquidity: a constant-product curve
/// whose virtual quote reserve is the start market cap) and is the end state: it is locked in this contract for
/// good. There is no function that removes it, so nobody, not the creator and not QHooks, can ever take it out.
///
/// This contract is also the hook of every pool it creates. Each swap pays the protocol fee (a fifth of the pool's
/// LP fee, on the unspecified side) straight to the platform wallet, the creator's launch blocks (if the style has
/// any) run their rules and charges exactly as in a Studio launch, and the first swap that takes the price past
/// 80% of the supply sold marks the launch Bonded. LP fees accrue to the locked position and anyone can send them
/// to the creator's payout address with `collect`.
///
/// Deployed with no constructor arguments through the deterministic deployer, so it has the same address on every
/// chain it supports; the chain's PoolManager, quote token, launch fee and platform wallet come from the table in
/// `chain()`. On any other chain every launch reverts. No owner, no upgrade, no pause.
contract QSimpleLaunch is IHooks, IUnlockCallback {
using PoolIdLibrary for PoolKey;
using CurrencyLibrary for Currency;
using BalanceDeltaLibrary for BalanceDelta;
uint256 public constant SUPPLY = 1_000_000_000e18;
int24 public constant TICK_SPACING = 200;
/// Ticks from the start price to the Bonded target: price x 25 (1.0001^32190), the point where 80% of the supply
/// has been bought out of the pool.
int24 public constant BOND_TICKS = 32190;
uint160 public constant REQUIRED_FLAGS = 8396; // beforeInitialize | beforeSwap | afterSwap | beforeSwapReturnDelta | afterSwapReturnDelta
address internal constant SAFE = 0x2b1Cf7c4071A98A59709166DFA73C7acb7E83E71;
address internal constant FLYWHEEL = 0xb85E67cf7728572033A9d36aEe3218DadF85bAA2;
address internal constant DEAD = 0x000000000000000000000000000000000000dEaD;
uint256 internal constant BPS = 10_000;
uint32 public constant DEFAULT_SNIPE = 15;
/// Most of the supply a creator may keep out of the pool (30%).
uint16 public constant MAX_RESERVE_BPS = 3000;
/// The anti-snipe charge at launch: the most the launch blocks allow for one charge (MAX_CHARGE_BPS).
uint16 internal constant SNIPE_BPS = 5000;
/// Highest start-cap step: each step raises the start price (and so the start market cap) by one tick spacing
/// (200 ticks, x1.0202). 161 steps = 32200 ticks, about 25x the chain's standard start cap.
uint256 public constant MAX_CAP_STEPS = 161;
// Styles (launch-block presets).
uint8 public constant NONE = 0;
uint8 public constant FAIR = 1;
uint8 public constant DEGEN = 2;
uint8 public constant COMMUNITY = 3;
uint8 public constant HOURS = 4;
uint8 public constant BURN = 5;
uint8 public constant FLYWHEEL_STYLE = 6;
struct Chain {
IPoolManager manager;
address quote;
/// True when the quote is the wrapped native coin: a first buy is paid in the native coin with the call.
bool wrapsNative;
uint256 launchFee;
/// Platform wallet for the launch fee and the protocol share of swap fees.
address platform;
/// Start tick when the token sorts as currency0 (price = quote per token); the mirror when it is currency1.
int24 tick0;
/// Start market cap of the whole supply, in quote base units (auto amounts of the presets scale with it).
uint256 startCap;
}
struct LaunchParams {
string name;
string symbol;
/// JSON with image, description and links. Only emitted, never stored.
string meta;
uint8 style;
/// The creator's LP fee in pips (1e6 = 100%), within LaunchFeePolicy.
uint24 fee;
/// Mixed with the creator's address into the token's CREATE2 salt.
bytes32 salt;
/// Optional first buy in the same transaction, in quote base units (0 for none). On wrapped-native chains it
/// is paid with the call's value on top of the launch fee; elsewhere it is pulled from the caller (approve first).
uint256 buyQuote;
uint256 minTokensOut;
/// Low 16 bits: anti-snipe length for styles with anti-snipe (Fair, Degen, Flywheel): the charge starts at
/// 50% and falls to 0 over this many seconds. 0 = the default 15 s; otherwise 15, 60, 300 or 600.
/// High 16 bits: start-cap steps (0 = the chain's standard start cap; each step x1.0202, at most
/// MAX_CAP_STEPS, about 25x). The start price, the Bonded price (start x 25) and the presets' auto amounts
/// (max buy per block, buyback size, clock minimum) all follow the chosen start cap.
uint32 snipeSeconds;
/// Who the launch is for: the creator role, the LP-fee payout, the style's first payee and the reserve.
/// 0 = the caller. Lets a contract (for example a contributor round) send the launch for a person.
address creator;
/// Share of the supply sent to the creator instead of the pool, in bps (at most 3000 = 30%). The rest goes
/// into the locked single-sided position as before.
uint16 reserveBps;
/// Optional post-quantum second key (SLH-DSA-SHA2-128s public key), only when launching for yourself. When set, the
/// creator role is held by the shared QPQCreator: changing the payout or handing on the role needs the creator's
/// wallet AND this key. Only the role moves; payout, payees, reserve and the token's address stay the creator's.
bytes32 pqKey;
/// Lock fee routing forever: no creator role at all (setPayout/setCreator then always revert). LP fees always go
/// to the creator's wallet. Only when launching for yourself. Covers this launch's role only, not the fee router.
bool lockRoles;
}
struct Pool {
address token;
int24 startTick;
int24 targetTick;
uint24 fee;
bool tokenIs0;
bool bonded;
address blocks;
address creator;
address payout;
}
mapping(bytes32 => Pool) internal pools;
uint256 public launches;
event Launched(bytes32 indexed poolId, address indexed token, address indexed creator, address quote, string name,
string symbol, string meta, uint8 style, address blocks, int24 startTick, int24 targetTick, uint256 supply, uint24 fee);
event FirstBuy(bytes32 indexed poolId, address indexed buyer, uint256 quoteIn, uint256 tokensOut);
event Bonded(bytes32 indexed poolId, int24 tick);
event FeesCollected(bytes32 indexed poolId, address indexed to, uint256 quoteAmount, uint256 tokenAmount);
event CreatorChanged(bytes32 indexed poolId, address from, address to);
event PayoutChanged(bytes32 indexed poolId, address from, address to);
event ProtocolFeeAccrued(bytes32 indexed poolId, address currency, uint256 amount);
event Swept(address indexed currency, uint256 amount);
error UnsupportedChain();
error NotManager();
error NotLaunchPool();
error InactiveCallback();
error BadParams();
error NotCreator();
error NoPlatform();
uint256 private constant T_LOCK = 0x51a7;
uint256 private constant T_INIT = 0x51a8;
/// The launching token's name and symbol, read back by its constructor (tokenParams). Length at the base slot,
/// then the bytes in 32-byte words.
uint256 private constant T_NAME = 0x51b0;
uint256 private constant T_SYMBOL = 0x51b8;
modifier onlyManager() {
if (msg.sender != address(chain().manager)) revert NotManager();
_;
}
modifier guarded() {
require(_tload(T_LOCK) == 0, "QSimple: busy");
_tstore(T_LOCK, 1);
_;
_tstore(T_LOCK, 0);
}
constructor() {
if (uint160(address(this)) & 0x3fff != REQUIRED_FLAGS) revert BadParams();
// The Flywheel style's vault maker must already be on this chain (deploy it first).
if (SimpleLaunchImpls.VAULT_MAKER.code.length == 0) revert BadParams();
// The post-quantum creator contract too (it needs its pinned verifier, so: verifier, QPQCreator, then this).
if (SimpleLaunchImpls.PQ_CREATOR.code.length == 0) revert BadParams();
}
// ---------------------------------------------------------------- chain table
/// @notice This chain's PoolManager, quote token, launch fee, platform wallet and start price.
function chain() public view returns (Chain memory c) {
uint256 id = block.chainid;
if (id == 4663) {
c = Chain(IPoolManager(0x8366a39CC670B4001A1121B8F6A443A643e40951), 0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73, true,
2e14, FLYWHEEL, -202200, 1666666666666666752);
} else if (id == 8453) {
c = Chain(IPoolManager(0x498581fF718922c3f8e6A244956aF099B2652b2b), 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913, false,
2e14, 0x20ed280Fb9E5276f76a633a428C5823dee1C87Cb, -398400, 5_000e6);
} else if (id == 1) {
c = Chain(IPoolManager(0x000000000004444c5dc75cB358380D2e3dE08A90), 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, false,
2e14, 0x229D9cE5e3CB3b3B099E47F2AB3384E53B17C5aE, -398400, 5_000e6);
} else if (id == 42161) {
c = Chain(IPoolManager(0x360E68faCcca8cA495c1B759Fd9EEe466db9FB32), 0xaf88d065e77c8cC2239327C5EDb3A432268e5831, false,
2e14, 0x27c34C655043c0c321f2a3d7eac91b76629194b2, -398400, 5_000e6);
} else if (id == 56) {
c = Chain(IPoolManager(0x28e2Ea090877bF75740558f6BFB36A5ffeE9e9dF), 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c, true,
7e14, 0xB6C198aaf44359d6F2D16e83108236497af9C3bB, -186200, 8333333333333334016);
} else if (id == 5042) {
c = Chain(IPoolManager(0x8366a39CC670B4001A1121B8F6A443A643e40951), 0x3600000000000000000000000000000000000000, false,
5e17, SAFE, -398400, 5_000e6);
} else if (id == 99801) {
c = Chain(IPoolManager(0x8366a39CC670B4001A1121B8F6A443A643e40951), 0xCD57F65c2B0e5881CFC2E609F7CD53b746E1F234, true,
2e14, 0xaE92B55d50ECEDD59189000D30c76772aD4fcE66, -156200, 166666666666666655744);
} else {
revert UnsupportedChain();
}
}
// ---------------------------------------------------------------- launch
/// @notice Launches a token in one transaction. Send exactly the chain's launch fee (plus the first buy on
/// wrapped-native chains). Returns the token and the pool id.
function launch(LaunchParams calldata p) external payable guarded returns (address token, bytes32 id) {
Chain memory c = chain();
uint256 nl = bytes(p.name).length;
uint256 sl = bytes(p.symbol).length;
if (nl == 0 || nl > 64 || sl == 0 || sl > 16 || bytes(p.meta).length > 4096 || p.style > FLYWHEEL_STYLE ||
p.reserveBps > MAX_RESERVE_BPS) revert BadParams();
address creator = p.creator == address(0) ? msg.sender : p.creator;
uint32 snipe = _atCap(c, p.snipeSeconds);
if (snipe != 15 && snipe != 60 && snipe != 300 && snipe != 600) revert BadParams();
LaunchFeePolicy.rates(p.fee); // reverts outside 1..100000 pips
if (c.wrapsNative ? msg.value != c.launchFee + p.buyQuote : msg.value != c.launchFee) revert BadParams();
// The platform wallet gets the fee now if it exists on this chain; otherwise it waits here for sweepNative().
if (c.platform.code.length != 0) {
(bool paid,) = c.platform.call{value: c.launchFee}("");
require(paid, "QSimple: launch fee transfer");
}
// A full ERC-20 (not a proxy): its constructor reads name/symbol from tokenParams() and mints SUPPLY to this contract.
_tstoreStr(T_NAME, p.name);
_tstoreStr(T_SYMBOL, p.symbol);
bytes memory init = type(QSimpleToken2).creationCode;
bytes32 tsalt = keccak256(abi.encode(msg.sender, p.salt));
assembly ("memory-safe") { token := create2(0, add(init, 0x20), mload(init), tsalt) }
require(token != address(0), "QSimple: clone");
uint256 reserve = SUPPLY * p.reserveBps / BPS;
if (reserve != 0) require(ISimpleToken(token).transfer(creator, reserve));
bool tokenIs0 = token < c.quote;
PoolKey memory key = PoolKey(
Currency.wrap(tokenIs0 ? token : c.quote), Currency.wrap(tokenIs0 ? c.quote : token), p.fee, TICK_SPACING, IHooks(address(this)));
id = PoolId.unwrap(key.toId());
int24 start = tokenIs0 ? c.tick0 : -c.tick0;
Pool storage pool = pools[id];
pool.token = token;
pool.startTick = start;
pool.targetTick = tokenIs0 ? start + BOND_TICKS : start - BOND_TICKS;
pool.fee = p.fee;
pool.tokenIs0 = tokenIs0;
pool.creator = creator;
pool.payout = creator;
// Both options only for your own launch: a launch sent for someone else can't lock their fee routing or tie it
// to the sender's key.
if ((p.lockRoles || p.pqKey != bytes32(0)) && creator != msg.sender) revert BadParams();
if (p.lockRoles) {
if (p.pqKey != bytes32(0)) revert BadParams();
pool.creator = address(0);
} else if (p.pqKey != bytes32(0)) {
pool.creator = SimpleLaunchImpls.PQ_CREATOR;
IPQCreator(SimpleLaunchImpls.PQ_CREATOR).registerFromFactory(id, creator, p.pqKey);
}
// Indexers see who holds the role from the start (review round 2).
if (pool.creator != creator) emit CreatorChanged(id, creator, pool.creator);
_tstore(T_INIT, 1);
c.manager.initialize(key, TickMath.getSqrtPriceAtTick(start));
_tstore(T_INIT, 0);
// Seed the locked position and run the optional first buy. The first buy happens before the style's
// blocks exist, so like a Pons, Clanker or Zora dev buy it pays no block charges. Uniswap v4 does not call a
// hook for a swap the hook itself makes, so it also pays no protocol fee and cannot mark the launch Bonded;
// the next trade does. Every later trade, from the next one on, runs the blocks.
c.manager.unlock(abi.encode(uint8(0), key, msg.sender, p.buyQuote, p.minTokensOut));
if (p.style != NONE) pool.blocks = _blocks(c, p.style, snipe, token, key, id, creator);
// Rounding dust of the supply that did not fit the position goes to the dead address.
uint256 dust = ISimpleToken(token).balanceOf(address(this));
if (dust != 0) ISimpleToken(token).transfer(DEAD, dust);
unchecked { ++launches; }
emit Launched(id, token, creator, c.quote, p.name, p.symbol, p.meta, p.style, pool.blocks, start, pool.targetTick, SUPPLY, p.fee);
}
function _blocks(Chain memory c, uint8 style, uint32 snipe, address token, PoolKey memory key, bytes32 id, address creator)
internal returns (address b)
{
b = _clone(SimpleLaunchImpls.BLOCKS, id);
address[8] memory payees;
uint16[8] memory shares;
payees[0] = creator;
if (style == FLYWHEEL_STYLE) {
// Holders who stake the token earn 25% of the creator's charges.
shares[0] = 7500;
payees[1] = IVaultMaker(SimpleLaunchImpls.VAULT_MAKER).make(token, c.quote);
shares[1] = 2500;
} else {
shares[0] = 10000;
}
QSimpleBlocks(b).initialize(_preset(style, snipe, token, c), payees, shares, c.manager, key, creator);
}
/// @notice The launch-blocks configuration of a style on this chain, for a `snipeSeconds` value as in
/// LaunchParams (anti-snipe length in the low 16 bits, start-cap steps in the high 16 bits).
function preset(uint8 style, uint32 snipeSeconds, address token) external view returns (QSimpleBlocks.Config memory) {
Chain memory c = chain();
uint32 snipe = _atCap(c, snipeSeconds);
return _preset(style, snipe, token, c);
}
/// @notice This chain's start tick and start market cap for a number of start-cap steps.
function startAt(uint256 steps) external view returns (int24 tick0, uint256 startCap) {
if (steps > MAX_CAP_STEPS) revert BadParams();
Chain memory c = chain();
_atCap(c, uint32(steps << 16));
return (c.tick0, c.startCap);
}
/// Splits `snipeSeconds` and moves the chain's start price up by the chosen start-cap steps.
function _atCap(Chain memory c, uint32 packed) internal pure returns (uint32 snipe) {
uint256 steps = packed >> 16;
if (steps > MAX_CAP_STEPS) revert BadParams();
snipe = packed & 0xffff;
if (snipe == 0) snipe = DEFAULT_SNIPE;
if (steps != 0) {
int24 off = int24(int256(steps)) * TICK_SPACING;
c.tick0 += off;
uint256 s = TickMath.getSqrtPriceAtTick(off);
c.startCap = FullMath.mulDiv(FullMath.mulDiv(c.startCap, s, 1 << 96), s, 1 << 96);
}
}
function _preset(uint8 style, uint32 snipe, address token, Chain memory ch) internal pure returns (QSimpleBlocks.Config memory c) {
c.token = token;
c.quote = ch.quote;
uint256 cap = ch.startCap;
if (style == FAIR || style == FLYWHEEL_STYLE) {
// Anti-snipe 50% falling to 0 over `snipe` seconds (default 15 s; the launch blocks cap a charge at 50%);
// 1% wallet cap and 30 s between buys for ten minutes (or the anti-snipe length, if longer); sandwich charge.
c.mask = (1 << 1) | (1 << 2) | (1 << 4) | (1 << 7);
c.guardSeconds = snipe > 600 ? snipe : 600;
c.snipeBps = SNIPE_BPS;
c.snipeDecay = snipe;
c.maxBuyPerBlock = uint128(cap / 100);
c.walletCapBps = 100;
c.cooldownSeconds = 30;
c.sandwichMaxBps = 800;
if (style == FLYWHEEL_STYLE) {
// 2% tax: 37.5% of it buys back and burns every 15 minutes, 12.5% to referrers, the rest to the payees.
c.mask |= (1 << 11) | (1 << 16) | (1 << 17) | (1 << 18);
c.buyTaxBps = 200;
c.sellTaxBps = 200;
c.taxDecay = 1800;
c.buybackShareBps = 3750;
c.buybackCooldown = 900;
c.buybackSlipBps = 100;
c.buybackMax = uint128(cap / 100);
c.referralShareBps = 1250;
}
} else if (style == DEGEN) {
// Anti-snipe as in Fair; launch tax 15% falling to 3% over 30 minutes, 1% burn per buy, king pot,
// last-buyer clock, referrals.
c.mask = (1 << 1) | (1 << 11) | (1 << 13) | (1 << 14) | (1 << 15) | (1 << 17) | (1 << 18);
c.guardSeconds = snipe > 300 ? snipe : 300;
c.snipeBps = SNIPE_BPS;
c.snipeDecay = snipe;
c.maxBuyPerBlock = uint128(cap / 100);
c.buyTaxBps = 300;
c.sellTaxBps = 300;
c.launchTaxBps = 1500;
c.taxDecay = 1800;
c.burnBps = 100;
c.kingShareBps = 2000;
c.kingRound = 3600;
c.clockShareBps = 2000;
c.clockTimer = 600;
c.clockMinBuy = uint128(cap / 1000);
c.referralShareBps = 1000;
} else if (style == COMMUNITY) {
// Exit clock (10% sell fee right after buying, falling to 0 over 3 days), 2% tax, 40% of it buys back.
c.mask = (1 << 6) | (1 << 11) | (1 << 16) | (1 << 17) | (1 << 18);
c.exitTopBps = 1000;
c.exitHorizon = 3 days;
c.buyTaxBps = 200;
c.sellTaxBps = 200;
c.taxDecay = 1800;
c.buybackShareBps = 4000;
c.buybackCooldown = 600;
c.buybackSlipBps = 300;
c.buybackMax = uint128(cap / 100);
c.referralShareBps = 2000;
} else if (style == HOURS) {
// US market sessions and a storm fee for wild swings, plus the sandwich charge.
c.mask = (1 << 7) | (1 << 9) | (1 << 10);
c.sandwichMaxBps = 800;
c.stormCeilBps = 300;
c.stormMult = 50;
c.stormInterval = 300;
c.stormDecay = 3600;
c.extendedBps = 30;
c.overnightBps = 50;
c.closedBps = 100;
} else if (style == BURN) {
// Every buy burns 2%; a 2% tax all goes to buybacks that burn.
c.mask = (1 << 11) | (1 << 13) | (1 << 16);
c.burnBps = 200;
c.buyTaxBps = 200;
c.sellTaxBps = 200;
c.taxDecay = 1800;
c.buybackShareBps = 10000;
c.buybackCooldown = 600;
c.buybackSlipBps = 300;
c.buybackMax = uint128(cap / 100);
}
}
// ---------------------------------------------------------------- unlock
function unlockCallback(bytes calldata data) external returns (bytes memory) {
IPoolManager m = chain().manager;
require(msg.sender == address(m) && _tload(T_LOCK) == 1);
uint8 action = uint8(bytes1(data[31]));
if (action == 0) {
(, PoolKey memory key, address buyer, uint256 buyQuote, uint256 minOut) = abi.decode(data, (uint8, PoolKey, address, uint256, uint256));
_seed(m, key, buyer, buyQuote, minOut);
} else if (action == 1) {
(, PoolKey memory key) = abi.decode(data, (uint8, PoolKey));
_collect(m, key);
} else {
(, Currency cur, uint256 amount, address to) = abi.decode(data, (uint8, Currency, uint256, address));
m.burn(address(this), cur.toId(), amount);
m.take(cur, to, amount);
}
return "";
}
function _seed(IPoolManager m, PoolKey memory key, address buyer, uint256 buyQuote, uint256 minOut) internal {
bytes32 id = PoolId.unwrap(key.toId());
Pool storage pool = pools[id];
bool tokenIs0 = pool.tokenIs0;
(int24 lower, int24 upper) = _range(pool);
uint160 sa = TickMath.getSqrtPriceAtTick(lower);
uint160 sb = TickMath.getSqrtPriceAtTick(upper);
// Everything still held (the supply less any reserve), less a hair so rounding up in the pool can never
// ask for more than we hold.
uint256 held = ISimpleToken(pool.token).balanceOf(address(this));
uint256 amount = held - held / 1e12;
uint256 liquidity = tokenIs0
? FullMath.mulDiv(FullMath.mulDiv(amount, sa, 1 << 96), sb, sb - sa)
: FullMath.mulDiv(amount, 1 << 96, sb - sa);
(BalanceDelta d,) = m.modifyLiquidity(key, IPoolManager.ModifyLiquidityParams(lower, upper, int256(liquidity), 0), "");
Currency tc = Currency.wrap(pool.token);
int128 owed = tokenIs0 ? d.amount0() : d.amount1();
require((tokenIs0 ? d.amount1() : d.amount0()) == 0 && owed < 0);
m.sync(tc);
ISimpleToken(pool.token).transfer(address(m), uint256(uint128(-owed)));
m.settle();
if (buyQuote == 0) return;
bool zeroForOne = !tokenIs0; // pay the quote, receive the token
BalanceDelta s = m.swap(key, IPoolManager.SwapParams(zeroForOne, -int256(buyQuote),
zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1), "");
int128 q = zeroForOne ? s.amount0() : s.amount1();
int128 t = zeroForOne ? s.amount1() : s.amount0();
require(q < 0 && t > 0);
uint256 spent = uint256(uint128(-q));
uint256 got = uint256(uint128(t));
require(got >= minOut, "QSimple: first buy below minimum");
Chain memory c = chain();
Currency qc = Currency.wrap(c.quote);
m.sync(qc);
if (c.wrapsNative) {
IWrappedNative(c.quote).deposit{value: spent}();
ISimpleToken(c.quote).transfer(address(m), spent);
if (buyQuote > spent) {
(bool ok,) = buyer.call{value: buyQuote - spent}("");
require(ok);
}
} else {
require(ISimpleToken(c.quote).transferFrom(buyer, address(m), spent));
}
m.settle();
m.take(tc, buyer, got);
emit FirstBuy(id, buyer, spent, got);
}
// ---------------------------------------------------------------- creator fees
/// @notice Sends the LP fees the locked position has earned to the creator's payout address. Anyone can call it.
function collect(PoolKey calldata key) external guarded {
if (pools[PoolId.unwrap(key.toId())].token == address(0) || address(key.hooks) != address(this)) revert NotLaunchPool();
chain().manager.unlock(abi.encode(uint8(1), key));
}
function _collect(IPoolManager m, PoolKey memory key) internal {
bytes32 id = PoolId.unwrap(key.toId());
Pool storage pool = pools[id];
(int24 lower, int24 upper) = _range(pool);
(BalanceDelta d,) = m.modifyLiquidity(key, IPoolManager.ModifyLiquidityParams(lower, upper, 0, 0), "");
int128 a0 = d.amount0();
int128 a1 = d.amount1();
require(a0 >= 0 && a1 >= 0);
address to = pool.payout;
if (a0 > 0) m.take(key.currency0, to, uint256(uint128(a0)));
if (a1 > 0) m.take(key.currency1, to, uint256(uint128(a1)));
(uint256 tokenAmt, uint256 quoteAmt) = pool.tokenIs0 ? (uint256(uint128(a0)), uint256(uint128(a1))) : (uint256(uint128(a1)), uint256(uint128(a0)));
emit FeesCollected(id, to, quoteAmt, tokenAmt);
}
/// @notice Pays protocol fees held for the platform (on a chain where its wallet had no code yet) to the
/// platform wallet, once that wallet exists. Anyone can call it; the destination is fixed.
function sweep(Currency currency) external guarded {
Chain memory c = chain();
if (c.platform.code.length == 0) revert NoPlatform();
uint256 amount = c.manager.balanceOf(address(this), currency.toId());
if (amount == 0) return;
c.manager.unlock(abi.encode(uint8(2), currency, amount, c.platform));
emit Swept(Currency.unwrap(currency), amount);
}
/// @notice Pays launch fees held here (native coin) to the platform wallet once it exists. Anyone can call it.
function sweepNative() external guarded {
address platform = chain().platform;
if (platform.code.length == 0) revert NoPlatform();
uint256 amount = address(this).balance;
if (amount == 0) return;
(bool ok,) = platform.call{value: amount}("");
require(ok, "QSimple: sweep");
emit Swept(address(0), amount);
}
/// @notice The creator hands the creator role (who may change the payout address and the role) to another
/// address, for example a two-key post-quantum guard contract.
function setCreator(bytes32 id, address to) external {
Pool storage pool = pools[id];
if (msg.sender != pool.creator || pool.creator == address(0)) revert NotCreator();
if (to == address(0)) revert BadParams();
emit CreatorChanged(id, pool.creator, to);
pool.creator = to;
}
/// @notice The creator sets where the LP fees go.
function setPayout(bytes32 id, address to) external {
Pool storage pool = pools[id];
if (msg.sender != pool.creator || pool.creator == address(0)) revert NotCreator();
if (to == address(0)) revert BadParams();
emit PayoutChanged(id, pool.payout, to);
pool.payout = to;
}
// ---------------------------------------------------------------- hook
function beforeInitialize(address sender, PoolKey calldata, uint160) external view onlyManager returns (bytes4) {
// Only pools this contract is creating, inside launch().
if (sender != address(this) || _tload(T_INIT) != 1) revert NotLaunchPool();
return IHooks.beforeInitialize.selector;
}
function beforeSwap(address sender, PoolKey calldata key, IPoolManager.SwapParams calldata p, bytes calldata data)
external onlyManager returns (bytes4, BeforeSwapDelta, uint24)
{
Pool storage pool = pools[PoolId.unwrap(key.toId())];
if (pool.token == address(0)) revert NotLaunchPool();
address b = pool.blocks;
if (b == address(0)) return (IHooks.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
(uint256 charge, bool burn) = QSimpleBlocks(b).beforeSwap(sender, p, data);
if (charge == 0) return (IHooks.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
_route((p.amountSpecified < 0) == p.zeroForOne ? key.currency0 : key.currency1, charge, burn, b);
return (IHooks.beforeSwap.selector, toBeforeSwapDelta(int128(int256(charge)), 0), 0);
}
function afterSwap(address sender, PoolKey calldata key, IPoolManager.SwapParams calldata p, BalanceDelta d, bytes calldata data)
external onlyManager returns (bytes4, int128)
{
bytes32 id = PoolId.unwrap(key.toId());
Pool storage pool = pools[id];
if (pool.token == address(0)) revert NotLaunchPool();
int128 a = d.amount0();
int128 b = d.amount1();
if (a == 0 && b == 0) return (IHooks.afterSwap.selector, 0);
require(p.zeroForOne ? a < 0 && b >= 0 : b < 0 && a >= 0);
(uint24 protocolPpm,) = LaunchFeePolicy.rates(pool.fee);
(bool is0, uint256 amount) = FeeDelta.assess(p.zeroForOne, p.amountSpecified, a, b, protocolPpm);
Currency currency = is0 ? key.currency0 : key.currency1;
IPoolManager m = IPoolManager(msg.sender);
if (amount != 0) {
// Straight to the platform wallet where it exists; elsewhere it is held here as a PoolManager claim
// until sweep() can pay it (never sent to an address without code).
address platform = chain().platform;
if (platform.code.length != 0) m.take(currency, platform, amount);
else m.mint(address(this), currency.toId(), amount);
emit ProtocolFeeAccrued(id, Currency.unwrap(currency), amount);
}
address blk = pool.blocks;
if (blk != address(0)) {
(uint256 vault, uint256 burned) = QSimpleBlocks(blk).afterSwap(sender, p, d, data);
if (vault != 0) _route(currency, vault, false, blk);
if (burned != 0) _route(currency, burned, true, blk);
amount += vault + burned;
}
if (!pool.bonded) {
(, int24 tick,,) = StateLibrary.getSlot0(m, PoolId.wrap(id));
if (pool.tokenIs0 ? tick >= pool.targetTick : tick <= pool.targetTick) {
pool.bonded = true;
emit Bonded(id, tick);
}
}
return (IHooks.afterSwap.selector, int128(uint128(amount)));
}
function _route(Currency c, uint256 amount, bool burn, address blk) private {
IPoolManager m = IPoolManager(msg.sender);
if (burn) m.take(c, DEAD, amount);
else m.mint(blk, c.toId(), amount);
}
function afterInitialize(address, PoolKey calldata, uint160, int24) external pure returns (bytes4) { revert InactiveCallback(); }
function beforeAddLiquidity(address, PoolKey calldata, IPoolManager.ModifyLiquidityParams calldata, bytes calldata)
external pure returns (bytes4) { revert InactiveCallback(); }
function afterAddLiquidity(address, PoolKey calldata, IPoolManager.ModifyLiquidityParams calldata, BalanceDelta, BalanceDelta, bytes calldata)
external pure returns (bytes4, BalanceDelta) { revert InactiveCallback(); }
function beforeRemoveLiquidity(address, PoolKey calldata, IPoolManager.ModifyLiquidityParams calldata, bytes calldata)
external pure returns (bytes4) { revert InactiveCallback(); }
function afterRemoveLiquidity(address, PoolKey calldata, IPoolManager.ModifyLiquidityParams calldata, BalanceDelta, BalanceDelta, bytes calldata)
external pure returns (bytes4, BalanceDelta) { revert InactiveCallback(); }
function beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata) external pure returns (bytes4) { revert InactiveCallback(); }
function afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata) external pure returns (bytes4) { revert InactiveCallback(); }
// ---------------------------------------------------------------- views
function launchOf(bytes32 id) external view returns (Pool memory) { return pools[id]; }
/// @notice How much of the supply has been bought out of the pool, in bps (10000 = all), from the pool price.
/// With constant liquidity, sold = 1 - sqrt(start price / price) (in the token's direction).
function progress(bytes32 id) external view returns (uint256 soldBps, bool bonded) {
Pool storage pool = pools[id];
if (pool.token == address(0)) revert NotLaunchPool();
(uint160 now_,,,) = StateLibrary.getSlot0(chain().manager, PoolId.wrap(id));
uint256 s0 = TickMath.getSqrtPriceAtTick(pool.startTick);
uint256 hi = pool.tokenIs0 ? now_ : s0;
uint256 lo = pool.tokenIs0 ? s0 : now_;
soldBps = hi <= lo ? 0 : BPS - FullMath.mulDiv(lo, BPS, hi);
bonded = pool.bonded;
}
/// @notice The token address a creator gets for a salt (for vanity-address mining on the site).
function predictToken(address creator, bytes32 salt) external view returns (address) {
bytes32 h = keccak256(type(QSimpleToken2).creationCode);
return address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), keccak256(abi.encode(creator, salt)), h)))));
}
/// @notice The name and symbol of the token being launched (read by its constructor during launch()).
function tokenParams() external view returns (string memory name, string memory symbol) {
return (_tloadStr(T_NAME), _tloadStr(T_SYMBOL));
}
// ---------------------------------------------------------------- helpers
function _range(Pool storage pool) internal view returns (int24 lower, int24 upper) {
return pool.tokenIs0
? (pool.startTick, TickMath.maxUsableTick(TICK_SPACING))
: (TickMath.minUsableTick(TICK_SPACING), pool.startTick);
}
/// EIP-1167 minimal proxy through CREATE2 (OpenZeppelin Clones layout).
function _clone(address impl, bytes32 salt) internal returns (address a) {
assembly ("memory-safe") {
mstore(0x00, or(shr(0xe8, shl(0x60, impl)), 0x3D602d80600A3D3981F3363d3d373d3D3D363d73000000))
mstore(0x20, or(shl(0x78, impl), 0x5af43d82803e903d91602b57fd5bf3))
a := create2(0, 0x09, 0x37, salt)
}
require(a != address(0), "QSimple: clone");
}
function _tstoreStr(uint256 base, string calldata s) internal {
uint256 n = bytes(s).length;
_tstore(base, n);
for (uint256 i; i < n; i += 32) {
uint256 w;
assembly ("memory-safe") { w := calldataload(add(s.offset, i)) }
if (n - i < 32) w &= ~(type(uint256).max >> ((n - i) * 8));
_tstore(base + 1 + i / 32, w);
}
}
function _tloadStr(uint256 base) internal view returns (string memory s) {
uint256 n = _tload(base);
s = new string(n);
for (uint256 i; i < n; i += 32) {
uint256 w = _tload(base + 1 + i / 32);
assembly ("memory-safe") { mstore(add(add(s, 32), i), w) }
}
}
function _tstore(uint256 slot, uint256 v) internal { assembly ("memory-safe") { tstore(slot, v) } }
function _tload(uint256 slot) internal view returns (uint256 v) { assembly ("memory-safe") { v := tload(slot) } }
}
src-l200/prototypes/launch-revenue/FeeDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
library FeeDelta {
error InvalidSwap();
error InvalidRate();
function assess(
bool zeroForOne,
int256 amountSpecified,
int128 amount0,
int128 amount1,
uint24 ratePpm
) internal pure returns (bool currencyIs0, uint256 feeAmount) {
if (amountSpecified == 0) revert InvalidSwap();
if (ratePpm > 20000) revert InvalidRate();
bool specifiedCurrencyIs0 = (amountSpecified < 0) == zeroForOne;
currencyIs0 = !specifiedCurrencyIs0;
int256 raw = currencyIs0 ? int256(amount0) : int256(amount1);
uint256 magnitude = raw < 0 ? uint256(-raw) : uint256(raw);
feeAmount = magnitude * uint256(ratePpm) / 1000000;
}
}
src-l200/prototypes/launch-revenue/LaunchFeePolicy.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
// Cline L54-C02; lead pinned the compiler version exactly.
library LaunchFeePolicy {
error InvalidCreatorFee();
uint256 internal constant DENOMINATOR = 1000000;
uint256 internal constant MAX_CREATOR_FEE = 100000;
function rates(uint256 creatorFeePpm)
internal
pure
returns (uint24 protocolFeePpm, uint24 totalFeePpm)
{
if (creatorFeePpm == 0 || creatorFeePpm > MAX_CREATOR_FEE) revert InvalidCreatorFee();
protocolFeePpm = uint24(creatorFeePpm / 5);
totalFeePpm = uint24(creatorFeePpm + protocolFeePpm);
}
}
src-l200/prototypes/simple-launch/src/QSimpleBlocks.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {BalanceDelta, BalanceDeltaLibrary} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
interface IBlocksToken {
function totalSupply() external view returns (uint256);
function balanceOf(address) external view returns (uint256);
}
/// @notice Launch blocks for one QHooks Simple launch pool: QLaunchBlocks deployed as a clone. The launch
/// contract (QSimpleLaunch, which is also the pool's hook) initialises it once, in the launch transaction, with a
/// fixed style preset; nothing can be changed afterwards. Charges are taken by the hook and held here as
/// PoolManager claims until anyone releases them to their fixed recipients.
/// Generated from QLaunchBlocks.sol (sha256 ed4203fd5a04fc360a75c11a156241b4eb6ce47f667422b38f167da2a52f85db) by scripts/make-blocks.mjs: only deployment and binding differ.
contract QSimpleBlocks is IUnlockCallback {
using PoolIdLibrary for PoolKey;
using CurrencyLibrary for Currency;
using BalanceDeltaLibrary for BalanceDelta;
// Block switches.
uint32 internal constant OPEN_DELAY = 1 << 0;
uint32 internal constant ANTI_SNIPE = 1 << 1;
uint32 internal constant WALLET_CAP = 1 << 2;
uint32 internal constant MAX_TRADE = 1 << 3;
uint32 internal constant COOLDOWN = 1 << 4;
uint32 internal constant HOLDER_GATE = 1 << 5;
uint32 internal constant EXIT_CLOCK = 1 << 6;
uint32 internal constant SANDWICH = 1 << 7;
uint32 internal constant IMPACT_FEE = 1 << 8;
uint32 internal constant STORM_FEE = 1 << 9;
uint32 internal constant SESSION_FEE = 1 << 10;
uint32 internal constant TAX = 1 << 11;
uint32 internal constant SIZE_TIERS = 1 << 12;
uint32 internal constant AUTO_BURN = 1 << 13;
uint32 internal constant KING = 1 << 14;
uint32 internal constant CLOCK_POT = 1 << 15;
uint32 internal constant BUYBACK = 1 << 16;
uint32 internal constant REFERRALS = 1 << 17;
uint32 internal constant POINTS = 1 << 18;
uint32 internal constant ALL = (1 << 19) - 1;
uint256 internal constant BPS = 10_000;
uint256 internal constant Q96 = 1 << 96;
uint256 internal constant MAX_CHARGE_BPS = 5_000;
address internal constant DEAD = 0x000000000000000000000000000000000000dEaD;
struct Config {
address token;
uint32 mask;
uint32 openDelay;
uint32 guardSeconds;
address quote;
uint16 snipeBps;
uint16 snipeFloorBps;
uint32 snipeDecay;
uint16 walletCapBps;
uint16 maxTradeBps;
uint128 maxBuyPerBlock;
uint32 maxTradeSeconds;
uint32 cooldownSeconds;
uint16 exitTopBps;
uint16 exitFloorBps;
uint32 exitHorizon;
address gateToken;
uint32 gateSeconds;
uint16 sandwichMaxBps;
uint16 impactCeilBps;
uint16 impactSlope;
uint128 gateMin;
uint16 stormFloorBps;
uint16 stormCeilBps;
uint32 stormInterval;
uint32 stormDecay;
uint16 stormMult;
uint16 regularBps;
uint16 extendedBps;
uint16 overnightBps;
uint16 closedBps;
uint16 buyTaxBps;
uint16 sellTaxBps;
uint16 launchTaxBps;
uint32 taxDecay;
uint16 tier1Bps;
uint16 tier2Bps;
uint16 burnBps;
uint128 tier1;
uint128 tier2;
uint16 kingShareBps;
uint32 kingRound;
uint16 clockShareBps;
uint32 clockTimer;
uint16 buybackShareBps;
uint32 buybackCooldown;
uint16 buybackSlipBps;
uint16 referralShareBps;
uint128 clockMinBuy;
uint128 buybackMax;
}
event Bound(address indexed hook, bytes32 indexed poolId, bool successor);
event LaunchFeePaid(address indexed payer, uint256 amount);
event Released(address indexed currency, uint256 amount);
event Claimed(address indexed account, uint256 amount);
event KingCrowned(uint256 indexed round, address indexed king, uint256 prize);
event ClockWon(address indexed winner, uint256 prize);
event BuybackBurned(uint256 quoteSpent, uint256 tokensBurned);
event PairAdded(address indexed pair);
address public owner;
Config internal cfg;
address[8] internal payeeList;
uint16[8] internal shareList;
bytes32 public configHash;
// Binding.
address public hook;
IPoolManager public manager;
PoolKey internal key;
bool public quoteIs0;
uint64 public launchTime;
uint256 public supply;
// Running state.
bool private locked;
uint64 private refBlock;
uint160 private refSqrt;
uint64 private stormCheckpoint;
uint160 private stormSqrt;
uint64 private stormPeakTime;
uint16 private stormPeak;
uint64 public lastBlockBuys;
uint128 public blockBuys;
mapping(address => uint64) public lastBuy;
mapping(address => uint256) public bought;
mapping(address => uint256) public points;
/// Second-pool hooks the owner created for this launch; their buys count toward every per-wallet guard.
mapping(address => bool) public pairs;
uint256 public totalPoints;
// Buckets, held as PoolManager claims.
uint256 public creatorQuote;
uint256 public creatorToken;
uint256 public buybackPot;
uint64 public lastBuyback;
mapping(address => uint256) public owed;
uint256 public totalOwed;
mapping(uint256 => uint256) public kingPot;
mapping(uint256 => address) public kingOf;
mapping(uint256 => uint256) public kingBest;
uint256 public kingCurrent;
uint256 public clockPot;
address public clockLeader;
uint64 public clockDeadline;
// Per-swap scratch (transient).
uint256 private constant T_RATE = 0x51a0;
uint256 private constant T_FLAGS = 0x51a1;
uint256 private constant T_PRE = 0x51a2;
uint256 private constant T_SQRT = 0x51a3;
modifier onlyHook() { require(msg.sender == hook && hook != address(0)); _; }
modifier nonReentrant() { require(!locked); locked = true; _; locked = false; }
/// The implementation can never be used itself; clones start with empty storage.
constructor() { hook = address(1); }
/// @notice Called once by QSimpleLaunch, in the launch transaction, right after it creates the clone. The
/// launch fee is paid to QSimpleLaunch, not here.
function initialize(Config memory c, address[8] memory payees_, uint16[8] memory shares_, IPoolManager manager_,
PoolKey memory key_, address owner_) external
{
require(hook == address(0));
_check(c, payees_, shares_);
address c0 = Currency.unwrap(key_.currency0);
address c1 = Currency.unwrap(key_.currency1);
require((c0 == c.token && c1 == c.quote) || (c0 == c.quote && c1 == c.token));
require(address(key_.hooks) == msg.sender);
owner = owner_;
cfg = c;
payeeList = payees_;
shareList = shares_;
configHash = keccak256(abi.encode(c, payees_, shares_));
hook = msg.sender;
manager = manager_;
key = key_;
quoteIs0 = c0 == c.quote;
launchTime = uint64(block.timestamp);
supply = IBlocksToken(c.token).totalSupply();
require(supply > 0);
emit Bound(msg.sender, PoolId.unwrap(key_.toId()), false);
}
function _check(Config memory c, address[8] memory p, uint16[8] memory s) private view {
require(c.token != address(0) && c.quote != address(0) && c.token != c.quote);
require(c.token.code.length > 0 && c.quote.code.length > 0);
require(c.mask & ~ALL == 0);
require(c.openDelay <= 7 days && c.guardSeconds <= 7 days);
if (c.mask & ANTI_SNIPE != 0) {
require(c.guardSeconds > 0 && c.snipeBps <= 5000 && c.snipeFloorBps <= c.snipeBps && c.snipeDecay <= c.guardSeconds);
}
if (c.mask & WALLET_CAP != 0) require(c.guardSeconds > 0 && c.walletCapBps > 0 && c.walletCapBps <= BPS);
if (c.mask & MAX_TRADE != 0) require(c.maxTradeBps > 0 && c.maxTradeBps <= BPS && c.maxTradeSeconds <= 30 days);
if (c.mask & COOLDOWN != 0) require(c.guardSeconds > 0 && c.cooldownSeconds > 0 && c.cooldownSeconds <= 1 hours);
if (c.mask & HOLDER_GATE != 0) require(c.gateToken.code.length > 0 && c.gateMin > 0 && c.gateSeconds > 0 && c.gateSeconds <= 7 days);
if (c.mask & EXIT_CLOCK != 0) require(c.exitTopBps <= 2500 && c.exitFloorBps <= c.exitTopBps && c.exitHorizon > 0 && c.exitHorizon <= 30 days);
if (c.mask & SANDWICH != 0) require(c.sandwichMaxBps >= 100 && c.sandwichMaxBps <= 1500);
if (c.mask & IMPACT_FEE != 0) require(c.impactCeilBps > 0 && c.impactCeilBps <= 1000 && c.impactSlope > 0 && c.impactSlope <= 1000);
if (c.mask & STORM_FEE != 0) {
require(c.stormFloorBps <= c.stormCeilBps && c.stormCeilBps <= 1000 && c.stormMult > 0 && c.stormMult <= 1000);
require(c.stormInterval >= 60 && c.stormInterval <= 1 days && c.stormDecay >= c.stormInterval && c.stormDecay <= 7 days);
}
if (c.mask & SESSION_FEE != 0) require(c.regularBps <= 1000 && c.extendedBps <= 1000 && c.overnightBps <= 1000 && c.closedBps <= 1000);
if (c.mask & TAX != 0) {
require(c.buyTaxBps <= 1000 && c.sellTaxBps <= 1000 && c.launchTaxBps <= 3000 && c.taxDecay <= 7 days);
require(c.launchTaxBps == 0 || (c.launchTaxBps >= c.buyTaxBps && c.launchTaxBps >= c.sellTaxBps && c.taxDecay > 0));
}
if (c.mask & SIZE_TIERS != 0) require(c.tier1 > 0 && c.tier2 > c.tier1 && c.tier1Bps <= c.tier2Bps && c.tier2Bps <= 1000);
if (c.mask & AUTO_BURN != 0) require(c.burnBps > 0 && c.burnBps <= 1000);
uint256 shares;
if (c.mask & KING != 0) { require(c.kingShareBps > 0 && c.kingRound >= 5 minutes && c.kingRound <= 7 days); shares += c.kingShareBps; }
if (c.mask & CLOCK_POT != 0) { require(c.clockShareBps > 0 && c.clockTimer >= 1 minutes && c.clockTimer <= 1 days); shares += c.clockShareBps; }
if (c.mask & BUYBACK != 0) {
require(c.buybackShareBps > 0 && c.buybackCooldown >= 1 minutes && c.buybackCooldown <= 1 days && c.buybackMax > 0);
require(c.buybackSlipBps >= 10 && c.buybackSlipBps <= 1000);
shares += c.buybackShareBps;
}
if (c.mask & REFERRALS != 0) { require(c.referralShareBps > 0); shares += c.referralShareBps; }
require(shares <= BPS);
uint256 total;
bool ended;
for (uint256 i; i < 8; ++i) {
if (p[i] == address(0)) { require(s[i] == 0); ended = true; continue; }
require(!ended && s[i] > 0);
for (uint256 j; j < i; ++j) require(p[j] != p[i]);
total += s[i];
}
require(total == BPS);
}
// ---------------------------------------------------------------- swap path
/// @return charge amount of the specified currency to take, burn whether it is burned.
function beforeSwap(address sender, IPoolManager.SwapParams calldata p, bytes calldata)
external onlyHook returns (uint256 charge, bool burn)
{
if (sender == address(this)) { _tstore(T_FLAGS, 1 << 7); return (0, false); }
Config storage c = cfg;
uint32 m = c.mask;
uint256 t = block.timestamp - launchTime;
if (m & OPEN_DELAY != 0) require(t >= c.openDelay, "QBlocks: trading not open");
bool isBuy = p.zeroForOne == quoteIs0;
bool exactIn = p.amountSpecified < 0;
bool specQuote = exactIn == isBuy;
uint256 spec = exactIn ? uint256(-p.amountSpecified) : uint256(p.amountSpecified);
if (isBuy && m & HOLDER_GATE != 0 && t < c.gateSeconds) {
require(_balance(c.gateToken, tx.origin) >= c.gateMin, "QBlocks: holders only");
}
if (isBuy && m & COOLDOWN != 0 && t < c.guardSeconds) {
uint64 last = lastBuy[tx.origin];
require(last == 0 || block.timestamp >= uint256(last) + c.cooldownSeconds, "QBlocks: cooldown");
}
uint160 sqrtNow;
if (m & (SANDWICH | IMPACT_FEE | STORM_FEE | BUYBACK) != 0) {
(sqrtNow,,,) = StateLibrary.getSlot0(manager, key.toId());
if (block.number != refBlock) { refBlock = uint64(block.number); refSqrt = sqrtNow; }
if (m & STORM_FEE != 0) _storm(c, sqrtNow);
}
uint256 rate = _preRate(c, m, t, isBuy, tx.origin);
uint256 flags = (isBuy ? 1 : 0) | (specQuote ? 2 : 0);
if (specQuote) {
rate += _tier(c, m, spec);
if (rate > MAX_CHARGE_BPS) rate = MAX_CHARGE_BPS;
charge = spec * rate / BPS;
flags |= 4;
} else if (isBuy && m & AUTO_BURN != 0) {
charge = spec * c.burnBps / BPS;
burn = true;
flags |= 8;
}
_tstore(T_RATE, rate);
_tstore(T_FLAGS, flags);
_tstore(T_PRE, charge);
_tstore(T_SQRT, sqrtNow);
}
/// @return vault charge of the unspecified currency kept here, burned charge sent to the dead address.
function afterSwap(address sender, IPoolManager.SwapParams calldata p, BalanceDelta d, bytes calldata hookData)
external onlyHook returns (uint256 vault, uint256 burned)
{
uint256 flags = _tload(T_FLAGS);
if (flags & (1 << 7) != 0 || sender == address(this)) { _tstore(T_FLAGS, 0); return (0, 0); }
Config storage c = cfg;
uint32 m = c.mask;
bool isBuy = flags & 1 != 0;
bool specQuote = flags & 2 != 0;
uint256 quoteLeg = _abs(quoteIs0 ? d.amount0() : d.amount1());
uint256 tokenLeg = _abs(quoteIs0 ? d.amount1() : d.amount0());
uint256 unspec = specQuote ? tokenLeg : quoteLeg;
uint256 t = block.timestamp - launchTime;
uint256 quoteCharge;
if (flags & 4 != 0) {
quoteCharge = _tload(T_PRE);
} else if (!specQuote) {
uint256 rate = _tload(T_RATE) + _tier(c, m, quoteLeg);
if (rate > MAX_CHARGE_BPS) rate = MAX_CHARGE_BPS;
quoteCharge = quoteLeg * rate / BPS;
vault = quoteCharge;
}
if (isBuy && specQuote && flags & 8 == 0 && m & AUTO_BURN != 0) burned = tokenLeg * c.burnBps / BPS;
if (m & (SANDWICH | IMPACT_FEE) != 0) {
uint256 post = _postRate(c, m, uint160(_tload(T_SQRT)));
if (post != 0) {
uint256 extra = unspec * post / BPS;
vault += extra;
if (specQuote) creatorToken += extra; else quoteCharge += extra;
}
}
require(vault + burned <= unspec / 2);
if (isBuy) {
if (m & ANTI_SNIPE != 0 && t < c.guardSeconds && c.maxBuyPerBlock != 0) {
if (lastBlockBuys != block.number) { lastBlockBuys = uint64(block.number); blockBuys = 0; }
uint256 next = uint256(blockBuys) + quoteLeg;
require(next <= _blockCap(c, t), "QBlocks: block buy cap");
blockBuys = uint128(next);
}
if (m & WALLET_CAP != 0 && t < c.guardSeconds) {
uint256 b = bought[tx.origin] + tokenLeg;
require(b <= supply * c.walletCapBps / BPS, "QBlocks: wallet cap");
bought[tx.origin] = b;
}
if (m & (COOLDOWN | EXIT_CLOCK) != 0) lastBuy[tx.origin] = uint64(block.timestamp);
if (m & KING != 0) _crown(c, t, quoteLeg);
if (m & CLOCK_POT != 0 && quoteLeg >= c.clockMinBuy) {
_settleClock();
clockLeader = tx.origin;
clockDeadline = uint64(block.timestamp + c.clockTimer);
}
}
if (m & MAX_TRADE != 0 && (c.maxTradeSeconds == 0 || t < c.maxTradeSeconds)) {
require(tokenLeg <= supply * c.maxTradeBps / BPS, "QBlocks: trade too large");
}
if (m & POINTS != 0) { points[tx.origin] += quoteLeg; totalPoints += quoteLeg; }
if (quoteCharge != 0) _allocate(c, m, t, quoteCharge, hookData);
_tstore(T_FLAGS, 0);
}
function _preRate(Config storage c, uint32 m, uint256 t, bool isBuy, address who) internal view returns (uint256 r) {
if (m & ANTI_SNIPE != 0 && isBuy && t < c.guardSeconds) {
if (c.snipeDecay == 0) r += c.snipeBps;
else if (t >= c.snipeDecay) r += c.snipeFloorBps;
else r += c.snipeBps - (uint256(c.snipeBps - c.snipeFloorBps) * t) / c.snipeDecay;
}
if (m & EXIT_CLOCK != 0 && !isBuy) {
uint256 since = lastBuy[who] == 0 ? t : block.timestamp - lastBuy[who];
if (since < c.exitHorizon) r += c.exitTopBps - (uint256(c.exitTopBps - c.exitFloorBps) * since) / c.exitHorizon;
else r += c.exitFloorBps;
}
if (m & STORM_FEE != 0) r += _stormRate(c);
if (m & SESSION_FEE != 0) r += _sessionRate(c, block.timestamp);
if (m & TAX != 0) {
uint256 base = isBuy ? c.buyTaxBps : c.sellTaxBps;
if (c.launchTaxBps != 0 && t < c.taxDecay) base = c.launchTaxBps - ((c.launchTaxBps - base) * t) / c.taxDecay;
r += base;
}
}
function _tier(Config storage c, uint32 m, uint256 quoteAmount) internal view returns (uint256) {
if (m & SIZE_TIERS == 0) return 0;
if (quoteAmount >= c.tier2) return c.tier2Bps;
if (quoteAmount >= c.tier1) return c.tier1Bps;
return 0;
}
function _blockCap(Config storage c, uint256 t) internal view returns (uint256) {
// The cap widens as the snipe tax falls and lifts when the decay ends.
if (c.snipeDecay == 0) return c.maxBuyPerBlock;
if (t >= c.snipeDecay) return type(uint256).max;
return uint256(c.maxBuyPerBlock) * c.snipeDecay / (c.snipeDecay - t);
}
function _postRate(Config storage c, uint32 m, uint160 before) internal view returns (uint256 r) {
if (before == 0 || refSqrt == 0) return 0;
(uint160 afterSqrt,,,) = StateLibrary.getSlot0(manager, key.toId());
uint256 open = refSqrt;
uint256 dBefore = before > open ? before - open : open - before;
uint256 dAfter = afterSqrt > open ? afterSqrt - open : open - afterSqrt;
if (dAfter > dBefore && m & IMPACT_FEE != 0) {
uint256 moveBps = _priceMoveBps(afterSqrt, before);
r = moveBps * c.impactSlope / 100;
if (r > c.impactCeilBps) r = c.impactCeilBps;
} else if (dAfter < dBefore && m & SANDWICH != 0) {
// Price bps are about twice sqrt-price bps for moves this small.
r = FullMath.mulDiv(dBefore - dAfter, 2 * BPS, open);
if (r > c.sandwichMaxBps) r = c.sandwichMaxBps;
}
}
function _allocate(Config storage c, uint32 m, uint256 t, uint256 amount, bytes calldata hookData) internal {
uint256 rest = amount;
if (m & KING != 0) {
uint256 s = amount * c.kingShareBps / BPS;
_rollKing(c, t);
kingPot[kingCurrent] += s;
rest -= s;
}
if (m & CLOCK_POT != 0) {
uint256 s = amount * c.clockShareBps / BPS;
_settleClock();
clockPot += s;
rest -= s;
}
if (m & BUYBACK != 0) {
uint256 s = amount * c.buybackShareBps / BPS;
buybackPot += s;
rest -= s;
}
if (m & REFERRALS != 0 && hookData.length >= 32) {
address ref = abi.decode(hookData[:32], (address));
if (ref != address(0) && ref != tx.origin && ref != address(this)) {
uint256 s = amount * c.referralShareBps / BPS;
owed[ref] += s;
totalOwed += s;
rest -= s;
}
}
creatorQuote += rest;
}
function _rollKing(Config storage c, uint256 t) internal {
uint256 r = t / c.kingRound;
uint256 cur = kingCurrent;
if (r != cur) {
if (kingOf[cur] == address(0) && kingPot[cur] != 0) { kingPot[r] += kingPot[cur]; kingPot[cur] = 0; }
kingCurrent = r;
}
}
function _crown(Config storage c, uint256 t, uint256 quoteLeg) internal {
_rollKing(c, t);
uint256 r = kingCurrent;
if (quoteLeg > kingBest[r]) { kingBest[r] = quoteLeg; kingOf[r] = tx.origin; }
}
function _settleClock() internal {
address leader = clockLeader;
if (leader != address(0) && block.timestamp > clockDeadline) {
uint256 prize = clockPot;
clockPot = 0;
clockLeader = address(0);
clockDeadline = 0;
owed[leader] += prize;
totalOwed += prize;
emit ClockWon(leader, prize);
}
}
function _storm(Config storage c, uint160 sqrtNow) internal {
if (stormSqrt == 0) { stormSqrt = sqrtNow; stormCheckpoint = uint64(block.timestamp); return; }
if (block.timestamp < uint256(stormCheckpoint) + c.stormInterval) return;
uint256 target = _priceMoveBps(sqrtNow, stormSqrt) * c.stormMult / 100;
if (target > c.stormCeilBps) target = c.stormCeilBps;
if (target > _stormLevel(c)) { stormPeak = uint16(target); stormPeakTime = uint64(block.timestamp); }
stormSqrt = sqrtNow;
stormCheckpoint = uint64(block.timestamp);
}
function _stormLevel(Config storage c) internal view returns (uint256) {
uint256 peak = stormPeak;
uint256 age = block.timestamp - stormPeakTime;
if (peak == 0 || age >= c.stormDecay) return 0;
return peak - peak * age / c.stormDecay;
}
function _stormRate(Config storage c) internal view returns (uint256) {
uint256 level = _stormLevel(c);
return level > c.stormFloorBps ? level : c.stormFloorBps;
}
// ---------------------------------------------------------------- US market sessions
function _sessionRate(Config storage c, uint256 ts) internal view returns (uint256) {
uint8 s = session(ts);
if (s == 0) return c.regularBps;
if (s == 1) return c.extendedBps;
if (s == 2) return c.overnightBps;
return c.closedBps;
}
/// @notice 0 regular, 1 pre-market or after hours, 2 overnight, 3 weekend (US Eastern time).
function session(uint256 ts) public pure returns (uint8) {
uint256 local = ts - (_isDst(ts) ? 4 hours : 5 hours);
uint256 day = local / 1 days;
uint256 dow = (day + 4) % 7; // 0 = Sunday
uint256 minute = (local % 1 days) / 60;
if (dow == 6) return 3;
if (dow == 0) return minute >= 1200 ? 2 : 3;
if (dow == 5 && minute >= 1200) return 3;
if (minute < 240 || minute >= 1200) return 2;
if (minute >= 570 && minute < 960) return 0;
return 1;
}
function _isDst(uint256 ts) internal pure returns (bool) {
uint256 y = _year(ts / 1 days);
uint256 mar = _days(y, 3, 1);
uint256 start = (mar + (7 - (mar + 4) % 7) % 7 + 7) * 1 days + 7 hours;
uint256 nov = _days(y, 11, 1);
uint256 end = (nov + (7 - (nov + 4) % 7) % 7) * 1 days + 6 hours;
return ts >= start && ts < end;
}
function _days(uint256 y, uint256 m, uint256 d) internal pure returns (uint256) {
if (m <= 2) y -= 1;
uint256 era = y / 400;
uint256 yoe = y - era * 400;
uint256 doy = (153 * (m > 2 ? m - 3 : m + 9) + 2) / 5 + d - 1;
uint256 doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return era * 146097 + doe - 719468;
}
function _year(uint256 z) internal pure returns (uint256) {
z += 719468;
uint256 era = z / 146097;
uint256 doe = z - era * 146097;
uint256 yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
uint256 doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
uint256 mp = (5 * doy + 2) / 153;
return yoe + era * 400 + (mp >= 10 ? 1 : 0);
}
// ---------------------------------------------------------------- payouts
/// @notice Settles a finished king round so its king can claim.
function settleKing(uint256 round) external nonReentrant {
Config storage c = cfg;
require(cfg.mask & KING != 0 && launchTime != 0);
require(round < (block.timestamp - launchTime) / c.kingRound);
address king = kingOf[round];
uint256 prize = kingPot[round];
require(king != address(0) && prize != 0);
kingPot[round] = 0;
owed[king] += prize;
totalOwed += prize;
emit KingCrowned(round, king, prize);
}
function settleClock() external nonReentrant { _settleClock(); }
/// @notice Pays the caller everything it has won or earned through referrals.
function claim() external nonReentrant returns (uint256 amount) {
amount = owed[msg.sender];
require(amount != 0);
owed[msg.sender] = 0;
totalOwed -= amount;
manager.unlock(abi.encode(uint8(1), msg.sender, amount, uint256(0)));
emit Claimed(msg.sender, amount);
}
/// @notice Sends creator charges to the fixed payees. Anyone can call it.
function release() external nonReentrant {
uint256 q = creatorQuote;
uint256 k = creatorToken;
require(q != 0 || k != 0);
creatorQuote = 0;
creatorToken = 0;
manager.unlock(abi.encode(uint8(2), address(0), q, k));
}
/// @notice Spends part of the buyback pot on the token and burns what it buys.
function buyback() external nonReentrant {
Config storage c = cfg;
require(c.mask & BUYBACK != 0 && launchTime != 0);
require(block.timestamp >= uint256(lastBuyback) + c.buybackCooldown);
uint256 amount = buybackPot < c.buybackMax ? buybackPot : c.buybackMax;
require(amount != 0);
lastBuyback = uint64(block.timestamp);
manager.unlock(abi.encode(uint8(3), address(0), amount, uint256(0)));
}
function unlockCallback(bytes calldata data) external returns (bytes memory) {
IPoolManager pm = manager;
require(msg.sender == address(pm) && locked);
(uint8 action, address to, uint256 amount, uint256 amount2) = abi.decode(data, (uint8, address, uint256, uint256));
Currency qc = Currency.wrap(cfg.quote);
Currency tc = Currency.wrap(cfg.token);
if (action == 1) {
_pay(pm, qc, to, amount);
} else if (action == 2) {
if (amount != 0) { _split(pm, qc, amount); emit Released(cfg.quote, amount); }
if (amount2 != 0) { _split(pm, tc, amount2); emit Released(cfg.token, amount2); }
} else {
_buyback(pm, qc, tc, amount);
}
return "";
}
function _split(IPoolManager pm, Currency cur, uint256 amount) internal {
uint256 left = amount;
for (uint256 i; i < 8; ++i) {
address p = payeeList[i];
if (p == address(0)) break;
uint256 part = (i + 1 == 8 || payeeList[i + 1] == address(0)) ? left : amount * shareList[i] / BPS;
left -= part;
if (part != 0) _pay(pm, cur, p, part);
}
}
function _pay(IPoolManager pm, Currency cur, address to, uint256 amount) internal {
pm.burn(address(this), cur.toId(), amount);
pm.take(cur, to, amount);
}
function _buyback(IPoolManager pm, Currency qc, Currency tc, uint256 amount) internal {
uint160 ref = refSqrt;
(uint160 sqrtNow,,,) = StateLibrary.getSlot0(pm, key.toId());
if (ref == 0 || refBlock != block.number) ref = sqrtNow;
uint256 slip = cfg.buybackSlipBps;
bool zeroForOne = quoteIs0;
// Buying the token moves price toward currency0 being cheaper when quote is currency0.
uint160 limit = zeroForOne
? uint160(FullMath.mulDiv(ref, 2 * BPS - slip, 2 * BPS))
: uint160(FullMath.mulDiv(ref, 2 * BPS + slip, 2 * BPS));
BalanceDelta d = pm.swap(key, IPoolManager.SwapParams(zeroForOne, -int256(amount), limit), "");
uint256 spent = _abs(zeroForOne ? d.amount0() : d.amount1());
uint256 got = _abs(zeroForOne ? d.amount1() : d.amount0());
require(spent <= amount && spent != 0);
buybackPot -= spent;
pm.burn(address(this), qc.toId(), spent);
pm.take(tc, DEAD, got);
emit BuybackBurned(spent, got);
}
// ---------------------------------------------------------------- views
/// @notice Registers a second pool's hook while the launch's owner is creating it (the caller has no code
/// yet). From then on that hook reports its buys here, so cooldown, wallet cap, exit clock and the
/// anti-snipe block cap count every pool of the launch together.
function addPair() external {
require(launchTime != 0 && tx.origin == owner && msg.sender != tx.origin && msg.sender.code.length == 0, "QBlocks: pair");
pairs[msg.sender] = true;
emit PairAdded(msg.sender);
}
/// @notice A registered pair hook reports a buy of `tokenLeg` tokens by the current trader (tx.origin).
/// The anti-snipe cap prices it in the launch quote at this pool's current price.
function notePairBuy(uint256 tokenLeg) external {
require(pairs[msg.sender], "QBlocks: pair");
Config storage c = cfg;
uint32 m = c.mask;
uint256 t = block.timestamp - launchTime;
if (m & COOLDOWN != 0 && t < c.guardSeconds) {
uint64 last = lastBuy[tx.origin];
require(last == 0 || block.timestamp >= uint256(last) + c.cooldownSeconds, "QBlocks: cooldown");
}
if (m & ANTI_SNIPE != 0 && t < c.guardSeconds && c.maxBuyPerBlock != 0) {
(uint160 s,,,) = StateLibrary.getSlot0(manager, key.toId());
uint256 quoteEq = quoteIs0 ? FullMath.mulDiv(FullMath.mulDiv(tokenLeg, Q96, s), Q96, s) : FullMath.mulDiv(FullMath.mulDiv(tokenLeg, s, Q96), s, Q96);
if (lastBlockBuys != block.number) { lastBlockBuys = uint64(block.number); blockBuys = 0; }
uint256 next = uint256(blockBuys) + quoteEq;
require(next <= _blockCap(c, t), "QBlocks: block buy cap");
blockBuys = uint128(next);
}
if (m & WALLET_CAP != 0 && t < c.guardSeconds) {
uint256 b = bought[tx.origin] + tokenLeg;
require(b <= supply * c.walletCapBps / BPS, "QBlocks: wallet cap");
bought[tx.origin] = b;
}
if (m & (COOLDOWN | EXIT_CLOCK) != 0) lastBuy[tx.origin] = uint64(block.timestamp);
}
function config() external view returns (Config memory c, address[8] memory payees, uint16[8] memory shares) {
return (cfg, payeeList, shareList);
}
function poolKey() external view returns (PoolKey memory) { return key; }
/// @notice The block charge in bps a trade of this size would pay right now, before
/// price-impact and sandwich charges, which depend on the trade's own price move.
function previewRate(bool isBuy, address trader, uint256 quoteAmount) external view returns (uint256 r) {
if (launchTime == 0) return 0;
Config storage c = cfg;
r = _preRate(c, c.mask, block.timestamp - launchTime, isBuy, trader) + _tier(c, c.mask, quoteAmount);
if (r > MAX_CHARGE_BPS) r = MAX_CHARGE_BPS;
}
function stormRate() external view returns (uint256) { return cfg.mask & STORM_FEE == 0 ? 0 : _stormRate(cfg); }
// ---------------------------------------------------------------- helpers
function _balance(address token, address who) internal view returns (uint256) {
(bool ok, bytes memory out) = token.staticcall{gas: 50_000}(abi.encodeCall(IBlocksToken.balanceOf, (who)));
return ok && out.length >= 32 ? abi.decode(out, (uint256)) : 0;
}
function _priceMoveBps(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 r = FullMath.mulDiv(a, 1e9, b);
uint256 p = r * r;
uint256 diff = p > 1e18 ? p - 1e18 : 1e18 - p;
return diff / 1e14;
}
function _abs(int128 v) internal pure returns (uint256) { return v < 0 ? uint256(uint128(-v)) : uint256(uint128(v)); }
function _tstore(uint256 slot, uint256 v) internal { assembly ("memory-safe") { tstore(slot, v) } }
function _tload(uint256 slot) internal view returns (uint256 v) { assembly ("memory-safe") { v := tload(slot) } }
}
src-l200/prototypes/simple-launch/src/QSimpleToken2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
interface IQSimpleToken2Deployer {
function tokenParams() external view returns (string memory name, string memory symbol);
}
/// @title QSimpleToken2
/// @notice A plain fixed-supply ERC-20 (18 decimals). The whole supply is minted once, in the constructor, to the
/// contract that deploys it. There is no owner and no admin: no mint, no burn function, no pause, no blacklist, no
/// fees, no transfer rules, no initializer and no proxy. Name and symbol are read from the deployer during
/// construction, so the creation code is the same for every token (stable CREATE2 addresses).
contract QSimpleToken2 {
uint256 public constant totalSupply = 1_000_000_000e18;
uint8 public constant decimals = 18;
string public name;
string public symbol;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
constructor() {
(name, symbol) = IQSimpleToken2Deployer(msg.sender).tokenParams();
balanceOf[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
function approve(address spender, uint256 amount) external returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) external returns (bool) {
_move(msg.sender, to, amount);
return true;
}
function transferFrom(address from, address to, uint256 amount) external returns (bool) {
uint256 a = allowance[from][msg.sender];
if (a != type(uint256).max) {
require(a >= amount, "QToken: allowance");
unchecked { allowance[from][msg.sender] = a - amount; }
}
_move(from, to, amount);
return true;
}
function _move(address from, address to, uint256 amount) private {
uint256 b = balanceOf[from];
require(b >= amount, "QToken: balance");
unchecked {
balanceOf[from] = b - amount;
balanceOf[to] += amount; // cannot overflow: the sum of all balances is totalSupply
}
emit Transfer(from, to, amount);
}
}
src-l200/prototypes/simple-launch/src/SimpleLaunchImpls.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// Implementation addresses: QSimpleToken, QSimpleBlocks and QVaultMaker deployed with no constructor arguments through the
/// deterministic deployer (0x4e59b44847b379578588920cA78FbF26c0B4956C) with salt 0, so the same on every chain.
/// Generated by scripts/pin-impls.mjs from the compiled init code; do not edit by hand.
library SimpleLaunchImpls {
address internal constant TOKEN = 0xDB3B3544d95Cf445E869bF3Bb9a2d1Dfb1d7007F;
address internal constant BLOCKS = 0x0Fe8d8Fb871F6d949ffe4C3f13D351e1b1ab2E94;
address internal constant VAULT_MAKER = 0x389ACc35f03488Bfaf25028A5FBe88eB49fE028e;
/// QPQCreator (post-quantum creator role): deterministic deployer, salt 0; same address on every chain.
address internal constant PQ_CREATOR = 0x9b1559aDc9B9c2Dce8A32957f3024F3393AE5bf3;
}
src-l200/vendor/uniswap-v4-core/src/interfaces/IExtsload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
src-l200/vendor/uniswap-v4-core/src/interfaces/IExttload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
src-l200/vendor/uniswap-v4-core/src/interfaces/IHooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IPoolManager} from "./IPoolManager.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
bytes calldata hookData
) external returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}
src-l200/vendor/uniswap-v4-core/src/interfaces/IPoolManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @param hookData The data to pass through to the add/removeLiquidity hooks
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
/// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
/// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
/// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency currency) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}
src-l200/vendor/uniswap-v4-core/src/interfaces/IProtocolFees.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param newProtocolFee The fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
}
src-l200/vendor/uniswap-v4-core/src/interfaces/callback/IUnlockCallback.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
/// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
/// @param data The data that was passed to the call to unlock
/// @return Any data that you want to be returned from the unlock call
function unlockCallback(bytes calldata data) external returns (bytes memory);
}
src-l200/vendor/uniswap-v4-core/src/interfaces/external/IERC20Minimal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
src-l200/vendor/uniswap-v4-core/src/interfaces/external/IERC6909Claims.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}
src-l200/vendor/uniswap-v4-core/src/libraries/BitMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}
src-l200/vendor/uniswap-v4-core/src/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
src-l200/vendor/uniswap-v4-core/src/libraries/FixedPoint128.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
src-l200/vendor/uniswap-v4-core/src/libraries/FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
assembly ("memory-safe") {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly ("memory-safe") {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (0 - denominator) & denominator;
// Divide denominator by power of two
assembly ("memory-safe") {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly ("memory-safe") {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly ("memory-safe") {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the preconditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) != 0) {
require(++result > 0);
}
}
}
}
src-l200/vendor/uniswap-v4-core/src/libraries/LiquidityMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Math library for liquidity
library LiquidityMath {
/// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
/// @param x The liquidity before change
/// @param y The delta by which liquidity should be changed
/// @return z The liquidity delta
function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
assembly ("memory-safe") {
z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
if shr(128, z) {
// revert SafeCastOverflow()
mstore(0, 0x93dafdf1)
revert(0x1c, 0x04)
}
}
}
}
src-l200/vendor/uniswap-v4-core/src/libraries/Position.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import {FullMath} from "./FullMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
using CustomRevert for bytes4;
/// @notice Cannot update a position with no liquidity
error CannotUpdateEmptyPosition();
// info stored for each user's position
struct State {
// the amount of liquidity owned by this position
uint128 liquidity;
// fee growth per unit of liquidity as of the last update to liquidity or fees owed
uint256 feeGrowthInside0LastX128;
uint256 feeGrowthInside1LastX128;
}
/// @notice Returns the State struct of a position, given an owner and position boundaries
/// @param self The mapping containing all user positions
/// @param owner The address of the position owner
/// @param tickLower The lower tick boundary of the position
/// @param tickUpper The upper tick boundary of the position
/// @param salt A unique value to differentiate between multiple positions in the same range
/// @return position The position info struct of the given owners' position
function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
internal
view
returns (State storage position)
{
bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);
position = self[positionKey];
}
/// @notice A helper function to calculate the position key
/// @param owner The address of the position owner
/// @param tickLower the lower tick boundary of the position
/// @param tickUpper the upper tick boundary of the position
/// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.
function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
internal
pure
returns (bytes32 positionKey)
{
// positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(add(fmp, 0x26), salt) // [0x26, 0x46)
mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)
mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)
mstore(fmp, owner) // [0x0c, 0x20)
positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes
// now clean the memory we used
mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt
mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt
mstore(fmp, 0) // fmp held owner
}
}
/// @notice Credits accumulated fees to a user's position
/// @param self The individual position to update
/// @param liquidityDelta The change in pool liquidity as a result of the position update
/// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries
/// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries
/// @return feesOwed0 The amount of currency0 owed to the position owner
/// @return feesOwed1 The amount of currency1 owed to the position owner
function update(
State storage self,
int128 liquidityDelta,
uint256 feeGrowthInside0X128,
uint256 feeGrowthInside1X128
) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
uint128 liquidity = self.liquidity;
if (liquidityDelta == 0) {
// disallow pokes for 0 liquidity positions
if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();
} else {
self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);
}
// calculate accumulated fees. overflow in the subtraction of fee growth is expected
unchecked {
feesOwed0 =
FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
feesOwed1 =
FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
}
// update the position
self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
}
}
src-l200/vendor/uniswap-v4-core/src/libraries/SafeCast.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}
src-l200/vendor/uniswap-v4-core/src/libraries/StateLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolId} from "../types/PoolId.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Position} from "./Position.sol";
/// @notice A helper library to provide state getters that use extsload
library StateLibrary {
/// @notice index of pools mapping in the PoolManager
bytes32 public constant POOLS_SLOT = bytes32(uint256(6));
/// @notice index of feeGrowthGlobal0X128 in Pool.State
uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;
// feeGrowthGlobal1X128 offset in Pool.State = 2
/// @notice index of liquidity in Pool.State
uint256 public constant LIQUIDITY_OFFSET = 3;
/// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;
uint256 public constant TICKS_OFFSET = 4;
/// @notice index of tickBitmap mapping in Pool.State
uint256 public constant TICK_BITMAP_OFFSET = 5;
/// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;
uint256 public constant POSITIONS_OFFSET = 6;
/**
* @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee
* @dev Corresponds to pools[poolId].slot0
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.
* @return tick The current tick of the pool.
* @return protocolFee The protocol fee of the pool.
* @return lpFee The swap fee of the pool.
*/
function getSlot0(IPoolManager manager, PoolId poolId)
internal
view
returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
bytes32 data = manager.extsload(stateSlot);
// 24 bits |24bits|24bits |24 bits|160 bits
// 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7
// ---------- | fee |protocolfee | tick | sqrtPriceX96
assembly ("memory-safe") {
// bottom 160 bits of data
sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
// next 24 bits of data
tick := signextend(2, shr(160, data))
// next 24 bits of data
protocolFee := and(shr(184, data), 0xFFFFFF)
// last 24 bits of data
lpFee := and(shr(208, data), 0xFFFFFF)
}
}
/**
* @notice Retrieves the tick information of a pool at a specific tick.
* @dev Corresponds to pools[poolId].ticks[tick]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve information for.
* @return liquidityGross The total position liquidity that references this tick
* @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
* @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
* @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
*/
function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128
)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
// read all 3 words of the TickInfo struct
bytes32[] memory data = manager.extsload(slot, 3);
assembly ("memory-safe") {
let firstWord := mload(add(data, 32))
liquidityNet := sar(128, firstWord)
liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
feeGrowthOutside0X128 := mload(add(data, 64))
feeGrowthOutside1X128 := mload(add(data, 96))
}
}
/**
* @notice Retrieves the liquidity information of a pool at a specific tick.
* @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve liquidity for.
* @return liquidityGross The total position liquidity that references this tick
* @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
*/
function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (uint128 liquidityGross, int128 liquidityNet)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
bytes32 value = manager.extsload(slot);
assembly ("memory-safe") {
liquidityNet := sar(128, value)
liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
/**
* @notice Retrieves the fee growth outside a tick range of a pool
* @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve fee growth for.
* @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
* @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
*/
function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
// offset by 1 word, since the first word is liquidityGross + liquidityNet
bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);
assembly ("memory-safe") {
feeGrowthOutside0X128 := mload(add(data, 32))
feeGrowthOutside1X128 := mload(add(data, 64))
}
}
/**
* @notice Retrieves the global fee growth of a pool.
* @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return feeGrowthGlobal0 The global fee growth for token0.
* @return feeGrowthGlobal1 The global fee growth for token1.
* @dev Note that feeGrowthGlobal can be artificially inflated
* For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal
* atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
*/
function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)
internal
view
returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State, `uint256 feeGrowthGlobal0X128`
bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);
// read the 2 words of feeGrowthGlobal
bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);
assembly ("memory-safe") {
feeGrowthGlobal0 := mload(add(data, 32))
feeGrowthGlobal1 := mload(add(data, 64))
}
}
/**
* @notice Retrieves total the liquidity of a pool.
* @dev Corresponds to pools[poolId].liquidity
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return liquidity The liquidity of the pool.
*/
function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `uint128 liquidity`
bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);
liquidity = uint128(uint256(manager.extsload(slot)));
}
/**
* @notice Retrieves the tick bitmap of a pool at a specific tick.
* @dev Corresponds to pools[poolId].tickBitmap[tick]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve the bitmap for.
* @return tickBitmap The bitmap of the tick.
*/
function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)
internal
view
returns (uint256 tickBitmap)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(int16 => uint256) tickBitmap;`
bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);
// slot id of the mapping key: `pools[poolId].tickBitmap[tick]
bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));
tickBitmap = uint256(manager.extsload(slot));
}
/**
* @notice Retrieves the position information of a pool without needing to calculate the `positionId`.
* @dev Corresponds to pools[poolId].positions[positionId]
* @param poolId The ID of the pool.
* @param owner The owner of the liquidity position.
* @param tickLower The lower tick of the liquidity range.
* @param tickUpper The upper tick of the liquidity range.
* @param salt The bytes32 randomness to further distinguish position state.
* @return liquidity The liquidity of the position.
* @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
* @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
*/
function getPositionInfo(
IPoolManager manager,
PoolId poolId,
address owner,
int24 tickLower,
int24 tickUpper,
bytes32 salt
) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {
// positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);
(liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);
}
/**
* @notice Retrieves the position information of a pool at a specific position ID.
* @dev Corresponds to pools[poolId].positions[positionId]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param positionId The ID of the position.
* @return liquidity The liquidity of the position.
* @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
* @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
*/
function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)
internal
view
returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)
{
bytes32 slot = _getPositionInfoSlot(poolId, positionId);
// read all 3 words of the Position.State struct
bytes32[] memory data = manager.extsload(slot, 3);
assembly ("memory-safe") {
liquidity := mload(add(data, 32))
feeGrowthInside0LastX128 := mload(add(data, 64))
feeGrowthInside1LastX128 := mload(add(data, 96))
}
}
/**
* @notice Retrieves the liquidity of a position.
* @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param positionId The ID of the position.
* @return liquidity The liquidity of the position.
*/
function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)
internal
view
returns (uint128 liquidity)
{
bytes32 slot = _getPositionInfoSlot(poolId, positionId);
liquidity = uint128(uint256(manager.extsload(slot)));
}
/**
* @notice Calculate the fee growth inside a tick range of a pool
* @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tickLower The lower tick of the range.
* @param tickUpper The upper tick of the range.
* @return feeGrowthInside0X128 The fee growth inside the tick range for token0.
* @return feeGrowthInside1X128 The fee growth inside the tick range for token1.
*/
function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)
internal
view
returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
{
(uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);
(uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =
getTickFeeGrowthOutside(manager, poolId, tickLower);
(uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =
getTickFeeGrowthOutside(manager, poolId, tickUpper);
(, int24 tickCurrent,,) = getSlot0(manager, poolId);
unchecked {
if (tickCurrent < tickLower) {
feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
} else if (tickCurrent >= tickUpper) {
feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;
feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;
} else {
feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
}
}
}
function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
}
function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(int24 => TickInfo) ticks`
bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);
// slot key of the tick key: `pools[poolId].ticks[tick]
return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));
}
function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(bytes32 => Position.State) positions;`
bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);
// slot of the mapping key: `pools[poolId].positions[positionId]
return keccak256(abi.encodePacked(positionId, positionMapping));
}
}
src-l200/vendor/uniswap-v4-core/src/libraries/TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}
src-l200/vendor/uniswap-v4-core/src/types/BalanceDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
src-l200/vendor/uniswap-v4-core/src/types/BeforeSwapDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}
src-l200/vendor/uniswap-v4-core/src/types/Currency.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}
src-l200/vendor/uniswap-v4-core/src/types/PoolId.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}
src-l200/vendor/uniswap-v4-core/src/types/PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"solmate/=src-l200/vendor/solmate/",
"@uniswap/v4-core/=src-l200/vendor/uniswap-v4-core/",
"forge-std/=lib/forge-std/src/",
"uniswap-v4-core/=src-l200/vendor/uniswap-v4-core/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.