Robinhood MainnetChain ID: 4663
Contract detail

BondingCurve

Live Robinhood Chain account facts for 0x203e8d19…0ff9f7e6. No activity has been observed yet while historical coverage continues.

Address type
Smart contract
Transactions
0 observed
History coverage
No indexed activity found
Verification
Verified
Compiler
0.8.26+commit.8a97fa7a
Verification match
exact
Creation transaction
0xd0fb3359…9d4a9c45
Created at block
#92651080
Language
Solidity
EVM version
cancun
License
MIT
Compiler optimization
Enabled · 500 runs
Deployed bytecode hash
0x4f5f52664ad7095f563102c2c5263c55417b5e71b66e47fc9abbdb88421d0e01
Verified contract

Contract source code

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {TransientSlot} from "@openzeppelin/contracts/utils/TransientSlot.sol";
import {IHooks} from "v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolIdLibrary} from "v4-core/src/types/PoolId.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {LiquidityAmounts} from "../libraries/LiquidityAmounts.sol";
import {LaunchToken} from "./LaunchToken.sol";
import {
    GraduationInfo,
    IBondingCurve,
    ICharterDrop,
    IFeeEscrow,
    ILaunchConfig,
    ILaunchFactory,
    ILaunchHook,
    ILaunchpadEvents,
    InitParams
} from "./interfaces/ILaunchpad.sol";
import {CurveMath} from "./libraries/CurveMath.sol";
import {FeeMath} from "./libraries/FeeMath.sol";
import {TradeLog} from "./libraries/TradeLog.sol";
import {LaunchConstants} from "./libraries/LaunchConstants.sol";

