opsis
754,930
soft launchtransactions enter through the HyperEVM inbox, only partners reach the sequencer directly. Public mainnet opens 9 Nov 2026, a reset before that is possible.
Contract✓ verified

StocksLauncher

0xac02140c5129d7ae0cf6834009f52b02ad0903fb on HyperEVM ↗
HYPE balance
0 HYPE
$0
tokens
0 HYPE
0 tokens
deployed by
creation tx 5d 7h ago
contract
StocksLauncher
compiler
v0.8.26+commit.8a97fa7a
optimizer
on, 200 runs · via IR
evm version
cancun
license
MIT
match
full: bytecode and metadata hash equal
verified
2026-10-30 23:17:16 UTC
constructor arguments
hook_ address0x8680…6acc
vault_ address0x839d…4c30
startTick_ int24173200
launchFee_ uint2560
platform_ address0x419e…e5cc

source (19 files)

src/StocksLauncher.solmain138 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {EleosToken} from "eleos/EleosToken.sol";
import {IEleosHookLike} from "./IEleosHookLike.sol";
import {StocksVault} from "./StocksVault.sol";

/// @title eleos stocks launcher
/// @notice Launches a coin of the Stocks mode in one call: a plain eleos coin (1 billion, all into its HYPE pool with
///         the eleos hook), its tax and split, anti-snipe, max wallet, the creator's dev buy, and its stock in the
///         vault. In the hook the vault stands as the coin's creator, so the creator side of the split goes there and
///         is split again: `stockBps` becomes the chosen stock, `creatorBps` goes to the person. Everything is fixed in
///         this call and readable on chain afterwards (`Launched`, the hook's `config`, the vault's `coin`).
contract StocksLauncher {
    struct Launch {
        string name;
        string symbol;
        string meta; // JSON: description, image, website, x, telegram (shown by the site, never used on chain)
        address stock; // the stock's Elysium address, listed in the vault
        uint16 buyBps;
        uint16 sellBps;
        uint16 stockBps; // the split after the platform's share, sums to 10000
        uint16 creatorBps;
        uint16 holdersBps;
        uint16 buybackBps;
        uint16 lpBps;
        bool antiSnipe;
        uint16 maxWalletBps; // 0 = no max wallet, else 50 to 10000 of the supply
        uint32 limitsSecs; // how long the max wallet holds, at most a day
        uint256 seed; // HYPE of msg.value for the coin's stock from the start
        bytes32 salt;
    }

    error BadParams(string why);
    error FeeShort();
    error PayoutFailed();

    event Launched(
        address indexed token,
        address indexed creator,
        address indexed stock,
        PoolId poolId,
        string name,
        string symbol,
        string meta,
        IEleosHookLike.Config cfg,
        uint16 stockBps,
        uint16 cutBps,
        uint256 maxWallet,
        uint64 limitsUntil,
        uint256 seed,
        uint256 devBuyHype,
        uint256 devBuyTokens
    );

    uint32 public constant SNIPE_SECS = 120;
    uint32 public constant MAX_LIMITS_SECS = 1 days;
    uint256 internal constant BPS = 10_000;

    IEleosHookLike public immutable hook;
    IPoolManager public immutable poolManager;
    StocksVault public immutable vault;
    /// @notice Where every pool starts: coins per HYPE as a tick (the starting market cap), as the standard launcher.
    int24 public immutable startTick;
    /// @notice HYPE every launch pays to the platform, fixed at deploy (may be 0).
    uint256 public immutable launchFee;
    address public immutable platform;

    address[] public tokens;

    constructor(IEleosHookLike hook_, StocksVault vault_, int24 startTick_, uint256 launchFee_, address platform_) {
        hook = hook_;
        poolManager = hook_.poolManager();
        vault = vault_;
        startTick = startTick_;
        launchFee = launchFee_;
        platform = platform_;
    }

    function count() external view returns (uint256) {
        return tokens.length;
    }

    function launch(Launch calldata p) external payable returns (address token) {
        _check(p);
        if (msg.value < launchFee + p.seed) revert FeeShort();

        uint256 maxWallet = uint256(p.maxWalletBps) * 1_000_000_000 ether / BPS;
        uint64 limitsUntil = p.maxWalletBps == 0 ? 0 : uint64(block.timestamp + p.limitsSecs);
        token = address(
            new EleosToken{salt: keccak256(abi.encode(msg.sender, p.salt))}(
                p.name, p.symbol, address(hook), address(poolManager), msg.sender, limitsUntil, maxWallet
            )
        );

        IEleosHookLike.Config memory cfg = IEleosHookLike.Config({
            creator: address(vault),
            buyBps: p.buyBps,
            sellBps: p.sellBps,
            creatorBps: p.stockBps + p.creatorBps,
            holdersBps: p.holdersBps,
            buybackBps: p.buybackBps,
            lpBps: p.lpBps,
            snipeSecs: p.antiSnipe ? SNIPE_SECS : 0
        });
        vault.register{value: p.seed}(token, msg.sender, p.stock, p.stockBps, p.creatorBps);
        uint256 devBuy = msg.value - launchFee - p.seed;
        (, uint256 devTokens) = hook.open{value: devBuy}(token, cfg, startTick);
        vault.finish(token);

        if (launchFee > 0) {
            (bool ok,) = platform.call{value: launchFee}("");
            if (!ok) revert PayoutFailed();
        }
        tokens.push(token);
        emit Launched(
            token, msg.sender, p.stock, hook.poolIdOf(token), p.name, p.symbol, p.meta, cfg, p.stockBps, p.creatorBps, maxWallet, limitsUntil, p.seed, devBuy, devTokens
        );
    }

    function _check(Launch calldata p) internal view {
        uint256 nameLen = bytes(p.name).length;
        uint256 symLen = bytes(p.symbol).length;
        if (nameLen == 0 || nameLen > 32) revert BadParams("name 1 to 32 bytes");
        if (symLen == 0 || symLen > 10) revert BadParams("ticker 1 to 10 bytes");
        if (bytes(p.meta).length > 2048) revert BadParams("meta over 2048 bytes");
        if (p.maxWalletBps != 0 && (p.maxWalletBps < 50 || p.maxWalletBps > 10_000)) revert BadParams("max wallet 0.5 to 100 %");
        if (p.limitsSecs > MAX_LIMITS_SECS) revert BadParams("limits at most a day");
        if (p.buyBps == 0 && p.sellBps == 0) revert BadParams("a stock needs a tax");
        if (p.buyBps > 1000 || p.sellBps > 1000) revert BadParams("tax at most 10 %");
        if (uint256(p.stockBps) + p.creatorBps + p.holdersBps + p.buybackBps + p.lpBps != BPS) revert BadParams("split must sum to 100 %");
        if (p.stockBps < vault.minStockBps()) revert BadParams("stock share under the minimum");
        if (!vault.stockInfo(p.stock).listed) revert BadParams("stock not listed");
    }
}
../../lib/v4-core/src/interfaces/IPoolManager.sol218 lines
// 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";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.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);

    /// @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);

    /// @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;
}
../../lib/v4-core/src/types/PoolId.sol18 lines
// 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/EleosToken.sol228 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

