Skip to content
Verified contractPartialMIT

LockstepFactory

Address0x2ddc710c4f81dad5121e2e98b6f0b17475acedd5
Balance

0 ETH

 

Transactions

4

 

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,287,218
Creation transaction
0x04c7eb8221…0bcd05aa3d
Main copy (most transactions)
0xaf016cc2…98bdf719

95 files

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

src/LockstepFactory.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 {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.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 {Ownable2Step, Ownable} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.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 {LockstepToken} from "./LockstepToken.sol";
import {LockstepDeployer} from "./LockstepDeployer.sol";
import {LaunchMath} from "./libraries/LaunchMath.sol";

/**
 * @title LockstepFactory
 * @notice Launch a coin once; it goes live on every chain of its plan at the same address and the same dollar price.
 *
 * 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
 * LockstepDeployer (constructor arg = this factory) is likewise at one address everywhere and holds the token code.
 *
 * 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`, covered by
 * that one fee). On each chain the factory:
 *   1. has the deployer CREATE2-deploy the LockstepToken (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 native coin at the launch's global opening market cap in USD,
 *      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 native, 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 LockstepFactory is Ownable2Step, ReentrancyGuard, IUnlockCallback {
    using SafeERC20 for IERC20;
    using PoolIdLibrary for PoolKey;

    /// @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 = 5_000;
    uint128 public constant MIN_RECEIVE_GAS = 60_000;
    uint128 public constant MAX_RECEIVE_GAS = 1_000_000;
    uint16 internal constant MSG_SEND = 1;
    uint16 internal constant MSG_SEND_AND_CALL = 2;
    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 {
        LockstepDeployer 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 lockstep runs on, this one included
        Route[] routes;
        address treasury;
        address launcher;
        /// @dev USD price of the native coin, 8 decimals
        uint256 nativeUsdE8;
        uint256 launchFee;
        uint128 receiveGas;
    }

    struct LaunchParams {
        string name;
        string symbol;
        LockstepToken.Metadata metadata;
        LockstepToken.Plan plan;
        /// @dev v4 pips, 3000..50000 (0.3%..5%)
        uint24 tradingFee;
        /// @dev must be OPENING_MCAP_USD (5000): 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;
        uint256 openingMcapWei;
        uint64 launchedAt;
        PoolKey key;
    }

    LockstepDeployer 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 nativeUsdE8;
    uint256 public launchFee;
    uint128 public receiveGas;
    bool public launchEnabled;
    bool public initialized;

    address[] public tokens;
    mapping(address token => Launch) internal _launches;
    /// @dev native owed to a recipient whose push failed
    mapping(address => uint256) public owed;

    event Initialized(uint32 localEid, address lzEndpoint, address treasury, address launcher);
    event RouteAdded(uint256 chainId, uint32 eid, uint64 confirmations);
    event TokenLaunched(
        address indexed token,
        address indexed creator,
        PoolId poolId,
        uint256 positionId,
        uint256 localSupply,
        uint256 openingMcapUsd,
        uint256 openingMcapWei,
        uint24 tradingFee,
        bool paidHere
    );
    event DevBuy(address indexed token, address indexed buyer, uint256 nativeIn, uint256 tokensOut);
    event FeesCollected(address indexed token, uint256 nativeFees, uint256 tokenFees, uint256 tokenFeesSoldFor, uint256 toCreator, uint256 toPlatform);
    event FeeRecipientSet(address indexed token, address recipient);
    event NativeUsdSet(uint256 nativeUsdE8);
    event LaunchFeeSet(uint256 fee);
    event TreasurySet(address treasury);
    event LauncherSet(address launcher);
    event LaunchEnabledSet(bool enabled);
    event ReceiveGasSet(uint128 gas);
    event Owed(address indexed to, uint256 amount);
    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 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 (
            address(c.deployer) == address(0) || address(c.poolManager) == address(0) || address(c.positionManager) == address(0)
                || address(c.permit2) == address(0) || c.lzEndpoint == address(0) || c.sendLib == address(0)
                || c.receiveLib == address(0) || c.executor == address(0) || 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;
        nativeUsdE8 = c.nativeUsdE8;
        launchFee = c.launchFee;
        receiveGas = c.receiveGas;
        launchEnabled = true;
        initialized = true;
        emit Initialized(localEid, c.lzEndpoint, c.treasury, c.launcher);
    }

    /// @notice Add a chain for FUTURE launches. Existing routes can never be changed, and 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 || routeOf[r.eid].eid != 0 || r.dvnMask == 0) revert BadRoute();
        routeOf[r.eid] = r;
        eids.push(r.eid);
        emit RouteAdded(r.chainId, r.eid, r.confirmations);
    }

    // ----------------------------- 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];
    }

    function launched(address token) external view returns (bool) {
        return _launches[token].token != address(0);
    }

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

    /// @notice Global opening market cap in native wei for a USD figure, at the current native price.
    function mcapWei(uint256 mcapUsd) public view returns (uint256) {
        return mcapUsd * 1e18 * 1e8 / nativeUsdE8;
    }

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

    /// @notice Native coin price used to open pools at a USD market cap. The launcher key keeps it fresh.
    function setNativeUsd(uint256 nativeUsdE8_) external onlyLauncher {
        if (nativeUsdE8_ == 0) revert BadMcap();
        nativeUsdE8 = nativeUsdE8_;
        emit NativeUsdSet(nativeUsdE8_);
    }

    function setLaunchFee(uint256 fee) external onlyOwner {
        launchFee = fee;
        emit LaunchFeeSet(fee);
    }

    function setTreasury(address treasury_) external onlyOwner {
        if (treasury_ == address(0)) revert ZeroAddress();
        treasury = treasury_;
        emit TreasurySet(treasury_);
    }

    function setLauncher(address launcher_) external onlyOwner {
        if (launcher_ == address(0)) revert ZeroAddress();
        launcher = launcher_;
        emit LauncherSet(launcher_);
    }

    function setLaunchEnabled(bool enabled) external onlyOwner {
        launchEnabled = enabled;
        emit LaunchEnabledSet(enabled);
    }

    /// @notice Gas floor for FUTURE launches' lzReceive.
    function setReceiveGas(uint128 gas) external onlyOwner {
        if (gas < MIN_RECEIVE_GAS || gas > MAX_RECEIVE_GAS) revert BadGas();
        receiveGas = gas;
        emit ReceiveGasSet(gas);
    }

    /// @notice The one route setting that stays adjustable on a live token: its lzReceive gas floor, so a chain that
    /// reprices gas cannot strand bridging. Capped; it can carry no value and nothing else.
    function setTokenReceiveGas(address token, uint128 gas) external onlyOwner {
        if (_launches[token].token == address(0)) revert UnknownToken();
        if (gas < MIN_RECEIVE_GAS || gas > MAX_RECEIVE_GAS) revert BadGas();
        LockstepToken(token).setEnforcedOptions(_enforcedOptions(LockstepToken(token).plan().eids, gas));
    }

    /// @notice Pull 100% of every launch's liquidity on THIS chain (tokens, native 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 + optional dev buy (native in).
    /// The platform launcher then submits the same params on every other chain of the plan.
    function launch(LaunchParams calldata p, 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 = msg.value - launchFee;
        if (devBuy != 0) devBuyTokens = _buy(token, devBuy, devBuyMinTokens, msg.sender);
    }

    /// @notice The launcher replays a launch on the plan's other chains. Any value sent is an opening buy burned to 0xdead
    /// (it gives indexers a first swap); the creator paid once, on their chain.
    function launchFor(address creator, LaunchParams calldata p)
        external
        payable
        nonReentrant
        onlyLauncher
        returns (address token)
    {
        token = _launch(creator, p, false);
        if (msg.value != 0) _buy(token, msg.value, 0, DEAD);
    }

    /// @notice Buy the coin on this chain with native, straight through its pool.
    function buy(address token, uint256 minOut, address to) external payable nonReentrant returns (uint256 out) {
        if (_launches[token].token == address(0)) revert UnknownToken();
        out = _buy(token, msg.value, minOut, to);
    }

    /// @notice Sell the coin on this chain for native, straight through its pool (approve this factory first).
    function sell(address token, uint256 amountIn, uint256 minOut, address to) external nonReentrant returns (uint256 out) {
        Launch storage l = _launches[token];
        if (l.token == address(0)) revert UnknownToken();
        IERC20(token).safeTransferFrom(msg.sender, address(this), amountIn);
        out = abi.decode(poolManager.unlock(abi.encode(false, l.key, amountIn, minOut, to)), (uint256));
    }

    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();
        LockstepToken.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
        LockstepToken(token).setEnforcedOptions(_enforcedOptions(remotes, receiveGas));
        LockstepToken(token).setDelegate(DEAD);

        // 3. + 4. hookless v4 pool vs native, opened at the global USD mcap, whole local share in one locked position
        uint256 localSupply = IERC20(token).balanceOf(address(this));
        uint256 mcap = mcapWei(p.openingMcapUsd);
        PoolKey memory key = PoolKey({
            currency0: Currency.wrap(NATIVE),
            currency1: Currency.wrap(token),
            fee: p.tradingFee,
            tickSpacing: TICK_SPACING,
            hooks: IHooks(address(0))
        });
        LaunchMath.Opening memory o = LaunchMath.compute(false, localSupply, mcap * localSupply / MCAP_SUPPLY, TICK_SPACING);
        poolManager.initialize(key, o.sqrtPriceX96);
        uint256 positionId = _mintPosition(key, token, o, localSupply);

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

        _launches[token] = Launch({
            token: token,
            creator: creator,
            feeRecipient: creator,
            positionId: positionId,
            localSupply: localSupply,
            openingMcapWei: mcap,
            launchedAt: uint64(block.timestamp),
            key: key
        });
        tokens.push(token);
        emit TokenLaunched(token, creator, key.toId(), positionId, localSupply, p.openingMcapUsd, mcap, p.tradingFee, 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);
        uint256 k;
        out = new EnforcedOptionParam[](remotes.length * 2);
        for (uint256 i; i < remotes.length; ++i) {
            if (remotes[i] == localEid) continue;
            out[k++] = EnforcedOptionParam(remotes[i], MSG_SEND, opt);
            out[k++] = EnforcedOptionParam(remotes[i], MSG_SEND_AND_CALL, opt);
        }
        assembly { mstore(out, k) }
    }

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

    /// @notice Collect a launch's LP fees on this chain. Anyone may call. Token-side fees are sold for native;
    /// 20% of the native 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();

        uint256 nativeBefore = address(this).balance;
        uint256 tokenBefore = IERC20(token).balanceOf(address(this));
        _take(l, 0, address(this));
        uint256 nativeFees = address(this).balance - nativeBefore;
        uint256 tokenFees = IERC20(token).balanceOf(address(this)) - tokenBefore;

        uint256 soldFor;
        if (tokenFees != 0) {
            soldFor = abi.decode(poolManager.unlock(abi.encode(false, l.key, tokenFees, uint256(0), address(this))), (uint256));
        }
        uint256 total = nativeFees + soldFor;
        toPlatform = total * PLATFORM_CUT_BPS / 10_000;
        toCreator = total - toPlatform;
        if (toPlatform != 0) _payOrOwe(treasury, toPlatform);
        if (toCreator != 0) _payOrOwe(l.feeRecipient, toCreator);
        emit FeesCollected(token, nativeFees, tokenFees, soldFor, toCreator, toPlatform);
    }

    /// @notice Withdraw native that could not be pushed to you.
    function claimOwed() external nonReentrant {
        uint256 a = owed[msg.sender];
        owed[msg.sender] = 0;
        _pay(msg.sender, a);
    }

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

    function _buy(address token, uint256 amountIn, uint256 minOut, address to) internal returns (uint256 out) {
        out = abi.decode(poolManager.unlock(abi.encode(true, _launches[token].key, amountIn, minOut, to)), (uint256));
        if (to != DEAD) emit DevBuy(token, to, amountIn, out);
    }

    /// @dev zeroForOne = native -> token (buy, native settled from our balance); else token -> native (fee sale)
    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();

        if (zeroForOne) {
            poolManager.settle{value: paid}();
            poolManager.take(key.currency1, recipient, out);
            if (paid < amountIn) _pay(recipient == DEAD ? treasury : recipient, amountIn - paid); // price limit hit
        } else {
            poolManager.sync(key.currency1);
            IERC20(Currency.unwrap(key.currency1)).safeTransfer(address(poolManager), paid);
            poolManager.settle();
            poolManager.take(key.currency0, recipient, out);
        }
        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);
    }

    function _mintPosition(PoolKey memory key, address token, 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), 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));
    }

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

    function _payOrOwe(address to, uint256 amount) internal {
        (bool ok,) = to.call{value: amount, gas: 50_000}("");
        if (!ok) {
            owed[to] += amount;
            emit Owed(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/",
    "@layerzerolabs/=node_modules/@layerzerolabs/",
    "solidity-bytes-utils/=node_modules/solidity-bytes-utils/",
    "@openzeppelin/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.