/// @title BondingCurve
/// @notice One clone per launch. Constant-product curve over a phantom stock
///         reserve; the base fee plus the snipe schedule is charged in stock
///         and pushed out per trade. The buy that empties the curve migrates
///         the real stock and the pool supply into a locked full-range v4 pool.
///         Shape is a snapshot of the config at launch; fee rates are read live.
contract BondingCurve is
    IBondingCurve,
    ILaunchpadEvents,
    IUnlockCallback,
    ReentrancyGuardTransient
{
    using SafeERC20 for IERC20;
    using PoolIdLibrary for PoolKey;
    using TransientSlot for bytes32;
    using TransientSlot for TransientSlot.BooleanSlot;

    /// @dev `stockNet` moves the reserve; `stockGross` is what the trader pays on
    ///      a buy or what the curve releases before fees on a sell.
    struct Quote {
        uint256 tokenAmount;
        uint256 stockNet;
        uint256 stockGross;
        uint256 fee;
        uint256 totalBps;
        uint256 creatorBps;
        uint256 snipeEffBps;
    }

    bytes32 private constant MIGRATING_SLOT =
        keccak256("standard.launchpad.BondingCurve.migrating");

    IPoolManager internal immutable _poolManager;
    address public immutable hook;

    // Identity, set once
    address public factory;
    ILaunchConfig public config;
    LaunchToken internal _token;
    address public stock;
    bool public stockIsCurrency0;
    uint64 public launchTime;

    // Snapshot of the config at launch
    uint128 public phantomReserve;
    uint256 public curveSupply;
    uint256 public poolSupply;
    uint256 public endVirtualTokens;
    uint256 public creatorBuyCap;
    int24 public poolTickSpacing;
    uint16[] internal _snipeScheduleBps;
    /// @notice The constant product: phantom reserve times the starting virtual tokens.
    uint256 public k;
    /// @notice Tokens held back for charter branches. Delivered to the factory's
    ///         charter drop at graduation, or burned if none is set by then.
    uint256 public charterDropAmount;
    uint8 public dropMode;
    /// @notice The module the hook activates for the pool at graduation.
    address public module;
    /// @notice Whether the graduated pool is the token's only v4 venue.
    bool public enforced;

    // Live state
    uint256 public virtualStock;
    uint256 public virtualTokens;
    address public feeRecipient;
    bool public creatorBuyOpen;
    bool public graduated;
    bool private _initialized;

    event FeeRecipientChanged(address indexed previous, address indexed current);
    event FeeRecipientReassigned(address indexed previous, address indexed current);

    error AlreadyInitialized();
    error NotFactory();
    error NotRouter();
    error NotPoolManager();
    error NotMigrating();
    error CurveGraduated();
    error CreatorBuyClosed();
    error ExceedsRemainingSupply();
    error InsufficientReserve();
    error InsufficientOutput();
    error ExcessiveInput();
    error ZeroAddress();
    error NotFeeRecipient();
    error NotFactoryOwner();
    error InvalidRecipient();

    modifier onlyRouter() {
        if (msg.sender != ILaunchFactory(factory).router()) revert NotRouter();
        _;
    }

    modifier onlyFeeRecipient() {
        if (msg.sender != feeRecipient) revert NotFeeRecipient();
        _;
    }

    /// @dev The implementation marks itself initialized so only clones trade.
    constructor(IPoolManager poolManager_, address hook_) {
        _poolManager = poolManager_;
        hook = hook_;
        _initialized = true;
    }

    /// @notice Sets a fresh clone up. Only the factory, once.
    function initialize(InitParams calldata p) external {
        if (_initialized) revert AlreadyInitialized();
        _initialized = true;

        factory = msg.sender;
        config = ILaunchFactory(msg.sender).config();
        _token = LaunchToken(p.token);
        stock = p.stock;
        stockIsCurrency0 = p.stock < p.token;
        launchTime = uint64(block.timestamp);

        phantomReserve = p.phantomReserve;
        curveSupply = p.config.curveSupply;
        poolSupply = p.config.poolSupply;
        endVirtualTokens = p.config.endVirtualTokens;
        creatorBuyCap = p.config.creatorBuyCap;
        poolTickSpacing = p.config.poolTickSpacing;
        if (p.snipeTaxOn) _snipeScheduleBps = p.config.snipeScheduleBps;
        k = uint256(p.phantomReserve) * p.config.virtualTokens;
        charterDropAmount = p.charterDropAmount;
        dropMode = p.dropMode;
        module = p.module;
        enforced = p.enforced;

        virtualStock = p.phantomReserve;
        virtualTokens = p.config.virtualTokens;
        feeRecipient = p.creator;
        creatorBuyOpen = true;
    }

    // ------------------------------------------------------------------
    // Trading
    // ------------------------------------------------------------------

    /// @notice Buys with `stockIn`, capped at remaining supply. Pulls only the stock used.
    function buyExactIn(uint256 stockIn, uint256 minTokensOut, address recipient, address referrer)
        external
        nonReentrant
        returns (uint256 tokensOut, uint256 stockUsed)
    {
        return _buyIn(msg.sender, stockIn, minTokensOut, recipient, referrer, false);
    }

    /// @notice Buys exactly `tokensOut`. Reverts if more than the curve holds.
    function buyExactOut(uint256 tokensOut, uint256 maxStockIn, address recipient, address referrer)
        external
        nonReentrant
        returns (uint256 stockIn)
    {
        return _buyOut(msg.sender, tokensOut, maxStockIn, recipient, referrer, false);
    }

    /// @notice Sells exactly `tokensIn` for stock, fees taken from the payout.
    function sellExactIn(uint256 tokensIn, uint256 minStockOut, address recipient, address referrer)
        external
        nonReentrant
        returns (uint256 stockOut)
    {
        return _sellIn(msg.sender, msg.sender, tokensIn, minStockOut, recipient, referrer);
    }

    /// @notice Sells whatever tokens it takes to receive exactly `stockOut`.
    function sellExactOut(
        uint256 stockOut,
        uint256 maxTokensIn,
        address recipient,
        address referrer
    ) external nonReentrant returns (uint256 tokensIn) {
        return _sellOut(msg.sender, msg.sender, stockOut, maxTokensIn, recipient, referrer);
    }

    /// @notice Router-only buy: the router pays the stock and names its caller.
    function buyExactInFor(
        address trader,
        uint256 stockIn,
        uint256 minTokensOut,
        address recipient,
        address referrer
    ) external nonReentrant onlyRouter returns (uint256 tokensOut, uint256 stockUsed) {
        return _buyIn(trader, stockIn, minTokensOut, recipient, referrer, false);
    }

    /// @notice Router-only buy: the router pays the stock and names its caller.
    function buyExactOutFor(
        address trader,
        uint256 tokensOut,
        uint256 maxStockIn,
        address recipient,
        address referrer
    ) external nonReentrant onlyRouter returns (uint256 stockIn) {
        return _buyOut(trader, tokensOut, maxStockIn, recipient, referrer, false);
    }

    /// @notice Router-only sell: tokens are pulled from `trader`, the router's caller.
    function sellExactInFor(
        address trader,
        uint256 tokensIn,
        uint256 minStockOut,
        address recipient,
        address referrer
    ) external nonReentrant onlyRouter returns (uint256 stockOut) {
        return _sellIn(trader, trader, tokensIn, minStockOut, recipient, referrer);
    }

    /// @notice Router-only sell: tokens are pulled from `trader`, the router's caller.
    function sellExactOutFor(
        address trader,
        uint256 stockOut,
        uint256 maxTokensIn,
        address recipient,
        address referrer
    ) external nonReentrant onlyRouter returns (uint256 tokensIn) {
        return _sellOut(trader, trader, stockOut, maxTokensIn, recipient, referrer);
    }

    /// @notice The launch's first trade, factory only: no snipe tax, capped at
    ///         `creatorBuyCap` tokens, pulls only the stock needed.
    function creatorBuy(uint256 stockIn, uint256 minTokensOut, address recipient, address referrer)
        external
        nonReentrant
        returns (uint256 tokensOut, uint256 stockUsed)
    {
        if (msg.sender != factory) revert NotFactory();
        if (!creatorBuyOpen) revert CreatorBuyClosed();

        uint256 capGross = _quoteBuyOut(creatorBuyCap, true).stockGross;
        if (stockIn >= capGross) {
            stockUsed = _buyOut(recipient, creatorBuyCap, stockIn, recipient, referrer, true);
            if (creatorBuyCap < minTokensOut) revert InsufficientOutput();
            return (creatorBuyCap, stockUsed);
        }
        return _buyIn(recipient, stockIn, minTokensOut, recipient, referrer, true);
    }

    // ------------------------------------------------------------------
    // Settings
    // ------------------------------------------------------------------

    /// @notice Hands the creator's fee stream, and with it the pool's module
    ///         control, to another address.
    function setFeeRecipient(address newRecipient) external nonReentrant onlyFeeRecipient {
        if (newRecipient == address(0)) revert ZeroAddress();
        emit FeeRecipientChanged(feeRecipient, newRecipient);
        feeRecipient = newRecipient;
    }

    /// @notice Factory owner moves the fee stream, for a community takeover after
    ///         the creator walks away. The escrow pays its unclaimed balance to
    ///         the new recipient too, since it reads the recipient at claim.
    function reassignFeeRecipient(address newRecipient) external nonReentrant {
        if (msg.sender != Ownable(factory).owner()) revert NotFactoryOwner();
        if (newRecipient == address(0)) revert ZeroAddress();
        emit FeeRecipientReassigned(feeRecipient, newRecipient);
        feeRecipient = newRecipient;
    }

    // ------------------------------------------------------------------
    // Views
    // ------------------------------------------------------------------

    function poolManager() external view returns (address) {
        return address(_poolManager);
    }

    function token() external view returns (address) {
        return address(_token);
    }

    function quoteBuyExactIn(uint256 stockIn)
        external
        view
        returns (uint256 tokensOut, uint256 stockUsed)
    {
        if (graduated) revert CurveGraduated();
        Quote memory q = _quoteBuyIn(stockIn, false);
        return (q.tokenAmount, q.stockGross);
    }

    function quoteBuyExactOut(uint256 tokensOut) external view returns (uint256 stockIn) {
        if (graduated) revert CurveGraduated();
        return _quoteBuyOut(tokensOut, false).stockGross;
    }

    function quoteSellExactIn(uint256 tokensIn) external view returns (uint256 stockOut) {
        if (graduated) revert CurveGraduated();
        Quote memory q = _quoteSellIn(tokensIn);
        return q.stockGross - q.fee;
    }

    function quoteSellExactOut(uint256 stockOut) external view returns (uint256 tokensIn) {
        if (graduated) revert CurveGraduated();
        return _quoteSellOut(stockOut).tokenAmount;
    }

    function currentSnipeTaxBps() external view returns (uint256) {
        return _snipeBps();
    }

    function snipeSchedule() external view returns (uint16[] memory) {
        return _snipeScheduleBps;
    }

    function remainingSupply() external view returns (uint256) {
        return virtualTokens - endVirtualTokens;
    }

    function realStockReserve() external view returns (uint256) {
        return virtualStock - phantomReserve;
    }

    /// @notice The pool this curve graduates into.
    function poolKey() external view returns (PoolKey memory) {
        return _poolKey();
    }

    // ------------------------------------------------------------------
    // Trade execution
    // ------------------------------------------------------------------

    function _buyIn(
        address trader,
        uint256 stockIn,
        uint256 minTokensOut,
        address recipient,
        address referrer,
        bool isCreatorBuy
    ) internal returns (uint256 tokensOut, uint256 stockUsed) {
        _checkTradable(recipient);
        Quote memory q = _quoteBuyIn(stockIn, isCreatorBuy);
        if (q.tokenAmount < minTokensOut) revert InsufficientOutput();
        _executeBuy(q, trader, recipient, referrer);
        return (q.tokenAmount, q.stockGross);
    }

    function _buyOut(
        address trader,
        uint256 tokensOut,
        uint256 maxStockIn,
        address recipient,
        address referrer,
        bool isCreatorBuy
    ) internal returns (uint256 stockIn) {
        _checkTradable(recipient);
        Quote memory q = _quoteBuyOut(tokensOut, isCreatorBuy);
        if (q.stockGross > maxStockIn) revert ExcessiveInput();
        _executeBuy(q, trader, recipient, referrer);
        return q.stockGross;
    }

    function _sellIn(
        address tokenSource,
        address trader,
        uint256 tokensIn,
        uint256 minStockOut,
        address recipient,
        address referrer
    ) internal returns (uint256 stockOut) {
        _checkTradable(recipient);
        Quote memory q = _quoteSellIn(tokensIn);
        stockOut = q.stockGross - q.fee;
        if (stockOut < minStockOut) revert InsufficientOutput();
        _executeSell(q, tokenSource, trader, recipient, referrer);
    }

    function _sellOut(
        address tokenSource,
        address trader,
        uint256 stockOut,
        uint256 maxTokensIn,
        address recipient,
        address referrer
    ) internal returns (uint256 tokensIn) {
        _checkTradable(recipient);
        Quote memory q = _quoteSellOut(stockOut);
        if (q.tokenAmount > maxTokensIn) revert ExcessiveInput();
        _executeSell(q, tokenSource, trader, recipient, referrer);
        return q.tokenAmount;
    }

    /// @dev Stock is pulled from msg.sender: the trader, the router, or the factory.
    function _executeBuy(Quote memory q, address trader, address recipient, address referrer)
        internal
    {
        creatorBuyOpen = false;
        virtualTokens -= q.tokenAmount;
        virtualStock += q.stockNet;

        IERC20(stock).safeTransferFrom(msg.sender, address(this), q.stockGross);
        (uint256 creatorFee, uint256 protocolFee) = _deliverFees(q);
        IERC20(address(_token)).safeTransfer(recipient, q.tokenAmount);
        _logTrade(true, trader, recipient, referrer, q, creatorFee, protocolFee);

        if (virtualTokens == endVirtualTokens) _graduate();
    }

    function _executeSell(
        Quote memory q,
        address tokenSource,
        address trader,
        address recipient,
        address referrer
    ) internal {
        creatorBuyOpen = false;
        virtualTokens += q.tokenAmount;
        virtualStock -= q.stockNet;

        IERC20(address(_token)).safeTransferFrom(tokenSource, address(this), q.tokenAmount);
        (uint256 creatorFee, uint256 protocolFee) = _deliverFees(q);
        IERC20(stock).safeTransfer(recipient, q.stockGross - q.fee);
        _logTrade(false, trader, recipient, referrer, q, creatorFee, protocolFee);
    }

    function _checkTradable(address recipient) internal view {
        if (graduated) revert CurveGraduated();
        if (recipient == address(0)) revert ZeroAddress();
        if (recipient == address(this)) revert InvalidRecipient();
    }

    /// @dev Creator's part to the escrow, protocol's part to the fee multisig.
    function _deliverFees(Quote memory q)
        internal
        returns (uint256 creatorFee, uint256 protocolFee)
    {
        (creatorFee, protocolFee) = FeeMath.split(q.fee, q.totalBps, q.creatorBps);
        if (creatorFee > 0) {
            address escrow = config.feeEscrow();
            IERC20(stock).safeTransfer(escrow, creatorFee);
            IFeeEscrow(escrow).credit(address(this), creatorFee);
        }
        if (protocolFee > 0) {
            IERC20(stock).safeTransfer(config.feeMultisig(), protocolFee);
        }
    }

    function _logTrade(
        bool isBuy,
        address trader,
        address recipient,
        address referrer,
        Quote memory q,
        uint256 creatorFee,
        uint256 protocolFee
    ) internal {
        TradeLog.Data memory d;
        d.recipient = recipient;
        d.isBuy = isBuy;
        d.tokenAmount = q.tokenAmount;
        d.stockAmount = q.stockGross;
        d.totalFee = q.fee;
        d.creatorFee = creatorFee;
        d.protocolFee = protocolFee;
        d.snipeFee = q.totalBps == 0 ? 0 : q.fee * q.snipeEffBps / q.totalBps;
        d.priceAfterWad = virtualStock * LaunchConstants.WAD / virtualTokens;
        d.virtualStockAfter = virtualStock;
        d.virtualTokensAfter = virtualTokens;
        TradeLog.emitTrade(address(_token), trader, referrer == trader ? address(0) : referrer, d);
    }

    // ------------------------------------------------------------------
    // Quotes
    // ------------------------------------------------------------------

    function _rates(bool isBuy, bool isCreatorBuy)
        internal
        view
        returns (uint256 totalBps, uint256 creatorBps, uint256 snipeEffBps)
    {
        uint256 snipe = (isBuy && !isCreatorBuy) ? _snipeBps() : 0;
        (uint16 base, uint16 creatorShare, uint16 cap) = config.feeRates();
        (totalBps, snipeEffBps) = FeeMath.effectiveRates(base, snipe, cap);
        creatorBps = creatorShare;
    }

    function _snipeBps() internal view returns (uint256) {
        uint256 i = block.timestamp - launchTime;
        return i < _snipeScheduleBps.length ? _snipeScheduleBps[i] : 0;
    }

    /// @dev An exact-in buy past the remaining supply becomes an exact-out buy of
    ///      the remainder. Rounding can push that gross a few wei over `stockIn`;
    ///      the fee absorbs it so the trader never pays more than stated.
    function _quoteBuyIn(uint256 stockIn, bool isCreatorBuy)
        internal
        view
        returns (Quote memory q)
    {
        (q.totalBps, q.creatorBps, q.snipeEffBps) = _rates(true, isCreatorBuy);
        q.fee = FeeMath.feeOnGross(stockIn, q.totalBps);
        q.stockNet = stockIn - q.fee;
        q.stockGross = stockIn;
        q.tokenAmount = CurveMath.buyExactIn(k, virtualTokens, virtualStock, q.stockNet);

        uint256 remaining = virtualTokens - endVirtualTokens;
        if (q.tokenAmount >= remaining) {
            q.tokenAmount = remaining;
            q.stockNet = CurveMath.buyExactOut(k, virtualTokens, virtualStock, remaining);
            q.fee = FeeMath.feeOnNet(q.stockNet, q.totalBps);
            q.stockGross = q.stockNet + q.fee;
            if (q.stockGross > stockIn) {
                q.stockGross = stockIn;
                q.fee = stockIn - q.stockNet;
            }
        }
    }

    function _quoteBuyOut(uint256 tokensOut, bool isCreatorBuy)
        internal
        view
        returns (Quote memory q)
    {
        if (tokensOut > virtualTokens - endVirtualTokens) revert ExceedsRemainingSupply();
        (q.totalBps, q.creatorBps, q.snipeEffBps) = _rates(true, isCreatorBuy);
        q.tokenAmount = tokensOut;
        q.stockNet = CurveMath.buyExactOut(k, virtualTokens, virtualStock, tokensOut);
        q.fee = FeeMath.feeOnNet(q.stockNet, q.totalBps);
        q.stockGross = q.stockNet + q.fee;
    }

    function _quoteSellIn(uint256 tokensIn) internal view returns (Quote memory q) {
        (q.totalBps, q.creatorBps, q.snipeEffBps) = _rates(false, false);
        q.tokenAmount = tokensIn;
        q.stockNet = CurveMath.sellExactIn(k, virtualTokens, virtualStock, tokensIn);
        if (q.stockNet > virtualStock - phantomReserve) revert InsufficientReserve();
        q.stockGross = q.stockNet;
        q.fee = FeeMath.feeOnGross(q.stockNet, q.totalBps);
    }

    function _quoteSellOut(uint256 stockOut) internal view returns (Quote memory q) {
        (q.totalBps, q.creatorBps, q.snipeEffBps) = _rates(false, false);
        q.fee = FeeMath.feeOnNet(stockOut, q.totalBps);
        q.stockNet = stockOut + q.fee;
        q.stockGross = q.stockNet;
        if (q.stockNet > virtualStock - phantomReserve) revert InsufficientReserve();
        q.tokenAmount = CurveMath.sellExactOut(k, virtualTokens, virtualStock, q.stockNet);
    }

    // ------------------------------------------------------------------
    // Graduation and migration
    // ------------------------------------------------------------------

    /// @dev Ends the buy that empties the curve, after the buyer's tokens and fees
    ///      are out. The token learns of graduation first: its PoolManager guard
    ///      would otherwise refuse the migration's own settlement.
    function _graduate() internal {
        graduated = true;
        _token.onGraduated();

        PoolKey memory key = _poolKey();
        (uint128 liquidity, uint256 paid0, uint256 paid1) = _migrate(key);
        _sweepDustAndRecord(key, liquidity, paid0, paid1);
    }

    /// @dev Initializes the pool at the curve's final price with all real stock
    ///      and the pool supply. Returns liquidity minted and what each side cost.
    function _migrate(PoolKey memory key) internal returns (uint128, uint256, uint256) {
        uint256 stockForPool = virtualStock - phantomReserve;
        (uint256 amount0, uint256 amount1) =
            stockIsCurrency0 ? (stockForPool, poolSupply) : (poolSupply, stockForPool);
        uint160 sqrtPriceX96 = uint160(Math.sqrt(Math.mulDiv(amount1, uint256(1) << 192, amount0)));

        _poolManager.initialize(key, sqrtPriceX96);

        MIGRATING_SLOT.asBoolean().tstore(true);
        bytes memory result = _poolManager.unlock(abi.encode(key, sqrtPriceX96, amount0, amount1));
        MIGRATING_SLOT.asBoolean().tstore(false);
        return abi.decode(result, (uint128, uint256, uint256));
    }

    function _sweepDustAndRecord(
        PoolKey memory key,
        uint128 liquidity,
        uint256 paid0,
        uint256 paid1
    ) internal {
        GraduationInfo memory info;
        info.poolId = key.toId();
        info.liquidity = liquidity;
        info.module = ILaunchHook(hook).moduleOf(info.poolId);
        (info.stockToPool, info.tokensToPool) = stockIsCurrency0 ? (paid0, paid1) : (paid1, paid0);

        (info.tokensToCharters, info.charterDrop, info.charterSnapshotComplete) =
            _deliverCharterDrop();
        info.tokensBurned = _token.balanceOf(address(this));
        if (info.tokensBurned > 0) {
            IERC20(address(_token)).safeTransfer(LaunchConstants.DEAD, info.tokensBurned);
        }
        info.stockDust = IERC20(stock).balanceOf(address(this));
        if (info.stockDust > 0) {
            IERC20(stock).safeTransfer(config.feeMultisig(), info.stockDust);
        }

        ILaunchFactory(factory).recordGraduation(info);
    }

    /// @dev Hands the reserved slice to the factory's current charter drop and
    ///      snapshots branch counts in the same block. The drop is read at
    ///      graduation, not launch: `setCharterDrop(0)` retires a broken drop and
    ///      the slice falls to the dust sweep, which burns it. The snapshot gets
    ///      whatever gas is left over the graduation reserve and is best-effort;
    ///      a reverting drop or a large charter set leaves the rest to a later
    ///      `snapshot` call and never blocks the buy.
    function _deliverCharterDrop()
        internal
        returns (uint256 amount, address dropAddress, bool snapshotComplete)
    {
        amount = charterDropAmount;
        if (amount == 0) return (0, address(0), false);
        dropAddress = ILaunchFactory(factory).charterDrop();
        if (dropAddress == address(0)) return (0, address(0), false);
        ICharterDrop drop = ICharterDrop(dropAddress);
        IERC20(address(_token)).safeTransfer(dropAddress, amount);
        drop.register(address(_token), amount, dropMode);
        uint256 left = gasleft();
        uint256 reserve = LaunchConstants.GRADUATION_GAS_RESERVE;
        try drop.snapshot{gas: left > reserve ? left - reserve : 0}(address(_token)) {} catch {}
        snapshotComplete = drop.snapshotComplete(address(_token));
    }

    /// @dev Mints the one full-range position and pays for it. PoolManager only,
    ///      and only inside `_graduate`'s unlock.
    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        if (msg.sender != address(_poolManager)) revert NotPoolManager();
        if (!MIGRATING_SLOT.asBoolean().tload()) revert NotMigrating();

        (PoolKey memory key, uint160 sqrtPriceX96, uint256 amount0, uint256 amount1) =
            abi.decode(data, (PoolKey, uint160, uint256, uint256));
        int24 tickLower = TickMath.minUsableTick(key.tickSpacing);
        int24 tickUpper = TickMath.maxUsableTick(key.tickSpacing);
        uint128 liquidity = LiquidityAmounts.getLiquidityForAmounts(
            sqrtPriceX96,
            TickMath.getSqrtPriceAtTick(tickLower),
            TickMath.getSqrtPriceAtTick(tickUpper),
            amount0,
            amount1
        );

        (BalanceDelta delta,) = _poolManager.modifyLiquidity(
            key,
            IPoolManager.ModifyLiquidityParams({
                tickLower: tickLower,
                tickUpper: tickUpper,
                liquidityDelta: int256(uint256(liquidity)),
                salt: 0
            }),
            ""
        );
        uint256 paid0 = _settle(key.currency0, delta.amount0());
        uint256 paid1 = _settle(key.currency1, delta.amount1());
        return abi.encode(liquidity, paid0, paid1);
    }

    function _settle(Currency currency, int128 delta) internal returns (uint256 owed) {
        if (delta >= 0) return 0;
        owed = uint256(uint128(-delta));
        _poolManager.sync(currency);
        IERC20(Currency.unwrap(currency)).safeTransfer(address(_poolManager), owed);
        _poolManager.settle();
    }

    function _poolKey() internal view returns (PoolKey memory) {
        (address currency0, address currency1) =
            stockIsCurrency0 ? (stock, address(_token)) : (address(_token), stock);
        return PoolKey({
            currency0: Currency.wrap(currency0),
            currency1: Currency.wrap(currency1),
            fee: LaunchConstants.POOL_LP_FEE,
            tickSpacing: poolTickSpacing,
            hooks: IHooks(hook)
        });
    }
}