/// @title eleos coin
/// @notice A plain ERC20 (1 billion, 18 decimals, no transfer tax) with three extras, all fixed at launch:
///           - HYPE dividends: the pool's hook sends the holders' share of every tax here (`distribute`), and every
///             wallet can claim its part by its balance. Pools, the hook, this contract and dead addresses earn nothing.
///           - a max wallet for the first `limitsUntil` seconds (0 = off): no wallet may hold more than `maxWallet`.
///           - EIP-2612 permit, so a sell needs no separate approval.
///         There is no owner, no mint after launch, no blacklist and no fee on transfer.
///         Launch modes extend it (rules in the coin, games): they override `_move` and call it through `super`.
///         A buy is a transfer out of the pool manager, a sell a transfer into it.
contract EleosToken {
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
    event Distributed(address indexed from, uint256 amount, uint256 eligibleSupply);
    event Claimed(address indexed holder, uint256 amount);

    error MaxWallet();
    error Balance();
    error Allowance();
    error Expired();
    error BadSignature();
    error PayoutFailed();

    address internal constant DEAD = 0x000000000000000000000000000000000000dEaD;
    uint256 internal constant MAG = 2 ** 128;
    /// @dev below one whole coin of eligible supply, dividends wait (keeps the per share math far from overflow)
    uint256 internal constant MIN_ELIGIBLE = 1 ether;

    string public name;
    string public symbol;
    uint8 public constant decimals = 18;
    uint256 public constant totalSupply = 1_000_000_000 ether;

    address public immutable hook;
    address public immutable poolManager;
    address public immutable creator;
    /// @notice The hook's bundler at launch (launches for someone else and hands the dev buy to several wallets in the
    ///         same transaction). Excluded like the hook: no dividends, no max wallet. address(0) when the hook has none.
    address public immutable bundler;
    uint64 public immutable launchedAt;
    uint64 public immutable limitsUntil;
    uint256 public immutable maxWallet;

    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;
    mapping(address => uint256) public nonces;

    // ---- dividends (the magnified dividend per share pattern)
    uint256 public magPerShare;
    uint256 public excludedSupply;
    uint256 public carry; // HYPE received while the eligible supply was below MIN_ELIGIBLE
    uint256 public totalDistributed;
    mapping(address => int256) internal corrections;
    mapping(address => uint256) public claimed;

    bytes32 internal immutable DOMAIN_SEPARATOR_0;
    uint256 internal immutable CHAIN_0;
    bytes32 internal constant PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");

    constructor(
        string memory name_,
        string memory symbol_,
        address hook_,
        address poolManager_,
        address creator_,
        uint64 limitsUntil_,
        uint256 maxWallet_
    ) {
        name = name_;
        symbol = symbol_;
        hook = hook_;
        poolManager = poolManager_;
        creator = creator_;
        bundler = _bundlerOf(hook_);
        launchedAt = uint64(block.timestamp);
        limitsUntil = limitsUntil_;
        maxWallet = maxWallet_;
        CHAIN_0 = block.chainid;
        DOMAIN_SEPARATOR_0 = _domain();
        // the whole supply goes to the hook, which puts it into the pool in the same transaction
        balanceOf[hook_] = totalSupply;
        excludedSupply = totalSupply;
        emit Transfer(address(0), hook_, totalSupply);
    }

    // ---------------------------------------------------------------- ERC20

    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) {
            if (a < amount) revert Allowance();
            allowance[from][msg.sender] = a - amount;
        }
        _move(from, to, amount);
        return true;
    }

    function approve(address spender, uint256 amount) external returns (bool) {
        allowance[msg.sender][spender] = amount;
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
        if (block.timestamp > deadline) revert Expired();
        bytes32 digest = keccak256(
            abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)))
        );
        address signer = ecrecover(digest, v, r, s);
        if (signer == address(0) || signer != owner) revert BadSignature();
        allowance[owner][spender] = value;
        emit Approval(owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view returns (bytes32) {
        return block.chainid == CHAIN_0 ? DOMAIN_SEPARATOR_0 : _domain();
    }

    function _domain() internal view returns (bytes32) {
        return keccak256(
            abi.encode(
                keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                keccak256(bytes(name)),
                keccak256("1"),
                block.chainid,
                address(this)
            )
        );
    }

    /// @notice Addresses that hold coins without earning dividends and without a max wallet: the pool manager (all
    ///         pool liquidity), the hook, this contract and the two burn addresses.
    function isExcluded(address a) public view virtual returns (bool) {
        return a == poolManager || a == hook || a == address(this) || a == DEAD || a == address(0) || a == bundler;
    }

    /// @dev the hook's bundler, read once at launch; a hook without one (other launch modes) gives address(0)
    function _bundlerOf(address hook_) internal view returns (address b) {
        (bool ok, bytes memory r) = hook_.staticcall(abi.encodeWithSignature("bundler()"));
        if (ok && r.length == 32) b = abi.decode(r, (address));
    }

    function _move(address from, address to, uint256 amount) internal virtual {
        uint256 b = balanceOf[from];
        if (b < amount) revert Balance();
        unchecked {
            balanceOf[from] = b - amount;
        }
        balanceOf[to] += amount;

        bool exFrom = isExcluded(from);
        bool exTo = isExcluded(to);
        int256 c = int256(magPerShare * amount);
        if (exFrom) excludedSupply -= amount;
        else corrections[from] += c;
        if (exTo) excludedSupply += amount;
        else corrections[to] -= c;

        if (!exTo && block.timestamp < limitsUntil && maxWallet != 0 && balanceOf[to] > maxWallet) revert MaxWallet();
        emit Transfer(from, to, amount);
    }

    // ---------------------------------------------------------------- HYPE dividends

    /// @notice Supply that earns dividends: everything outside the pool, the hook and the burn addresses.
    function eligibleSupply() public view returns (uint256) {
        return totalSupply - excludedSupply;
    }

    /// @notice Shares `msg.value` (plus anything carried) among all eligible holders by balance. Anyone may add.
    function distribute() public payable {
        uint256 amount = msg.value + carry;
        if (amount == 0) return;
        uint256 eligible = eligibleSupply();
        if (eligible < MIN_ELIGIBLE) {
            carry = amount;
            return;
        }
        carry = 0;
        magPerShare += amount * MAG / eligible;
        totalDistributed += amount;
        emit Distributed(msg.sender, amount, eligible);
    }

    receive() external payable virtual {
        distribute();
    }

    /// @notice HYPE a holder can claim now.
    function claimable(address holder) public view returns (uint256) {
        if (isExcluded(holder)) return 0;
        uint256 earned = uint256(int256(magPerShare * balanceOf[holder]) + corrections[holder]) / MAG;
        uint256 done = claimed[holder];
        return earned > done ? earned - done : 0;
    }

    function claim() external returns (uint256) {
        return _pay(msg.sender);
    }

    /// @notice Pays a holder's dividends to that holder. Anyone may trigger it (the keeper does for big holders).
    function claimFor(address holder) external returns (uint256) {
        return _pay(holder);
    }

    function _pay(address holder) internal returns (uint256 amount) {
        amount = claimable(holder);
        if (amount == 0) return 0;
        claimed[holder] += amount;
        (bool ok,) = holder.call{value: amount}("");
        if (!ok) revert PayoutFailed();
        emit Claimed(holder, amount);
    }

    /// @notice Coins burned so far (held by the dead address or the zero address).
    function burned() external view returns (uint256) {
        return balanceOf[DEAD] + balanceOf[address(0)];
    }
}
src/IEleosHookLike.sol52 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolId} from "v4-core/types/PoolId.sol";

