Skip to content
Verified contractPartialMIT

StockFactory

Address0x45d89272c4a00b818fc3d0458f8bc4ffa9feefb0
Balance

0 ETH

 

Transactions

39

 

Compiler

solc 0.8.26

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,277,191
Creation transaction
0x47063186e0…56370134e0

94 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/stock/StockFactory.sol

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

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "v4-core/interfaces/callback/IUnlockCallback.sol";
import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {SwapParams} from "v4-core/types/PoolOperation.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {IPositionManager} from "v4-periphery/interfaces/IPositionManager.sol";
import {Actions} from "v4-periphery/libraries/Actions.sol";
import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {ILayerZeroEndpointV2} from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
import {EnforcedOptionParam} from "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppOptionsType3.sol";

import {StockToken} from "./StockToken.sol";
import {StockDeployer} from "./StockDeployer.sol";
import {LaunchMath} from "../libraries/LaunchMath.sol";

/**
 * @title StockFactory
 * @notice stock.fun: launch a coin once; it goes live on every chain of its plan at the same address and the same
 * dollar price, and every chain's pool pairs it against that chain's version of ONE stock (or the native coin).
 *
 * The factory is CREATE2-deployed through the canonical deployer with chain-agnostic init code (constructor arg = owner
 * only), so it sits at one address on every chain; everything chain-specific arrives once through `initialize`. Its
 * StockDeployer (constructor arg = this factory) is likewise at one address everywhere and holds the token code.
 *
 * Quotes: every chain's factory maps a ticker ("NVDA") to that chain's stock token (Ondo on Ethereum, cStocks on Base,
 * Robinhood's own on Robinhood Chain, bStocks on BNB Chain) and keeps, per ticker, the opening market cap in that
 * stock's own units (`openingMcapQuote` = $7,000 at the stock's current price, refreshed by the launcher key).
 * "NATIVE" is the chain's own coin.
 *
 * A launch is the SAME `LaunchParams` submitted on every chain of the plan: by the creator on the chain they pay on
 * (`launch`, launch fee + optional dev buy), and by the platform's launcher key on the others (`launchFor`). On each
 * chain the factory:
 *   1. has the deployer CREATE2-deploy the StockToken (same address everywhere; it mints this chain's share of the 1B
 *      to us) and pin every LayerZero route of it (send/receive library, executor, DVNs, confirmations)
 *   2. sets the lzReceive gas floor, then hands the token's endpoint delegate to 0xdead so no key can re-route it
 *   3. opens a plain hookless Uniswap v4 pool vs the quote at the launch's opening market cap, LP fee = the launch's
 *      trading fee, so aggregators and DexScreener see an ordinary pool
 *   4. puts the whole local share in as one one-sided position held by this factory (only the owner's `rescue`
 *      can pull it, every market on this chain at once)
 *
 * Fees: the position's LP fees are collected by anyone through `collectFees`; token-side fees are sold into the pool
 * for the quote, then 20% goes to the platform treasury and 80% to the launch's fee recipient (the creator by default).
 *
 * Prices stay together by arbitrage: buy on the cheaper chain, bridge with the OFT, sell on the dearer one.
 */