/// @notice The part of the eleos hook (contracts/src/EleosHook.sol) the Stocks mode uses. Same structs, same order.
interface IEleosHookLike {
    struct Config {
        address creator;
        uint16 buyBps;
        uint16 sellBps;
        uint16 creatorBps;
        uint16 holdersBps;
        uint16 buybackBps;
        uint16 lpBps;
        uint32 snipeSecs;
    }

    struct Book {
        uint64 launchedAt;
        int24 startTick;
        int24 emaTick;
        uint64 emaAt;
        uint128 pending;
        uint128 snipePending;
        uint128 lpHype;
        uint128 lpTokens;
        uint128 creatorOwed;
    }

    function poolManager() external view returns (IPoolManager);
    function platformBps() external view returns (uint16);
    function poolIdOf(address token) external view returns (PoolId);
    function config(address token) external view returns (Config memory);
    function book(address token) external view returns (Book memory);
    function open(address token, Config calldata cfg, int24 startTick) external payable returns (uint128 liquidity, uint256 devTokens);
    function process(address token) external returns (uint256 total);
    function payCreator(address token) external returns (uint256 amount);
    function lowerTax(address token, uint16 buyBps, uint16 sellBps) external;
    function giveShare(address token, uint16 toHolders, uint16 toBuyback, uint16 toLp) external;
}

/// @notice The eleos coin as the vault sees it (contracts/src/EleosToken.sol).
interface IEleosCoin {
    function totalSupply() external view returns (uint256);
    function balanceOf(address a) external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
}
src/StocksVault.sol555 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {IEleosHookLike, IEleosCoin} from "./IEleosHookLike.sol";

interface IStockToken {
    function balanceOf(address a) external view returns (uint256);
    function decimals() external view returns (uint8);
}

/// @title eleos stocks vault
/// @notice A real stock under every coin of the Stocks mode. Each coin is a plain eleos coin in its HYPE pool (tradable
///         through any router from the first second); in the eleos hook this vault stands as the coin's creator, so the
///         creator side of every tax comes here and is split by the numbers fixed at launch: one part becomes the coin's
///         stock, the rest goes to the person who launched it.
///
///         HYPE becomes stock through fills, without an oracle and without an admin price: anyone who delivers the stock
///         here (bought on HyperEVM and brought over by the canonical token bridge) gets the coins' waiting HYPE at the
///         ask of a slowly rising auction. Each round starts 10 % under the last fill and rises by 2 % of it per hour up
///         to 125 %, then by 0.25 % per hour. The first to deliver gets it, so competition keeps fills near the market.
///         The last price and the round's start move toward a fill by the fill's share of the stock's waiting HYPE: a
///         small fill barely moves them, a fill of everything sets them.
///
///         Anyone can hand coins in at any time: they go to 0xdead and the holder gets their share of the coin's stock
///         and of its HYPE not yet filled, share = coins / (total supply - coins at 0xdead and 0x0). Of every hand in
///         `exitFeeBps` is kept back: `exitPlatformBps` of it goes to the platform, the rest stays and raises the share
///         of everyone left. If the stock cannot be sent to the holder, the HYPE part is still paid and the stock part
///         waits for that address.
///
///         No owner, no pause, no upgrade. The setter named at deploy can list stocks (never remove one, never change a
///         price) and can freeze the list for good. The creator of a coin can only give: lower the tax, move part of
///         their own cut to the stock or to holders, buyback or liquidity.
contract StocksVault {
    struct Stock {
        bool listed;
        uint8 decimals;
        uint64 anchorAt; // where the current round starts
        uint128 anchor; // HYPE wei per whole unit (10 ** decimals) at the last fill, or the listing price
        uint128 budget; // HYPE of every coin on this stock, waiting for fills
    }

    struct Coin {
        address creator; // the person: gets the cut, may give
        address stock;
        uint16 stockBps; // of the split after the platform share: becomes the stock
        uint16 cutBps; // of the split after the platform share: to the creator
        uint128 hype; // HYPE waiting for the stock (part of the stock's budget)
        uint128 held; // stock units held for this coin
    }

    struct Totals {
        uint128 collected; // HYPE in from the tax
        uint128 toCreator;
        uint128 added; // HYPE in from launch seeds and gifts
        uint128 spent; // HYPE paid for fills
        uint128 bought; // stock units in
        uint128 handedIn; // coins handed in
        uint128 hypeOut; // HYPE paid on hand ins
        uint128 stockOut; // stock paid on hand ins
    }

    error Refused();
    error NotLauncher();
    error NotCreator();
    error NotListed();
    error Unknown();
    error Known();
    error BadInput();
    error AskMoved(uint256 ask);
    error TooSmall();
    error Delivery();
    error PayoutTooLow();
    error SendFailed();
    error NothingOwed();
    error Reentered();

    event Listed(address indexed stock, uint8 decimals, uint256 startPrice);
    event ListFrozen();
    event LauncherSet(address indexed launcher);
    event Registered(address indexed token, address indexed creator, address indexed stock, uint16 stockBps, uint16 cutBps, uint256 seed);
    event Collected(address indexed token, uint256 amount, uint256 toStock, uint256 toCreator);
    event Added(address indexed token, address indexed from, uint256 amount);
    event Filled(address indexed token, address indexed stock, address indexed filler, uint256 hype, uint256 units, uint256 ask);
    event Round(address indexed stock, address indexed filler, uint256 hype, uint256 units, uint256 ask, uint256 anchor, bytes32 note);
    event HandedIn(address indexed token, address indexed by, address to, uint256 coins, uint256 hypeOut, uint256 stockOut, uint256 hypeFee, uint256 stockFee);
    event Gave(address indexed token, uint16 stockBps, uint16 cutBps);
    event CreatorMoved(address indexed token, address indexed from, address indexed to);
    event CreatorPaid(address indexed token, address indexed to, uint256 amount);
    event CreatorOwed(address indexed token, address indexed to, uint256 amount);
    event StockOwed(address indexed stock, address indexed to, uint256 amount);
    event StockClaimed(address indexed stock, address indexed to, uint256 amount);
    event PlatformPaid(address indexed to, address indexed asset, uint256 amount);

    uint256 internal constant BPS = 10_000;
    /// @notice every round starts this far under the last fill
    uint256 public constant DIP_BPS = 1000;
    /// @notice and rises by this much of the last fill per hour
    uint256 public constant RISE_BPS_PER_HOUR = 200;
    /// @notice up to this (125 % of the last fill, 17.5 hours into the round)
    uint256 public constant FAST_TOP_BPS = 12_500;
    /// @notice then this much per hour (6 % a day)
    uint256 public constant SLOW_BPS_PER_HOUR = 25;
    /// @notice least HYPE one fill may take
    uint256 public constant MIN_FILL = 0.01 ether;
    uint16 public constant MAX_EXIT_FEE_BPS = 500;
    uint16 public constant MAX_EXIT_PLATFORM_BPS = 3000;
    /// @notice the gas a creator payout may use before it waits as owed (a creator wallet that burns gas cannot stop a collect)
    uint256 internal constant CREATOR_GAS = 50_000;
    address internal constant DEAD = 0x000000000000000000000000000000000000dEaD;

    IEleosHookLike public immutable hook;
    address public immutable setter;
    address public immutable platform;
    /// @notice least share of the split (after the platform's share) a coin gives to its stock, fixed at deploy
    uint16 public immutable minStockBps;
    uint16 public immutable exitFeeBps;
    uint16 public immutable exitPlatformBps;

    address public launcher;
    bool public listFrozen;

    mapping(address => Stock) internal stockOf;
    address[] public stockList;
    mapping(address => Coin) internal coinOf;
    mapping(address => Totals) internal totalsOf;
    address[] public coinList;

    mapping(address => uint256) public creatorOwed;
    mapping(address => mapping(address => uint256)) public stockOwed;
    mapping(address => uint256) public stockOwedTotal;
    uint256 public platformHype;
    mapping(address => uint256) public platformStock;

    /// @dev the coin whose creator payout (or launch) is under way: the only time the hook may send HYPE here
    address internal expecting;
    uint256 internal balanceAtRegister;
    uint256 internal entered;

    constructor(IEleosHookLike hook_, address setter_, address platform_, uint16 minStockBps_, uint16 exitFeeBps_, uint16 exitPlatformBps_) {
        if (address(hook_) == address(0) || setter_ == address(0) || platform_ == address(0)) revert BadInput();
        if (minStockBps_ == 0 || minStockBps_ > BPS || exitFeeBps_ > MAX_EXIT_FEE_BPS || exitPlatformBps_ > MAX_EXIT_PLATFORM_BPS) revert BadInput();
        hook = hook_;
        setter = setter_;
        platform = platform_;
        minStockBps = minStockBps_;
        exitFeeBps = exitFeeBps_;
        exitPlatformBps = exitPlatformBps_;
    }

    modifier nonReentrant() {
        if (entered != 0) revert Reentered();
        entered = 1;
        _;
        entered = 0;
    }

    modifier onlyLauncher() {
        if (msg.sender != launcher || launcher == address(0)) revert NotLauncher();
        _;
    }

    modifier onlyCreator(address token) {
        if (msg.sender != coinOf[token].creator || msg.sender == address(0)) revert NotCreator();
        _;
    }

    // ---------------------------------------------------------------- the setter

    /// @notice Names the launcher, once.
    function setLauncher(address l) external {
        if (msg.sender != setter || launcher != address(0) || l == address(0)) revert Refused();
        launcher = l;
        emit LauncherSet(l);
    }

    /// @notice Lists a stock coins may pick: its Elysium address (the bridge's copy, which may not exist yet), its
    ///         decimals and the HYPE wei per whole unit its first round starts from. Never removed, never repriced.
    function listStock(address stock, uint8 decimals_, uint128 startPrice) external {
        if (msg.sender != setter || listFrozen) revert Refused();
        if (stock == address(0) || stockOf[stock].listed || startPrice == 0 || decimals_ > 24) revert BadInput();
        if (stock.code.length > 0 && IStockToken(stock).decimals() != decimals_) revert BadInput();
        stockOf[stock] = Stock({listed: true, decimals: decimals_, anchorAt: uint64(block.timestamp), anchor: startPrice, budget: 0});
        stockList.push(stock);
        emit Listed(stock, decimals_, startPrice);
    }

    /// @notice No stock can be listed after this.
    function freezeList() external {
        if (msg.sender != setter || listFrozen) revert Refused();
        listFrozen = true;
        emit ListFrozen();
    }

    // ---------------------------------------------------------------- launch (the launcher, around the hook's open)

    /// @notice Books a new coin before its pool opens. `msg.value` is the creator's seed for the stock.
    function register(address token, address creator, address stock, uint16 stockBps, uint16 cutBps) external payable onlyLauncher nonReentrant {
        Stock storage s = stockOf[stock];
        if (!s.listed) revert NotListed();
        if (coinOf[token].stock != address(0)) revert Known();
        if (creator == address(0) || stockBps < minStockBps || uint256(stockBps) + cutBps > BPS) revert BadInput();
        coinOf[token] = Coin({creator: creator, stock: stock, stockBps: stockBps, cutBps: cutBps, hype: uint128(msg.value), held: 0});
        coinList.push(token);
        if (msg.value > 0) {
            s.budget += uint128(msg.value);
            totalsOf[token].added += uint128(msg.value);
        }
        expecting = token;
        balanceAtRegister = address(this).balance;
        emit Registered(token, creator, stock, stockBps, cutBps, msg.value);
    }

    /// @notice After the pool opened: the dev buy (the hook sends it to the coin's creator in the hook, which is this
    ///         vault) and any HYPE it did not spend go on to the person.
    function finish(address token) external onlyLauncher nonReentrant {
        if (expecting != token) revert Unknown();
        expecting = address(0);
        address to = coinOf[token].creator;
        uint256 coins = IEleosCoin(token).balanceOf(address(this));
        if (coins > 0 && !IEleosCoin(token).transfer(to, coins)) revert SendFailed();
        uint256 left = address(this).balance - balanceAtRegister;
        if (left > 0) {
            (bool ok,) = to.call{value: left}("");
            if (!ok) revert SendFailed();
        }
    }

    // ---------------------------------------------------------------- the tax (anyone)

    /// @notice Runs the coin's split in the hook if it can (enough tax, price near its average), takes the creator side
    ///         here and splits it: the stock part waits for fills, the cut goes to the creator.
    function collect(address token) external nonReentrant returns (uint256 amount) {
        Coin storage c = coinOf[token];
        if (c.stock == address(0)) revert Unknown();
        try hook.process(token) {} catch {}
        expecting = token;
        uint256 before = address(this).balance;
        hook.payCreator(token);
        expecting = address(0);
        amount = address(this).balance - before;
        if (amount == 0) return 0;
        uint256 toStock = amount * c.stockBps / (uint256(c.stockBps) + c.cutBps);
        uint256 toCreator = amount - toStock;
        c.hype += uint128(toStock);
        stockOf[c.stock].budget += uint128(toStock);
        Totals storage t = totalsOf[token];
        t.collected += uint128(amount);
        t.toCreator += uint128(toCreator);
        emit Collected(token, amount, toStock, toCreator);
        if (toCreator > 0) _payCreator(token, c.creator, toCreator);
    }

    /// @notice Adds HYPE to a coin's stock (anyone, e.g. the creator after launch).
    function add(address token) external payable nonReentrant {
        Coin storage c = coinOf[token];
        if (c.stock == address(0)) revert Unknown();
        if (msg.value == 0) revert BadInput();
        c.hype += uint128(msg.value);
        stockOf[c.stock].budget += uint128(msg.value);
        totalsOf[token].added += uint128(msg.value);
        emit Added(token, msg.sender, msg.value);
    }

    // ---------------------------------------------------------------- fills (anyone)

    /// @notice HYPE wei the vault pays now per whole unit of `stock` delivered.
    function askOf(address stock) public view returns (uint256) {
        Stock storage s = stockOf[stock];
        if (!s.listed) return 0;
        uint256 dt = block.timestamp - s.anchorAt;
        uint256 f = BPS - DIP_BPS + dt * RISE_BPS_PER_HOUR / 1 hours;
        if (f > FAST_TOP_BPS) {
            uint256 fast = (FAST_TOP_BPS - (BPS - DIP_BPS)) * 1 hours / RISE_BPS_PER_HOUR;
            f = FAST_TOP_BPS + (dt - fast) * SLOW_BPS_PER_HOUR / 1 hours;
        }
        return uint256(s.anchor) * f / BPS;
    }

    /// @notice Delivers `stock` (approve this vault first) for the HYPE of the given coins at the ask now: for each coin
    ///         `hype[i]` of its waiting HYPE, for ceil(hype * unit / ask) units. Reverts if the ask is under `minAsk`
    ///         (another fill just moved it). `note` is the filler's own reference (e.g. its HyperEVM transaction).
    function fill(address stock, address[] calldata coins, uint256[] calldata hype, uint256 minAsk, bytes32 note)
        external
        nonReentrant
        returns (uint256 units, uint256 paid)
    {
        Stock storage s = stockOf[stock];
        if (!s.listed || stock.code.length == 0) revert NotListed();
        if (coins.length == 0 || coins.length != hype.length) revert BadInput();
        uint256 ask = askOf(stock);
        if (ask == 0 || ask < minAsk) revert AskMoved(ask);
        uint256 unit = 10 ** uint256(s.decimals);
        uint256 budget = s.budget;
        for (uint256 i; i < coins.length; ++i) {
            Coin storage c = coinOf[coins[i]];
            uint256 h = hype[i];
            if (c.stock != stock) revert Unknown();
            if (h == 0 || h > c.hype) revert BadInput();
            uint256 part = (h * unit + ask - 1) / ask;
            c.hype -= uint128(h);
            c.held += uint128(part);
            Totals storage t = totalsOf[coins[i]];
            t.spent += uint128(h);
            t.bought += uint128(part);
            emit Filled(coins[i], stock, msg.sender, h, part, ask);
            paid += h;
            units += part;
        }
        if (paid < MIN_FILL) revert TooSmall();
        s.budget = uint128(budget - paid);

        uint256 before = IStockToken(stock).balanceOf(address(this));
        _call(stock, abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), units));
        if (IStockToken(stock).balanceOf(address(this)) - before < units) revert Delivery();

        // the round moves toward this fill by its share of everything that waited
        uint256 a = s.anchor;
        a = ask >= a ? a + (ask - a) * paid / budget : a - (a - ask) * paid / budget;
        if (a == 0) a = 1;
        s.anchor = uint128(a);
        s.anchorAt = uint64(uint256(s.anchorAt) + (block.timestamp - s.anchorAt) * paid / budget);
        emit Round(stock, msg.sender, paid, units, ask, a, note);

        (bool ok,) = msg.sender.call{value: paid}("");
        if (!ok) revert SendFailed();
    }

    // ---------------------------------------------------------------- handing coins in (anyone)

    /// @notice Coins that share the vault: total supply minus coins at 0xdead and 0x0.
    function outstanding(address token) public view returns (uint256) {
        IEleosCoin c = IEleosCoin(token);
        return c.totalSupply() - c.balanceOf(DEAD) - c.balanceOf(address(0));
    }

    /// @notice What handing in `coins` of `token` pays now, after the fee.
    function quote(address token, uint256 coins) public view returns (uint256 hypeOut, uint256 stockOut, uint256 hypeFee, uint256 stockFee) {
        Coin storage c = coinOf[token];
        if (c.stock == address(0)) return (0, 0, 0, 0);
        uint256 out = outstanding(token);
        if (out == 0 || coins > out) return (0, 0, 0, 0);
        uint256 h = uint256(c.hype) * coins / out;
        uint256 u = uint256(c.held) * coins / out;
        hypeFee = h * exitFeeBps / BPS;
        stockFee = u * exitFeeBps / BPS;
        hypeOut = h - hypeFee;
        stockOut = u - stockFee;
    }

    /// @notice Hands in `coins` (approve this vault first): they go to 0xdead, `to` gets the share of the coin's HYPE
    ///         and stock (`quote`).
    function handIn(address token, uint256 coins, uint256 minHype, uint256 minStock, address to)
        external
        nonReentrant
        returns (uint256 hypeOut, uint256 stockOut)
    {
        return _handIn(token, coins, minHype, minStock, to);
    }

    /// @notice `handIn` with an EIP-2612 permit for the coins, one transaction. A permit that was already used (seen
    ///         in the mempool and sent first) is fine as long as the allowance is there.
    function handInWithPermit(
        address token,
        uint256 coins,
        uint256 minHype,
        uint256 minStock,
        address to,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external nonReentrant returns (uint256 hypeOut, uint256 stockOut) {
        try IEleosCoin(token).permit(msg.sender, address(this), coins, deadline, v, r, s) {} catch {}
        return _handIn(token, coins, minHype, minStock, to);
    }

    function _handIn(address token, uint256 coins, uint256 minHype, uint256 minStock, address to) internal returns (uint256 hypeOut, uint256 stockOut) {
        Coin storage c = coinOf[token];
        if (c.stock == address(0)) revert Unknown();
        if (coins == 0 || to == address(0)) revert BadInput();
        uint256 hypeFee;
        uint256 stockFee;
        (hypeOut, stockOut, hypeFee, stockFee) = quote(token, coins);
        if (hypeOut < minHype || stockOut < minStock || hypeOut + stockOut == 0) revert PayoutTooLow();

        uint256 deadBefore = IEleosCoin(token).balanceOf(DEAD);
        if (!IEleosCoin(token).transferFrom(msg.sender, DEAD, coins)) revert Delivery();
        if (IEleosCoin(token).balanceOf(DEAD) - deadBefore != coins) revert Delivery();

        uint256 hypePlat = hypeFee * exitPlatformBps / BPS;
        uint256 stockPlat = stockFee * exitPlatformBps / BPS;
        c.hype -= uint128(hypeOut + hypePlat);
        c.held -= uint128(stockOut + stockPlat);
        stockOf[c.stock].budget -= uint128(hypeOut + hypePlat);
        platformHype += hypePlat;
        platformStock[c.stock] += stockPlat;
        Totals storage t = totalsOf[token];
        t.handedIn += uint128(coins);
        t.hypeOut += uint128(hypeOut);
        t.stockOut += uint128(stockOut);
        emit HandedIn(token, msg.sender, to, coins, hypeOut, stockOut, hypeFee, stockFee);

        if (stockOut > 0 && !_trySend(c.stock, to, stockOut)) {
            stockOwed[c.stock][to] += stockOut;
            stockOwedTotal[c.stock] += stockOut;
            emit StockOwed(c.stock, to, stockOut);
        }
        if (hypeOut > 0) {
            (bool ok,) = to.call{value: hypeOut}("");
            if (!ok) revert SendFailed();
        }
    }

    /// @notice Sends stock that waited for `to` (anyone may trigger it; it only ever goes to `to`).
    function claimStock(address stock, address to) external nonReentrant returns (uint256 amount) {
        amount = stockOwed[stock][to];
        if (amount == 0) revert NothingOwed();
        stockOwed[stock][to] = 0;
        stockOwedTotal[stock] -= amount;
        _call(stock, abi.encodeWithSignature("transfer(address,uint256)", to, amount));
        emit StockClaimed(stock, to, amount);
    }

    // ---------------------------------------------------------------- the creator can only give

    /// @notice Lowers the coin's buy and sell tax in the hook. Never higher.
    function lowerTax(address token, uint16 buyBps, uint16 sellBps) external onlyCreator(token) nonReentrant {
        hook.lowerTax(token, buyBps, sellBps);
    }

    /// @notice Moves part of the creator's cut to the stock. Never back.
    function giveToStock(address token, uint16 bps) external onlyCreator(token) nonReentrant {
        Coin storage c = coinOf[token];
        if (bps == 0 || bps > c.cutBps) revert BadInput();
        c.cutBps -= bps;
        c.stockBps += bps;
        emit Gave(token, c.stockBps, c.cutBps);
    }

    /// @notice Moves part of the creator's cut to holders, buyback or liquidity in the hook. Never back.
    function giveShare(address token, uint16 toHolders, uint16 toBuyback, uint16 toLp) external onlyCreator(token) nonReentrant {
        Coin storage c = coinOf[token];
        uint256 sum = uint256(toHolders) + toBuyback + toLp;
        if (sum == 0 || sum > c.cutBps) revert BadInput();
        c.cutBps -= uint16(sum);
        hook.giveShare(token, toHolders, toBuyback, toLp);
        emit Gave(token, c.stockBps, c.cutBps);
    }

    /// @notice Hands the coin's cut and the right to give to another wallet.
    function transferCreator(address token, address to) external onlyCreator(token) nonReentrant {
        if (to == address(0) || to == msg.sender) revert BadInput();
        coinOf[token].creator = to;
        emit CreatorMoved(token, msg.sender, to);
    }

    /// @notice Pays a creator payout that could not be sent in `collect` (anyone may trigger it, it goes to the creator).
    function payCreator(address token) external nonReentrant returns (uint256 amount) {
        amount = creatorOwed[token];
        if (amount == 0) revert NothingOwed();
        creatorOwed[token] = 0;
        address to = coinOf[token].creator;
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert SendFailed();
        emit CreatorPaid(token, to, amount);
    }

    // ---------------------------------------------------------------- the platform's part of hand in fees (anyone)

    function payPlatform() external nonReentrant returns (uint256 amount) {
        amount = platformHype;
        if (amount == 0) revert NothingOwed();
        platformHype = 0;
        (bool ok,) = platform.call{value: amount}("");
        if (!ok) revert SendFailed();
        emit PlatformPaid(platform, address(0), amount);
    }

    function payPlatformStock(address stock) external nonReentrant returns (uint256 amount) {
        amount = platformStock[stock];
        if (amount == 0) revert NothingOwed();
        platformStock[stock] = 0;
        _call(stock, abi.encodeWithSignature("transfer(address,uint256)", platform, amount));
        emit PlatformPaid(platform, stock, amount);
    }

    // ---------------------------------------------------------------- views

    function coin(address token) external view returns (Coin memory) {
        return coinOf[token];
    }

    function totals(address token) external view returns (Totals memory) {
        return totalsOf[token];
    }

    function stockInfo(address s) external view returns (Stock memory) {
        return stockOf[s];
    }

    function stockCount() external view returns (uint256) {
        return stockList.length;
    }

    function coinCount() external view returns (uint256) {
        return coinList.length;
    }

    /// @notice Everything a page needs about a coin in one call: its vault, the hook's waiting creator side, the coins
    ///         outstanding, and the ask of its stock now.
    function board(address token)
        external
        view
        returns (Coin memory c, Totals memory t, uint256 out, uint256 ask, uint256 owedInHook, uint256 pendingInHook)
    {
        c = coinOf[token];
        t = totalsOf[token];
        if (c.stock == address(0)) return (c, t, 0, 0, 0, 0);
        out = outstanding(token);
        ask = askOf(c.stock);
        IEleosHookLike.Book memory b = hook.book(token);
        owedInHook = b.creatorOwed;
        pendingInHook = uint256(b.pending) + b.snipePending;
    }

    // ---------------------------------------------------------------- internals

    function _payCreator(address token, address to, uint256 amount) internal {
        (bool ok,) = to.call{value: amount, gas: CREATOR_GAS}("");
        if (ok) {
            emit CreatorPaid(token, to, amount);
        } else {
            creatorOwed[token] += amount;
            emit CreatorOwed(token, to, amount);
        }
    }

    /// @dev a token call that must succeed (no return value or true)
    function _call(address token, bytes memory data) internal {
        (bool ok, bytes memory r) = token.call(data);
        if (!ok || (r.length != 0 && !abi.decode(r, (bool)))) revert Delivery();
    }

    function _trySend(address token, address to, uint256 amount) internal returns (bool) {
        (bool ok, bytes memory r) = token.call(abi.encodeWithSignature("transfer(address,uint256)", to, amount));
        return ok && (r.length == 0 || (r.length == 32 && abi.decode(r, (bool))));
    }

    /// @dev HYPE comes only through the functions above; the hook sends the creator side only while `collect` or a
    ///      launch waits for it, so nobody can make the hook pay here outside them and leave HYPE unbooked.
    receive() external payable {
        if (msg.sender != address(hook) || expecting == address(0)) revert Refused();
    }
}
../../lib/v4-core/src/types/Currency.sol120 lines
// 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)));
    }
}
../../lib/v4-core/src/types/PoolKey.sol23 lines
// 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;
}
../../lib/v4-core/src/interfaces/IHooks.sol153 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.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,
        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,
        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,
        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,
        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, 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,
        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);
}
../../lib/v4-core/src/interfaces/external/IERC6909Claims.sol67 lines
// 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);
}
../../lib/v4-core/src/interfaces/IProtocolFees.sol53 lines
// 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);
}
../../lib/v4-core/src/types/BalanceDelta.sol73 lines
// 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)
        }
    }
}
../../lib/v4-core/src/interfaces/IExtsload.sol22 lines
// 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);
}
../../lib/v4-core/src/interfaces/IExttload.sol16 lines
// 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);
}
../../lib/v4-core/src/types/PoolOperation.sol27 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";

/// @notice Parameter struct for `ModifyLiquidity` pool operations
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 Parameter struct for `Swap` pool operations
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;
}
../../lib/v4-core/src/interfaces/external/IERC20Minimal.sol49 lines
// 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);
}
../../lib/v4-core/src/libraries/CustomRevert.sol121 lines
// 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))
        }
    }
}
../../lib/v4-core/src/types/BeforeSwapDelta.sol39 lines
// 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)
        }
    }
}
../../lib/v4-core/src/libraries/SafeCast.sol61 lines
// 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));
    }
}