contract StockFactory is Ownable, ReentrancyGuard, IUnlockCallback {
    using SafeERC20 for IERC20;

    /// @dev market caps are quoted on 1B (each chain's own 1B, or the whole coin in degen mode)
    uint256 public constant MCAP_SUPPLY = 1_000_000_000e18;
    /// @dev 1: the opening price snaps to the grid by at most 0.01% (only the launch position's two ticks are initialized)
    int24 public constant TICK_SPACING = 1;
    uint24 public constant MIN_TRADING_FEE = 3_000; // 0.3%
    uint24 public constant MAX_TRADING_FEE = 50_000; // 5%
    uint16 public constant PLATFORM_CUT_BPS = 2_000; // 20% of trading fees
    /// @dev every launch opens at exactly this global market cap, on every chain
    uint256 public constant OPENING_MCAP_USD = 7_000;
    uint128 public constant MIN_RECEIVE_GAS = 60_000;
    uint128 public constant MAX_RECEIVE_GAS = 1_000_000;
    uint32 public constant SOLANA_EID = 30168;
    /// @dev lamports the executor drops with every delivery to Solana (rent for the receiver's token account)
    uint128 public constant SOLANA_RECEIVE_VALUE = 2_500_000;
    uint16 internal constant MSG_SEND = 1;
    uint16 internal constant MSG_SEND_AND_CALL = 2;
    bytes32 public constant NATIVE_TICKER = "NATIVE";
    address public constant NATIVE = address(0);
    address public constant DEAD = 0x000000000000000000000000000000000000dEaD;

    /// @dev one chain the factory routes to: chain id, eid, the block confirmations its sends wait for, and which of
    /// THIS chain's DVNs (bit i = dvns[i]) the route uses: the providers both ends run. Any 2 of them must attest.
    struct Route {
        uint256 chainId;
        uint32 eid;
        uint64 confirmations;
        uint8 dvnMask;
    }

    /// @dev everything chain-specific, set once by `initialize`
    struct ChainConfig {
        StockDeployer deployer;
        /// @dev the LockstepRescuer (same address on every chain): may trigger `rescue` when the owner sends it
        address rescuer;
        IPoolManager poolManager;
        IPositionManager positionManager;
        IAllowanceTransfer permit2;
        address lzEndpoint;
        address sendLib;
        address receiveLib;
        address executor;
        /// @dev this chain's DVN contracts, ascending; each route picks its 2-of-N set from them by mask
        address[] dvns;
        /// @dev every chain stock.fun runs on, this one included (Solana as SOLANA_CHAIN_ID / SOLANA_EID)
        Route[] routes;
        address treasury;
        address launcher;
        uint256 launchFee;
        uint128 receiveGas;
    }

    /// @dev one thing a pool can pair against on this chain
    struct Quote {
        /// @dev the stock token here, or NATIVE
        address token;
        uint8 decimals;
        /// @dev OPENING_MCAP_USD in the quote's own units at its current price; 0 = not launchable
        uint256 openingMcap;
    }

    struct LaunchParams {
        string name;
        string symbol;
        StockToken.Metadata metadata;
        StockToken.Plan plan;
        /// @dev the stock every chain pairs against ("NVDA"), or NATIVE_TICKER
        bytes32 quote;
        /// @dev the Solana OFT store the coin bridges to; 0 unless Solana is in the plan
        bytes32 solanaPeer;
        /// @dev v4 pips, 3000..50000 (0.3%..5%)
        uint24 tradingFee;
        /// @dev must be OPENING_MCAP_USD (7000): the market cap (of 1B) every chain opens at
        uint256 openingMcapUsd;
        /// @dev creator-chosen salt, reused on every chain (part of the address)
        bytes32 salt;
    }

    struct Launch {
        address token;
        address creator;
        address feeRecipient;
        uint256 positionId;
        uint256 localSupply;
        uint64 launchedAt;
        /// @dev the pool: the coin and its quote (this chain's stock, or NATIVE) in address order
        PoolKey key;
    }

    StockDeployer public deployer;
    address public rescuer;
    IPoolManager public poolManager;
    IPositionManager public positionManager;
    IAllowanceTransfer public permit2;
    address public lzEndpoint;
    address public sendLib;
    address public receiveLib;
    address public executor;
    address[] internal _dvns;
    uint32 public localEid;
    mapping(uint32 eid => Route) public routeOf;
    uint32[] public eids;

    address public treasury;
    address public launcher;
    uint256 public launchFee;
    uint128 public receiveGas;
    bool public launchEnabled;
    bool public initialized;

    mapping(bytes32 ticker => Quote) public quotes;
    bytes32[] public tickers;

    address[] public tokens;
    mapping(address token => Launch) internal _launches;

    event Initialized(uint32 localEid, address lzEndpoint, address treasury, address launcher);
    event RouteAdded(uint256 chainId, uint32 eid, uint64 confirmations);
    event QuoteSet(bytes32 indexed ticker, address token, uint8 decimals, uint256 openingMcap);
    event TokenLaunched(address indexed token, address indexed creator, bytes32 quote, address quoteToken, uint256 openingMcap, bool paidHere);
    event Swap(address indexed token, address indexed to, bool buy, uint256 amountIn, uint256 amountOut);
    event FeesCollected(address indexed token, uint256 quoteFees, uint256 tokenFees, uint256 tokenFeesSoldFor, uint256 toCreator, uint256 toPlatform);
    event FeeRecipientSet(address indexed token, address recipient);
    event AdminSet(address treasury, address launcher, uint256 launchFee, uint128 receiveGas, bool launchEnabled);
    event Rescued(address indexed token, uint256 indexed positionId, uint128 liquidity, address to);

    error ZeroAddress();
    error AlreadyInitialized();
    error NotInitialized();
    error LaunchesDisabled();
    error NotPoolManager();
    error NotLauncher();
    error NotFeeRecipient();
    error SlippageExceeded();
    error UnknownToken();
    error UnknownQuote();
    error WrongValue();
    error EmptyString();
    error LogoTooLarge();
    error BadTradingFee();
    error BadMcap();
    error BadRoute();
    error UnsupportedChain(uint256 chainId, uint32 eid);
    error WrongLaunchFee();
    error BadGas();
    error NativeTransferFailed();

    /// @dev the ONLY constructor argument: keeps the init code identical on every chain
    constructor(address owner_) Ownable(owner_) {}

    modifier onlyLauncher() {
        if (msg.sender != launcher && msg.sender != owner()) revert NotLauncher();
        _;
    }

    // ----------------------------- one-shot chain config -----------------------------

    function initialize(ChainConfig calldata c) external onlyOwner {
        if (initialized) revert AlreadyInitialized();
        if (c.treasury == address(0) || c.launcher == address(0) || c.dvns.length == 0) revert ZeroAddress();
        for (uint256 i = 1; i < c.dvns.length; ++i) {
            if (c.dvns[i] <= c.dvns[i - 1]) revert BadRoute(); // ascending, no duplicates (ULN requirement)
        }
        if (c.receiveGas < MIN_RECEIVE_GAS || c.receiveGas > MAX_RECEIVE_GAS) revert BadGas();

        if (c.deployer.factory() != address(this)) revert BadRoute();
        deployer = c.deployer;
        rescuer = c.rescuer;
        poolManager = c.poolManager;
        positionManager = c.positionManager;
        permit2 = c.permit2;
        lzEndpoint = c.lzEndpoint;
        sendLib = c.sendLib;
        receiveLib = c.receiveLib;
        executor = c.executor;
        _dvns = c.dvns;
        localEid = ILayerZeroEndpointV2(c.lzEndpoint).eid();
        for (uint256 i; i < c.routes.length; ++i) _addRoute(c.routes[i]);
        if (routeOf[localEid].chainId != block.chainid) revert BadRoute();

        treasury = c.treasury;
        launcher = c.launcher;
        launchFee = c.launchFee;
        receiveGas = c.receiveGas;
        launchEnabled = true;
        initialized = true;
        emit Initialized(localEid, c.lzEndpoint, c.treasury, c.launcher);
    }

    /// @notice Add a chain, or re-pin an existing route's confirmations / DVN set, for FUTURE launches. Existing tokens
    /// are unaffected (their peers and route configs were fixed when they launched).
    function addRoute(Route calldata r) external onlyOwner {
        _addRoute(r);
    }

    function _addRoute(Route calldata r) internal {
        if (r.chainId == 0 || r.eid == 0 || r.confirmations == 0 || r.dvnMask == 0) revert BadRoute();
        if (routeOf[r.eid].eid == 0) eids.push(r.eid);
        routeOf[r.eid] = r;
        emit RouteAdded(r.chainId, r.eid, r.confirmations);
    }

    // ----------------------------- quotes -----------------------------

    /// @notice Register (or re-point) what a ticker pairs against on this chain. `token` = NATIVE for the native coin.
    function setQuote(bytes32 ticker, address token, uint256 openingMcap) external onlyOwner {
        if (ticker == 0) revert UnknownQuote();
        if ((ticker == NATIVE_TICKER) != (token == NATIVE)) revert UnknownQuote();
        Quote storage q = quotes[ticker];
        if (q.decimals == 0 && q.token == NATIVE && q.openingMcap == 0) tickers.push(ticker);
        q.token = token;
        q.decimals = token == NATIVE ? 18 : IERC20Metadata(token).decimals();
        q.openingMcap = openingMcap;
        emit QuoteSet(ticker, token, q.decimals, openingMcap);
    }

    /// @notice Refresh opening market caps as stock prices move: OPENING_MCAP_USD in each quote's units. The launcher key
    /// keeps them fresh. 0 pauses launches on that quote.
    function setOpeningMcaps(bytes32[] calldata ts, uint256[] calldata mcaps) external onlyLauncher {
        if (ts.length != mcaps.length) revert BadMcap();
        for (uint256 i; i < ts.length; ++i) {
            Quote storage q = quotes[ts[i]];
            if (q.decimals == 0) revert UnknownQuote();
            q.openingMcap = mcaps[i];
            emit QuoteSet(ts[i], q.token, q.decimals, mcaps[i]);
        }
    }

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

    function confirmationsOf(uint32 eid) external view returns (uint64) {
        return routeOf[eid].confirmations;
    }

    function dvns() external view returns (address[] memory) {
        return _dvns;
    }

    function routes() external view returns (Route[] memory out) {
        out = new Route[](eids.length);
        for (uint256 i; i < eids.length; ++i) out[i] = routeOf[eids[i]];
    }

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

    function getLaunch(address token) external view returns (Launch memory) {
        return _launches[token];
    }

    /// @notice The address the token gets on EVERY chain of its plan.
    function predictTokenAddress(address creator, LaunchParams calldata p) external view returns (address) {
        return deployer.predict(_salt(creator, p.salt), _args(creator, p));
    }

    // ----------------------------- admin -----------------------------

    /// @notice Treasury, launcher key, launch fee, lzReceive gas floor for FUTURE launches, and the launch switch.
    function setAdmin(address treasury_, address launcher_, uint256 launchFee_, uint128 receiveGas_, bool enabled) external onlyOwner {
        if (treasury_ == address(0) || launcher_ == address(0)) revert ZeroAddress();
        if (receiveGas_ < MIN_RECEIVE_GAS || receiveGas_ > MAX_RECEIVE_GAS) revert BadGas();
        treasury = treasury_;
        launcher = launcher_;
        launchFee = launchFee_;
        receiveGas = receiveGas_;
        launchEnabled = enabled;
        emit AdminSet(treasury_, launcher_, launchFee_, receiveGas_, enabled);
    }

    /// @notice Pull 100% of every launch's liquidity on THIS chain (tokens, quote and unclaimed fees) to the owner. Closes
    /// every market here. Called by the owner, or by the rescuer when the owner's LockstepRescuer.rescue on any chain
    /// reaches this one over LayerZero (that is how one rescue empties every chain).
    function rescue() external nonReentrant {
        if (msg.sender != owner() && msg.sender != rescuer) revert NotLauncher();
        address to = owner();
        for (uint256 i; i < tokens.length; ++i) {
            Launch storage l = _launches[tokens[i]];
            uint128 liq = positionManager.getPositionLiquidity(l.positionId);
            if (liq == 0) continue;
            _take(l, liq, to);
            emit Rescued(l.token, l.positionId, liq, to);
        }
    }

    // ----------------------------- creator -----------------------------

    function setFeeRecipient(address token, address recipient) external {
        Launch storage l = _launches[token];
        if (l.token == address(0)) revert UnknownToken();
        if (msg.sender != l.feeRecipient && msg.sender != l.creator) revert NotFeeRecipient();
        if (recipient == address(0)) revert ZeroAddress();
        l.feeRecipient = recipient;
        emit FeeRecipientSet(token, recipient);
    }

    // ----------------------------- launch -----------------------------

    /// @notice Launch on the chain you pay on. `msg.value` = launchFee, plus the dev buy when the coin pairs with native;
    /// `devBuyQuote` is the dev buy in the stock when it pairs with one (approve this factory first). The platform
    /// launcher then submits the same params on every other chain of the plan.
    function launch(LaunchParams calldata p, uint256 devBuyQuote, uint256 devBuyMinTokens)
        external
        payable
        nonReentrant
        returns (address token, uint256 devBuyTokens)
    {
        if (msg.value < launchFee) revert WrongLaunchFee();
        token = _launch(msg.sender, p, true);
        if (launchFee != 0) _pay(treasury, launchFee);
        uint256 devBuy = _pull(_launches[token], msg.value - launchFee, devBuyQuote);
        if (devBuy != 0) devBuyTokens = _swap(_launches[token], true, devBuy, devBuyMinTokens, msg.sender);
    }

    /// @notice The launcher replays a launch on the plan's other chains. The creator paid once, on their chain.
    function launchFor(address creator, LaunchParams calldata p) external nonReentrant onlyLauncher returns (address token) {
        token = _launch(creator, p, false);
    }

    // ----------------------------- trade -----------------------------

    /// @notice Buy (`buy` = true, paying in the coin's quote: `msg.value` of native, or `amountIn` of the stock, approved)
    /// or sell (`amountIn` of the coin, approved; the quote goes to `to`) straight through the coin's pool here.
    /// Native <-> stock for stock-paired coins is the per-chain StockRouter's job.
    function trade(address token, bool buy, uint256 amountIn, uint256 minOut, address to) external payable nonReentrant returns (uint256 out) {
        Launch storage l = _launches[token];
        if (l.token == address(0)) revert UnknownToken();
        if (buy) {
            amountIn = _pull(l, msg.value, amountIn);
        } else {
            if (msg.value != 0) revert WrongValue();
            IERC20(token).safeTransferFrom(msg.sender, address(this), amountIn);
        }
        out = _swap(l, buy, amountIn, minOut, to);
    }

    /// @dev the quote for a buy: msg.value for a native-paired coin (no stock may come with it), else `amount` of the
    /// stock pulled from the caller (no value may come with it)
    function _pull(Launch storage l, uint256 value, uint256 amount) internal returns (uint256) {
        address qt = _quoteOf(l);
        if (qt == NATIVE) {
            if (amount != 0) revert WrongValue();
            return value;
        }
        if (value != 0) revert WrongValue();
        if (amount != 0) IERC20(qt).safeTransferFrom(msg.sender, address(this), amount);
        return amount;
    }

    function _launch(address creator, LaunchParams calldata p, bool paidHere) internal returns (address token) {
        if (!initialized) revert NotInitialized();
        if (!launchEnabled) revert LaunchesDisabled();
        if (bytes(p.name).length == 0 || bytes(p.symbol).length == 0) revert EmptyString();
        if (bytes(p.metadata.logo).length > 12_000) revert LogoTooLarge();
        if (p.tradingFee < MIN_TRADING_FEE || p.tradingFee > MAX_TRADING_FEE) revert BadTradingFee();
        if (p.openingMcapUsd != OPENING_MCAP_USD) revert BadMcap();
        Quote memory q = quotes[p.quote];
        if (q.decimals == 0 || q.openingMcap == 0) revert UnknownQuote();
        StockToken.Plan calldata pl = p.plan;
        for (uint256 i; i < pl.eids.length; ++i) {
            if (i >= pl.chainIds.length || routeOf[pl.eids[i]].chainId != pl.chainIds[i]) {
                revert UnsupportedChain(i < pl.chainIds.length ? pl.chainIds[i] : 0, pl.eids[i]);
            }
        }

        // 1. same deployer + same init code + same salt => same address on every chain; the token checks the plan.
        //    The deployer is the token's endpoint delegate for this one call and pins every route.
        uint32[] memory remotes = _remotes(pl.eids);
        token = deployer.deploy(_salt(creator, p.salt), _args(creator, p), remotes);

        // 2. gas floor, then the endpoint delegate goes to 0xdead for good
        StockToken(token).setEnforcedOptions(_enforcedOptions(remotes, receiveGas));
        StockToken(token).setDelegate(DEAD);

        // 3. + 4. hookless v4 pool vs the quote, opened at the quote-denominated mcap, whole local share in one position
        uint256 localSupply = IERC20(token).balanceOf(address(this));
        bool tokenIs0 = uint160(token) < uint160(q.token);
        PoolKey memory key = PoolKey({
            currency0: Currency.wrap(tokenIs0 ? token : q.token),
            currency1: Currency.wrap(tokenIs0 ? q.token : token),
            fee: p.tradingFee,
            tickSpacing: TICK_SPACING,
            hooks: IHooks(address(0))
        });
        LaunchMath.Opening memory o = LaunchMath.compute(tokenIs0, localSupply, q.openingMcap * localSupply / MCAP_SUPPLY, TICK_SPACING);
        poolManager.initialize(key, o.sqrtPriceX96);
        uint256 positionId = _mintPosition(key, token, tokenIs0, o, localSupply);

        uint256 dust = IERC20(token).balanceOf(address(this));
        if (dust != 0) StockToken(token).burn(dust);

        _launches[token] = Launch({
            token: token,
            creator: creator,
            feeRecipient: creator,
            positionId: positionId,
            localSupply: localSupply,
            launchedAt: uint64(block.timestamp),
            key: key
        });
        tokens.push(token);
        emit TokenLaunched(token, creator, p.quote, q.token, q.openingMcap, paidHere);
    }

    function _remotes(uint32[] calldata planEids) internal view returns (uint32[] memory out) {
        out = new uint32[](planEids.length);
        uint256 n;
        for (uint256 i; i < planEids.length; ++i) if (planEids[i] != localEid) out[n++] = planEids[i];
        assembly { mstore(out, n) }
    }

    function _enforcedOptions(uint32[] memory remotes, uint128 gas) internal view returns (EnforcedOptionParam[] memory out) {
        // type-3 options with one executor lzReceive option: 0x0003 | worker 1 | size 17 | type 1 | uint128 gas
        bytes memory opt = abi.encodePacked(uint16(3), uint8(1), uint16(17), uint8(1), gas);
        // Solana deliveries also carry lamports for the receiver's token account: size 33 | type 1 | gas | value
        bytes memory solOpt = abi.encodePacked(uint16(3), uint8(1), uint16(33), uint8(1), gas, SOLANA_RECEIVE_VALUE);
        uint256 k;
        out = new EnforcedOptionParam[](remotes.length * 2);
        for (uint256 i; i < remotes.length; ++i) {
            if (remotes[i] == localEid) continue;
            bytes memory o = remotes[i] == SOLANA_EID ? solOpt : opt;
            out[k++] = EnforcedOptionParam(remotes[i], MSG_SEND, o);
            out[k++] = EnforcedOptionParam(remotes[i], MSG_SEND_AND_CALL, o);
        }
        assembly { mstore(out, k) }
    }

    // ----------------------------- fees -----------------------------

    /// @notice Collect a launch's LP fees on this chain. Anyone may call. Token-side fees are sold for the quote;
    /// 20% of the quote goes to the treasury and 80% to the fee recipient.
    function collectFees(address token) external nonReentrant returns (uint256 toCreator, uint256 toPlatform) {
        Launch storage l = _launches[token];
        if (l.token == address(0)) revert UnknownToken();

        address qt = _quoteOf(l);
        uint256 quoteBefore = _bal(qt);
        uint256 tokenBefore = IERC20(token).balanceOf(address(this));
        _take(l, 0, address(this));
        uint256 quoteFees = _bal(qt) - quoteBefore;
        uint256 tokenFees = IERC20(token).balanceOf(address(this)) - tokenBefore;

        uint256 soldFor;
        if (tokenFees != 0) soldFor = _swap(l, false, tokenFees, 0, address(this));
        uint256 total = quoteFees + soldFor;
        toPlatform = total * PLATFORM_CUT_BPS / 10_000;
        toCreator = total - toPlatform;
        if (toPlatform != 0) _payCur(qt, treasury, toPlatform);
        if (toCreator != 0) _payCur(qt, l.feeRecipient, toCreator);
        emit FeesCollected(token, quoteFees, tokenFees, soldFor, toCreator, toPlatform);
    }

    // ----------------------------- v4 -----------------------------

    /// @dev buy: quote -> coin (the quote is already held by this contract); sell: coin -> quote. Output to `to`.
    function _swap(Launch storage l, bool buy, uint256 amountIn, uint256 minOut, address to) internal returns (uint256 out) {
        bool tokenIs0 = Currency.unwrap(l.key.currency0) == l.token;
        out = abi.decode(poolManager.unlock(abi.encode(buy != tokenIs0, l.key, amountIn, minOut, to)), (uint256));
        emit Swap(l.token, to, buy, amountIn, out);
    }

    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        (bool zeroForOne, PoolKey memory key, uint256 amountIn, uint256 minOut, address recipient) =
            abi.decode(data, (bool, PoolKey, uint256, uint256, address));

        BalanceDelta d = poolManager.swap(
            key,
            SwapParams({
                zeroForOne: zeroForOne,
                amountSpecified: -int256(amountIn),
                sqrtPriceLimitX96: zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1
            }),
            ""
        );
        uint256 paid = uint256(uint128(-(zeroForOne ? d.amount0() : d.amount1())));
        uint256 out = uint256(uint128(zeroForOne ? d.amount1() : d.amount0()));
        if (out < minOut) revert SlippageExceeded();

        Currency cin = zeroForOne ? key.currency0 : key.currency1;
        Currency cout = zeroForOne ? key.currency1 : key.currency0;
        if (cin.isAddressZero()) {
            poolManager.settle{value: paid}();
        } else {
            poolManager.sync(cin);
            IERC20(Currency.unwrap(cin)).safeTransfer(address(poolManager), paid);
            poolManager.settle();
        }
        poolManager.take(cout, recipient, out);
        // price limit hit: the unspent input goes back to the recipient (the treasury for an opening buy)
        if (paid < amountIn) _payCur(Currency.unwrap(cin), recipient == DEAD ? treasury : recipient, amountIn - paid);
        return abi.encode(out);
    }

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

    function _args(address creator, LaunchParams calldata p) internal pure returns (bytes memory) {
        return abi.encode(p.name, p.symbol, p.metadata, creator, p.tradingFee, p.openingMcapUsd, p.plan, p.quote, p.solanaPeer);
    }

    function _mintPosition(PoolKey memory key, address token, bool tokenIs0, LaunchMath.Opening memory o, uint256 amount)
        internal
        returns (uint256 positionId)
    {
        IERC20(token).forceApprove(address(permit2), amount);
        permit2.approve(token, address(positionManager), uint160(amount), uint48(block.timestamp + 1 hours));
        positionId = positionManager.nextTokenId();
        bytes memory actions = abi.encodePacked(uint8(Actions.MINT_POSITION), uint8(Actions.SETTLE_PAIR));
        bytes[] memory params = new bytes[](2);
        params[0] = abi.encode(
            key, o.tickLower, o.tickUpper, uint256(o.liquidity), tokenIs0 ? uint128(amount) : uint128(0), tokenIs0 ? uint128(0) : uint128(amount), address(this), bytes("")
        );
        params[1] = abi.encode(key.currency0, key.currency1);
        positionManager.modifyLiquidities(abi.encode(actions, params), block.timestamp);
    }

    /// @dev decrease `liq` of the launch's position (0 = fees only) and send both currencies to `to`
    function _take(Launch storage l, uint256 liq, address to) internal {
        bytes memory actions = abi.encodePacked(uint8(Actions.DECREASE_LIQUIDITY), uint8(Actions.TAKE_PAIR));
        bytes[] memory params = new bytes[](2);
        params[0] = abi.encode(l.positionId, liq, uint128(0), uint128(0), bytes(""));
        params[1] = abi.encode(l.key.currency0, l.key.currency1, to);
        positionManager.modifyLiquidities(abi.encode(actions, params), block.timestamp);
    }

    function _salt(address creator, bytes32 salt) internal pure returns (bytes32) {
        return keccak256(abi.encode(creator, salt));
    }

    /// @dev the coin's quote on this chain: the pool's other currency (NATIVE for a native-paired coin)
    function _quoteOf(Launch storage l) internal view returns (address) {
        address c0 = Currency.unwrap(l.key.currency0);
        return c0 == l.token ? Currency.unwrap(l.key.currency1) : c0;
    }

    function _bal(address cur) internal view returns (uint256) {
        return cur == NATIVE ? address(this).balance : IERC20(cur).balanceOf(address(this));
    }

    function _pay(address to, uint256 amount) internal {
        if (amount == 0) return;
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert NativeTransferFailed();
    }

    /// @dev push `amount` of `cur` (NATIVE or an ERC20) to `to`
    function _payCur(address cur, address to, uint256 amount) internal {
        if (amount == 0) return;
        if (cur == NATIVE) _pay(to, amount);
        else IERC20(cur).safeTransfer(to, amount);
    }

    /// @dev native from fee collection, swaps and PoolManager refunds
    receive() external payable {}
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
    "v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/src/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "forge-std/=lib/forge-std/src/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "@layerzerolabs/=node_modules/@layerzerolabs/",
    "solidity-bytes-utils/=node_modules/solidity-bytes-utils/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-periphery/lib/v4-core/node_modules/hardhat/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.