Skip to content
Verified contractExact

LaunchTokenSafe

Address0x318f96bbfd417e795ee530ec9677a4cea320c8cd
Balance

0 ETH

 

Transactions

989

 

Compiler

solc 0.8.24

 

Same code

80 more contracts

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 100 runs
EVM version
shanghai
Via IR
yes
License
Not stated
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,704,272
Creation transaction
0x8136ac8a09…b3061f2c72

project/contracts/LaunchTokenSafe.sol

pragma solidity ^0.8.24;

interface IERC20Reward {
    function balanceOf(address account) external view returns (uint256);
    function transfer(address recipient, uint256 amount) external returns (bool);
}

library FullPrecisionRewardMath {
    error MulDivOverflow();

    function mulDiv(uint256 multiplicand, uint256 multiplier, uint256 denominator)
        internal
        pure
        returns (uint256 result)
    {
        unchecked {
            uint256 productLow;
            uint256 productHigh;
            assembly ("memory-safe") {
                let productMod := mulmod(multiplicand, multiplier, not(0))
                productLow := mul(multiplicand, multiplier)
                productHigh := sub(sub(productMod, productLow), lt(productMod, productLow))
            }

            if (productHigh == 0) return productLow / denominator;
            if (denominator <= productHigh) revert MulDivOverflow();

            uint256 remainder;
            assembly ("memory-safe") {
                remainder := mulmod(multiplicand, multiplier, denominator)
                productHigh := sub(productHigh, gt(remainder, productLow))
                productLow := sub(productLow, remainder)
            }

            uint256 powerOfTwo = denominator & (0 - denominator);
            assembly ("memory-safe") {
                denominator := div(denominator, powerOfTwo)
                productLow := div(productLow, powerOfTwo)
                powerOfTwo := add(div(sub(0, powerOfTwo), powerOfTwo), 1)
            }
            productLow |= productHigh * powerOfTwo;

            uint256 inverse = (3 * denominator) ^ 2;
            inverse *= 2 - denominator * inverse;
            inverse *= 2 - denominator * inverse;
            inverse *= 2 - denominator * inverse;
            inverse *= 2 - denominator * inverse;
            inverse *= 2 - denominator * inverse;
            inverse *= 2 - denominator * inverse;
            result = productLow * inverse;
        }
    }
}

contract LaunchTokenSafe {
    uint256 private constant REWARD_SCALE = 1e30;

    // The factory that CREATE2-deployed this token, captured at deploy. initialize() additionally requires
    // msg.sender == deployer, so authorization never rests solely on deploy+init being atomic.
    address public immutable deployer;

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

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

    address public launcher;
    address public pairedStock;
    address public rewardToken;
    address public feeManager;
    address public poolManager;
    bool public holdersShare;

    string public description;
    string public image;
    string public website;
    string public twitter;

    uint256 public rewardEligibleSupply;
    uint256 public accRewardPerShare;
    uint256 public rewardReserve;

    mapping(address => uint256) private _rewardDebt;
    mapping(address => uint256) private _pendingReward;
    mapping(address => bool) public excludedFromRewards;

    bool private _initialized;
    bool private _claiming;

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
    event RewardNotified(uint256 amount, uint256 eligibleSupply);
    event RewardClaimed(address indexed account, uint256 amount);

    error AlreadyInitialized();
    error Unauthorized();
    error InvalidAddress();
    error InsufficientBalance();
    error InsufficientAllowance();
    error NoEligibleSupply();
    error InvalidRewardFunding();
    error RewardTransferFailed();
    error ReentrantClaim();

    // Each launched token is its OWN standalone contract (deployed with CREATE2 by the factory, never a
    // proxy or clone). The factory deploys and initialize()s it in the same atomic launch() call, so there
    // is no window for anyone else to initialize it; initialize() then locks itself against a second call.
    constructor() {
        deployer = msg.sender;
    }

    function initialize(
        string calldata name_,
        string calldata symbol_,
        uint256 supply_,
        address launcher_,
        address feeManager_,
        address poolManager_,
        address pairedStock_,
        string calldata description_,
        string calldata image_,
        string calldata website_,
        string calldata twitter_,
        bool holdersShare_
    ) external {
        if (_initialized) revert AlreadyInitialized();
        if (msg.sender != deployer || msg.sender != feeManager_) revert Unauthorized();
        if (launcher_ == address(0) || feeManager_ == address(0) || poolManager_ == address(0) || pairedStock_ == address(0)) {
            revert InvalidAddress();
        }

        _initialized = true;
        name = name_;
        symbol = symbol_;
        launcher = launcher_;
        feeManager = feeManager_;
        poolManager = poolManager_;
        pairedStock = pairedStock_;
        rewardToken = pairedStock_;
        holdersShare = holdersShare_;
        description = description_;
        image = image_;
        website = website_;
        twitter = twitter_;

        excludedFromRewards[feeManager_] = true;
        excludedFromRewards[poolManager_] = true;

        totalSupply = supply_;
        balanceOf[feeManager_] = supply_;
        emit Transfer(address(0), feeManager_, supply_);
    }

    function meta() external view returns (string memory, string memory, string memory, string memory, address) {
        return (description, image, website, twitter, pairedStock);
    }

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

    function transfer(address recipient, uint256 value) external returns (bool) {
        _transfer(msg.sender, recipient, value);
        return true;
    }

    function transferFrom(address sender, address recipient, uint256 value) external returns (bool) {
        uint256 currentAllowance = allowance[sender][msg.sender];
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < value) revert InsufficientAllowance();
            unchecked {
                allowance[sender][msg.sender] = currentAllowance - value;
            }
            emit Approval(sender, msg.sender, allowance[sender][msg.sender]);
        }
        _transfer(sender, recipient, value);
        return true;
    }

    // Public self-burn: anyone can burn ONLY their own tokens. The fee manager uses it to burn the
    // token-side of collected fees (deflationary). No privileged party can touch another holder's
    // balance, so this is not an "owner can change balance" backdoor — it's a plain, permissionless burn.
    function burn(uint256 amount) external {
        uint256 balance = balanceOf[msg.sender];
        if (balance < amount) revert InsufficientBalance();

        bool excluded = excludedFromRewards[msg.sender];
        if (!excluded) _accrue(msg.sender);
        unchecked {
            balanceOf[msg.sender] = balance - amount;
            totalSupply -= amount;
        }
        if (!excluded) {
            rewardEligibleSupply -= amount;
            _rewardDebt[msg.sender] = FullPrecisionRewardMath.mulDiv(balanceOf[msg.sender], accRewardPerShare, REWARD_SCALE);
        }

        emit Transfer(msg.sender, address(0), amount);
    }

    function notifyRewardAmount(uint256 amount) external {
        if (msg.sender != feeManager) revert Unauthorized();
        if (!holdersShare || rewardEligibleSupply == 0) revert NoEligibleSupply();
        if (amount == 0) return;

        uint256 fundedBalance = IERC20Reward(rewardToken).balanceOf(address(this));
        if (fundedBalance < rewardReserve + amount) revert InvalidRewardFunding();

        rewardReserve += amount;
        accRewardPerShare += FullPrecisionRewardMath.mulDiv(amount, REWARD_SCALE, rewardEligibleSupply);
        emit RewardNotified(amount, rewardEligibleSupply);
    }

    function withdrawableRewardOf(address account) public view returns (uint256) {
        uint256 pending = _pendingReward[account];
        if (excludedFromRewards[account]) return pending;

        uint256 accumulated = FullPrecisionRewardMath.mulDiv(balanceOf[account], accRewardPerShare, REWARD_SCALE);
        uint256 debt = _rewardDebt[account];
        return accumulated > debt ? pending + accumulated - debt : pending;
    }

    function claimReward() external returns (uint256 amount) {
        if (_claiming) revert ReentrantClaim();
        _claiming = true;

        _accrue(msg.sender);
        amount = _pendingReward[msg.sender];
        if (amount != 0) {
            _pendingReward[msg.sender] = 0;
            rewardReserve -= amount;
            _safeRewardTransfer(msg.sender, amount);
            emit RewardClaimed(msg.sender, amount);
        }

        _claiming = false;
    }

    // Launcher-only push: sends each supplied holder their unclaimed reward in one call, so holders don't
    // have to claim individually. The launcher passes the holder list (the app already indexes it), which
    // keeps the token lean and lets big holder sets be paginated across calls. Each account only ever
    // receives its OWN accrued reward — the launcher can never redirect or over-pay anyone. The token-side
    // of fees is burned at collect time (LaunchpadFactorySafe.harvest), so harvesting before a distribute
    // burns as usual. Any holder can always fall back to the permissionless claimReward().
    function distribute(address[] calldata accounts) external {
        if (msg.sender != launcher) revert Unauthorized();
        if (_claiming) revert ReentrantClaim();
        _claiming = true;

        for (uint256 i; i < accounts.length; ++i) {
            address account = accounts[i];
            if (excludedFromRewards[account]) continue;
            _accrue(account);
            uint256 amount = _pendingReward[account];
            if (amount == 0) continue;

            _pendingReward[account] = 0;
            rewardReserve -= amount;
            _safeRewardTransfer(account, amount);
            emit RewardClaimed(account, amount);
        }

        _claiming = false;
    }

    function _transfer(address sender, address recipient, uint256 value) internal {
        if (recipient == address(0)) revert InvalidAddress();
        uint256 senderBalance = balanceOf[sender];
        if (senderBalance < value) revert InsufficientBalance();

        _accrue(sender);
        if (recipient != sender) _accrue(recipient);

        if (recipient != sender) {
            unchecked {
                balanceOf[sender] = senderBalance - value;
                balanceOf[recipient] += value;
            }

            bool senderExcluded = excludedFromRewards[sender];
            bool recipientExcluded = excludedFromRewards[recipient];
            if (senderExcluded && !recipientExcluded) {
                rewardEligibleSupply += value;
            } else if (!senderExcluded && recipientExcluded) {
                rewardEligibleSupply -= value;
            }

            _rewardDebt[sender] = senderExcluded
                ? 0
                : FullPrecisionRewardMath.mulDiv(balanceOf[sender], accRewardPerShare, REWARD_SCALE);
            _rewardDebt[recipient] = recipientExcluded
                ? 0
                : FullPrecisionRewardMath.mulDiv(balanceOf[recipient], accRewardPerShare, REWARD_SCALE);
        }

        emit Transfer(sender, recipient, value);
    }

    function _accrue(address account) internal {
        if (excludedFromRewards[account]) {
            _rewardDebt[account] = 0;
            return;
        }

        uint256 accumulated = FullPrecisionRewardMath.mulDiv(balanceOf[account], accRewardPerShare, REWARD_SCALE);
        uint256 debt = _rewardDebt[account];
        if (accumulated > debt) _pendingReward[account] += accumulated - debt;
        _rewardDebt[account] = accumulated;
    }

    function _safeRewardTransfer(address recipient, uint256 amount) internal {
        (bool success, bytes memory returndata) = rewardToken.call(
            abi.encodeCall(IERC20Reward.transfer, (recipient, amount))
        );
        if (!success || (returndata.length != 0 && !abi.decode(returndata, (bool)))) revert RewardTransferFailed();
    }
}

project/contracts/LaunchpadFactorySafe.sol

pragma solidity ^0.8.24;

import {LaunchTokenSafe} from "./LaunchTokenSafe.sol";
import {LiquidityLockVault} from "./LiquidityLockVault.sol";

interface IERC20Safe {
    function balanceOf(address account) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function transfer(address recipient, uint256 amount) external returns (bool);
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}

interface IPermit2Safe {
    function approve(address token, address spender, uint160 amount, uint48 expiration) external;
}

interface IPositionManagerSafe {
    struct PoolKey {
        address currency0;
        address currency1;
        uint24 fee;
        int24 tickSpacing;
        address hooks;
    }

    function initializePool(PoolKey calldata key, uint160 sqrtPriceX96) external payable returns (int24 tick);
    function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;
    function nextTokenId() external view returns (uint256);
    function ownerOf(uint256 tokenId) external view returns (address);
    function permit2() external view returns (address);
    function poolManager() external view returns (address);
}

// The dev anti-snipe buy talks DIRECTLY to the v4 PoolManager (never a router, never user calldata):
// the factory unlocks, swaps the paired asset it just pulled from the dev into the fresh pool, and
// settles/takes within its own unlockCallback. All of this is typed and built internally.
interface IPoolManagerSafe {
    struct SwapParams {
        bool zeroForOne;
        int256 amountSpecified;
        uint160 sqrtPriceLimitX96;
    }

    function unlock(bytes calldata data) external returns (bytes memory);
    function swap(IPositionManagerSafe.PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
        external
        returns (int256);
    function sync(address currency) external;
    function settle() external payable returns (uint256);
    function take(address currency, address to, uint256 amount) external;
}

contract LaunchpadFactorySafe {
    uint24 public constant FEE = 10_000;
    int24 public constant TICK_SPACING = 200;
    int24 public constant RANGE_TICKS = 60_000;
    int24 public constant MIN_USABLE_TICK = -887_200;
    int24 public constant MAX_USABLE_TICK = 887_200;
    uint256 public constant PROTOCOL_BPS = 1_000;
    uint256 public constant KEEPER_BPS = 100;
    uint256 public constant BPS_DENOMINATOR = 10_000;
    uint256 public constant MAX_SEED_DUST_DIVISOR = 1_000_000;
    uint256 public constant MAX_DEV_BUYS = 5;
    uint256 public constant MAX_DEV_ALLOCATION_BPS = 2_000;
    uint160 internal constant MIN_SQRT_PRICE = 4_295_128_739;
    uint160 internal constant MAX_SQRT_PRICE = 1_461_446_703_485_210_103_287_273_052_203_988_822_378_723_970_342;

    address public immutable permit2;
    address public immutable positionManager;
    address public immutable poolManager;
    // keccak256 of the standalone token's creation code, snapshotted once at deploy so predict() can
    // resolve CREATE2 addresses without embedding a second copy of that code in the factory runtime.
    bytes32 public immutable tokenInitCodeHash;

    address public owner;
    address public pendingOwner;
    bool public paused;

    address[] public launches;
    address[] public pairTokens;

    mapping(address => address) public launcherOf;
    mapping(address => address) public vaultOf;
    mapping(address => uint256) public positionIdOf;
    mapping(address => bool) public pairAllowed;
    mapping(address => uint256) private _pairIndex;

    uint256 private _entered = 1;

    // Swap context for the one dev buy that runs inside launch(). It exists ONLY between the
    // poolManager.unlock() call and its callback, and is deleted immediately after — there is no
    // standing "accept a buy" mode. The buy is a launch() parameter, so it can fire exactly once per
    // token and can never be re-triggered (launch() reverts on the token's create2 address collision).
    struct SwapContext {
        bool active;
        bool zeroForOne;
        address currency0;
        address currency1;
        address paired;
        address token;
        uint256 amountIn;
    }

    SwapContext private _swap;

    struct Params {
        string name;
        string symbol;
        uint256 supply;
        address pairedStock;
        bytes32 salt;
        string description;
        string image;
        string website;
        string twitter;
        bool holdersShare;
        uint160 sqrtPriceX96;
        int24 tickLower;
        int24 tickUpper;
        uint128 liquidity;
        // Optional creator allocation, in basis points of supply (0 = give it all to liquidity), capped at
        // MAX_DEV_ALLOCATION_BPS. This share is sent to the launcher; the rest is seeded and locked.
        uint256 devAllocationBps;
        // Optional atomic anti-snipe bundle: up to MAX_DEV_BUYS (recipient, paired amount) pairs, each
        // bought in-transaction right after the seed. Empty arrays = no dev buy.
        uint256[] devBuyAmounts;
        address[] devBuyRecipients;
    }

    event Launched(
        address indexed token,
        address indexed launcher,
        address indexed pairedStock,
        address vault,
        uint256 positionId,
        string name,
        string symbol
    );
    event DevBought(address indexed token, address indexed recipient, uint256 pairedSpent, uint256 tokensBought);
    event Harvested(
        address indexed token,
        address indexed keeper,
        uint256 userCut,
        uint256 protocolCut,
        uint256 keeperCut,
        uint256 burnt
    );
    event PairAdded(address indexed token);
    event PairRemoved(address indexed token);
    event PauseChanged(bool paused);
    event OwnershipTransferStarted(address indexed owner, address indexed pendingOwner);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    error Unauthorized();
    error ReentrantCall();
    error LaunchesPaused();
    error InvalidInfrastructure();
    error InvalidPair();
    error InvalidMetadata();
    error InvalidSupply();
    error InvalidRange();
    error InvalidPrice();
    error InvalidLiquidity();
    error DeploymentFailed();
    error InvalidPosition();
    error ExcessSeedDust();
    error UnknownLaunch();
    error TokenCallFailed();
    error InvalidDevBuy();
    error InvalidDevAllocation();
    error NoDevBuyMade();

    modifier onlyOwner() {
        if (msg.sender != owner) revert Unauthorized();
        _;
    }

    modifier nonReentrant() {
        if (_entered != 1) revert ReentrantCall();
        _entered = 2;
        _;
        _entered = 1;
    }

    constructor(address permit2_, address positionManager_, address poolManager_, address[] memory initialPairTokens) {
        if (
            permit2_ == address(0) || positionManager_ == address(0) || poolManager_ == address(0)
                || permit2_.code.length == 0 || positionManager_.code.length == 0 || poolManager_.code.length == 0
        ) revert InvalidInfrastructure();

        try IPositionManagerSafe(positionManager_).permit2() returns (address configuredPermit2) {
            if (configuredPermit2 != permit2_) revert InvalidInfrastructure();
        } catch {
            revert InvalidInfrastructure();
        }
        try IPositionManagerSafe(positionManager_).poolManager() returns (address configuredPoolManager) {
            if (configuredPoolManager != poolManager_) revert InvalidInfrastructure();
        } catch {
            revert InvalidInfrastructure();
        }

        permit2 = permit2_;
        positionManager = positionManager_;
        poolManager = poolManager_;
        owner = msg.sender;
        tokenInitCodeHash = keccak256(type(LaunchTokenSafe).creationCode);
        emit OwnershipTransferred(address(0), msg.sender);

        for (uint256 i; i < initialPairTokens.length; ++i) {
            if (!pairAllowed[initialPairTokens[i]]) _addPairToken(initialPairTokens[i]);
        }
    }

    function predict(address launcher, bytes32 userSalt) public view returns (address) {
        bytes32 deploymentSalt = _deploymentSalt(launcher, userSalt);
        return address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), deploymentSalt, tokenInitCodeHash)))));
    }

    function launch(Params calldata params) external nonReentrant returns (address token) {
        if (paused) revert LaunchesPaused();
        _validateParams(params);

        token = _deployToken(_deploymentSalt(msg.sender, params.salt));
        LaunchTokenSafe(token).initialize(
            params.name,
            params.symbol,
            params.supply,
            msg.sender,
            address(this),
            poolManager,
            params.pairedStock,
            params.description,
            params.image,
            params.website,
            params.twitter,
            params.holdersShare
        );

        bool tokenIsCurrency0 = uint160(token) < uint160(params.pairedStock);
        address currency0 = tokenIsCurrency0 ? token : params.pairedStock;
        address currency1 = tokenIsCurrency0 ? params.pairedStock : token;
        IPositionManagerSafe.PoolKey memory key = IPositionManagerSafe.PoolKey({
            currency0: currency0,
            currency1: currency1,
            fee: FEE,
            tickSpacing: TICK_SPACING,
            hooks: address(0)
        });

        int24 initializedTick = IPositionManagerSafe(positionManager).initializePool(key, params.sqrtPriceX96);
        if (initializedTick == type(int24).max) revert InvalidPrice();
        if (tokenIsCurrency0) {
            if (initializedTick > params.tickLower) revert InvalidRange();
        } else if (initializedTick < params.tickUpper) {
            revert InvalidRange();
        }

        uint256 positionId = IPositionManagerSafe(positionManager).nextTokenId();
        if (positionId == 0) revert InvalidPosition();
        LiquidityLockVault vault = new LiquidityLockVault{salt: keccak256(abi.encode(token, positionId))}(
            address(this), positionManager, positionId, currency0, currency1
        );

        _forceApprove(token, permit2, params.supply);
        IPermit2Safe(permit2).approve(token, positionManager, uint160(params.supply), uint48(block.timestamp + 300));

        uint256 devAllocation = (params.supply * params.devAllocationBps) / BPS_DENOMINATOR;
        uint256 seedAmount = params.supply - devAllocation;

        bytes[] memory actionParams = new bytes[](2);
        uint128 amount0Max = tokenIsCurrency0 ? uint128(seedAmount) : 0;
        uint128 amount1Max = tokenIsCurrency0 ? 0 : uint128(seedAmount);
        actionParams[0] = abi.encode(
            key,
            params.tickLower,
            params.tickUpper,
            uint256(params.liquidity),
            amount0Max,
            amount1Max,
            address(vault),
            bytes("")
        );
        actionParams[1] = abi.encode(currency0, currency1);

        IPositionManagerSafe(positionManager).modifyLiquidities(
            abi.encode(hex"020d", actionParams),
            block.timestamp + 300
        );

        IPermit2Safe(permit2).approve(token, positionManager, 0, 0);
        _forceApprove(token, permit2, 0);

        if (!vault.received() || IPositionManagerSafe(positionManager).ownerOf(positionId) != address(vault)) {
            revert InvalidPosition();
        }

        if (devAllocation != 0) _safeTransfer(token, msg.sender, devAllocation);

        uint256 leftover = LaunchTokenSafe(token).balanceOf(address(this));
        if (leftover > (params.supply / MAX_SEED_DUST_DIVISOR) + 1) revert ExcessSeedDust();
        if (leftover != 0) LaunchTokenSafe(token).burn(leftover);

        uint256 buyCount = params.devBuyRecipients.length;
        if (buyCount != 0) {
            if (buyCount > MAX_DEV_BUYS || params.devBuyAmounts.length != buyCount) revert InvalidDevBuy();
            for (uint256 i; i < buyCount; ++i) {
                _devBuy(token, params.pairedStock, tokenIsCurrency0, currency0, currency1, params.devBuyRecipients[i], params.devBuyAmounts[i]);
            }
        }

        launches.push(token);
        launcherOf[token] = msg.sender;
        vaultOf[token] = address(vault);
        positionIdOf[token] = positionId;

        emit Launched(token, msg.sender, params.pairedStock, address(vault), positionId, params.name, params.symbol);
    }

    // One anti-snipe buy in the bundle, executed atomically in the same transaction as the seed so no
    // bot can insert between them. The factory pulls EXACTLY `amountIn` of the paired asset from the
    // launcher (msg.sender), swaps it into the pool it just created, sends every bought token to
    // `recipient`, and refunds any unspent paired to the launcher. It ends each buy holding zero of both
    // currencies — nothing lingers in the factory to be drained.
    function _devBuy(
        address token,
        address paired,
        bool tokenIsCurrency0,
        address currency0,
        address currency1,
        address recipient,
        uint256 amountIn
    ) internal {
        // recipient == address(this) would strand the bought tokens in the factory; amountIn is bounded to
        // int128 because it becomes a negative exact-input amountSpecified for the v4 swap.
        if (
            amountIn == 0 || amountIn > uint256(uint128(type(int128).max)) || recipient == address(0)
                || recipient == address(this)
        ) revert InvalidDevBuy();
        _safeTransferFrom(paired, msg.sender, address(this), amountIn);

        _swap = SwapContext({
            active: true,
            zeroForOne: !tokenIsCurrency0,
            currency0: currency0,
            currency1: currency1,
            paired: paired,
            token: token,
            amountIn: amountIn
        });

        // The callback returns the EXACT paired spent and token bought (from the swap's own balance
        // deltas) — never a balanceOf — so a stray paired/token balance donated to the factory cannot
        // skew the refund, the emitted amounts, or underflow-revert (brick) the launch.
        bytes memory result = IPoolManagerSafe(poolManager).unlock("");
        delete _swap;
        (uint256 spent, uint256 bought) = abi.decode(result, (uint256, uint256));

        if (bought == 0) revert NoDevBuyMade();
        _safeTransfer(token, recipient, bought);
        if (spent < amountIn) _safeTransfer(paired, msg.sender, amountIn - spent);

        emit DevBought(token, recipient, spent, bought);
    }

    // Called by the v4 PoolManager during _devBuy's unlock, and only then. The two guards below make it
    // impossible to reach in any other context: msg.sender must be the PoolManager, and a swap must be
    // in flight (_swap.active), which is only true for the few opcodes between unlock() and its return.
    function unlockCallback(bytes calldata) external returns (bytes memory) {
        if (msg.sender != poolManager) revert Unauthorized();
        SwapContext memory ctx = _swap;
        if (!ctx.active) revert Unauthorized();

        IPositionManagerSafe.PoolKey memory key = IPositionManagerSafe.PoolKey({
            currency0: ctx.currency0,
            currency1: ctx.currency1,
            fee: FEE,
            tickSpacing: TICK_SPACING,
            hooks: address(0)
        });
        IPoolManagerSafe.SwapParams memory sp = IPoolManagerSafe.SwapParams({
            zeroForOne: ctx.zeroForOne,
            amountSpecified: -int256(ctx.amountIn),
            sqrtPriceLimitX96: ctx.zeroForOne ? MIN_SQRT_PRICE + 1 : MAX_SQRT_PRICE - 1
        });

        int256 delta = IPoolManagerSafe(poolManager).swap(key, sp, "");
        int128 amount0 = int128(delta >> 128);
        int128 amount1 = int128(delta);

        int128 inputDelta = ctx.zeroForOne ? amount0 : amount1;
        int128 outputDelta = ctx.zeroForOne ? amount1 : amount0;

        uint256 spent;
        uint256 bought;
        if (inputDelta < 0) {
            spent = uint256(uint128(-inputDelta));
            IPoolManagerSafe(poolManager).sync(ctx.paired);
            _safeTransfer(ctx.paired, poolManager, spent);
            IPoolManagerSafe(poolManager).settle();
        }
        if (outputDelta > 0) {
            bought = uint256(uint128(outputDelta));
            IPoolManagerSafe(poolManager).take(ctx.token, address(this), bought);
        }

        return abi.encode(spent, bought);
    }

    function harvest(address token) external nonReentrant {
        address vault = vaultOf[token];
        if (vault == address(0)) revert UnknownLaunch();

        LaunchTokenSafe launchToken = LaunchTokenSafe(token);
        address paired = launchToken.pairedStock();
        uint256 pairedBefore = IERC20Safe(paired).balanceOf(address(this));
        uint256 tokenBefore = launchToken.balanceOf(address(this));

        LiquidityLockVault(vault).collect(address(this));

        uint256 tokenAfter = launchToken.balanceOf(address(this));
        uint256 tokenFees = tokenAfter - tokenBefore;
        if (tokenFees != 0) launchToken.burn(tokenFees);

        uint256 pairedFees = IERC20Safe(paired).balanceOf(address(this)) - pairedBefore;
        if (pairedFees == 0) {
            emit Harvested(token, msg.sender, 0, 0, 0, tokenFees);
            return;
        }

        // Plain arithmetic is safe here: pairedFees is a real fee balance (far below 2^128) and the BPS
        // multipliers are <= 10000, so the product cannot overflow — no full-precision mulDiv needed. This
        // also keeps the 512-bit library out of the factory runtime (only the token needs it).
        uint256 protocolCut = (pairedFees * PROTOCOL_BPS) / BPS_DENOMINATOR;
        uint256 keeperCut = (pairedFees * KEEPER_BPS) / BPS_DENOMINATOR;
        uint256 userCut = pairedFees - protocolCut - keeperCut;

        if (protocolCut != 0) _safeTransfer(paired, owner, protocolCut);
        if (keeperCut != 0) _safeTransfer(paired, msg.sender, keeperCut);

        if (launchToken.holdersShare() && launchToken.rewardEligibleSupply() != 0) {
            _safeTransfer(paired, token, userCut);
            launchToken.notifyRewardAmount(userCut);
        } else {
            _safeTransfer(paired, launcherOf[token], userCut);
        }

        emit Harvested(token, msg.sender, userCut, protocolCut, keeperCut, tokenFees);
    }

    // Owner-curated pair allowlist. OPERATING ASSUMPTION: only standard, fixed-behaviour ERC20s may be
    // added — never fee-on-transfer, rebasing, or hostile/upgradeable tokens. The contract trusts an
    // allowlisted pair to move exactly the amount it is told; a misbehaving pair can only grief its OWN
    // launches (revert harvest/launch), never reach another launch's locked LP or any user's funds.
    function addPairToken(address token) external onlyOwner {
        _addPairToken(token);
    }

    // Batch add: seed the allowlist with many pairs in one transaction. Owner-only, uses the exact same
    // per-token validation as addPairToken; already-allowed tokens are skipped (idempotent, so a re-run
    // is safe) but a genuinely invalid address (zero, non-contract, or non-ERC20) reverts the whole
    // batch. Only edits the pair allowlist — it cannot touch liquidity or any launched position.
    function addPairTokens(address[] calldata tokens) external onlyOwner {
        for (uint256 i; i < tokens.length; ++i) {
            if (!pairAllowed[tokens[i]]) _addPairToken(tokens[i]);
        }
    }

    function _addPairToken(address token) internal {
        if (token == address(0) || token.code.length == 0 || pairAllowed[token]) revert InvalidPair();
        (bool success, bytes memory data) = token.staticcall(abi.encodeCall(IERC20Safe.balanceOf, (address(this))));
        if (!success || data.length < 32) revert InvalidPair();

        pairAllowed[token] = true;
        pairTokens.push(token);
        _pairIndex[token] = pairTokens.length;
        emit PairAdded(token);
    }

    function removePairToken(address token) external onlyOwner {
        uint256 indexPlusOne = _pairIndex[token];
        if (!pairAllowed[token] || indexPlusOne == 0) revert InvalidPair();

        uint256 index = indexPlusOne - 1;
        uint256 lastIndex = pairTokens.length - 1;
        if (index != lastIndex) {
            address last = pairTokens[lastIndex];
            pairTokens[index] = last;
            _pairIndex[last] = index + 1;
        }
        pairTokens.pop();
        delete _pairIndex[token];
        pairAllowed[token] = false;
        emit PairRemoved(token);
    }

    function setPaused(bool paused_) external onlyOwner {
        paused = paused_;
        emit PauseChanged(paused_);
    }

    function transferOwnership(address newOwner) external onlyOwner {
        if (newOwner == address(0)) revert Unauthorized();
        pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner, newOwner);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert Unauthorized();
        address previousOwner = owner;
        owner = msg.sender;
        pendingOwner = address(0);
        emit OwnershipTransferred(previousOwner, msg.sender);
    }

    function launchesCount() external view returns (uint256) {
        return launches.length;
    }

    function pairTokensCount() external view returns (uint256) {
        return pairTokens.length;
    }

    function allLaunches() external view returns (address[] memory) {
        return launches;
    }

    function allPairTokens() external view returns (address[] memory) {
        return pairTokens;
    }

    function _validateParams(Params calldata params) internal view {
        if (!pairAllowed[params.pairedStock] || params.pairedStock.code.length == 0) revert InvalidPair();
        if (params.supply == 0 || params.supply > type(uint128).max) revert InvalidSupply();
        if (params.devAllocationBps > MAX_DEV_ALLOCATION_BPS) revert InvalidDevAllocation();
        if (params.sqrtPriceX96 == 0) revert InvalidPrice();
        if (params.liquidity == 0) revert InvalidLiquidity();
        if (
            params.tickLower < MIN_USABLE_TICK || params.tickUpper > MAX_USABLE_TICK
                || params.tickLower % TICK_SPACING != 0 || params.tickUpper % TICK_SPACING != 0
                || int256(params.tickUpper) - int256(params.tickLower) != int256(RANGE_TICKS)
        ) revert InvalidRange();

        bytes memory nameBytes = bytes(params.name);
        bytes memory symbolBytes = bytes(params.symbol);
        if (nameBytes.length == 0 || nameBytes.length > 64 || symbolBytes.length < 2 || symbolBytes.length > 11) {
            revert InvalidMetadata();
        }
        for (uint256 i; i < symbolBytes.length; ++i) {
            bytes1 character = symbolBytes[i];
            bool uppercase = character >= 0x41 && character <= 0x5a;
            bool number = character >= 0x30 && character <= 0x39;
            if (!uppercase && !number) revert InvalidMetadata();
        }
        if (
            bytes(params.description).length > 500 || bytes(params.image).length > 16_384
                || bytes(params.website).length > 256 || bytes(params.twitter).length > 256
        ) revert InvalidMetadata();
    }

    function _deploymentSalt(address launcher, bytes32 userSalt) internal pure returns (bytes32) {
        return keccak256(abi.encode(launcher, userSalt));
    }

    // Deploy a fresh, fully self-contained LaunchTokenSafe at a deterministic CREATE2 address. This is a
    // real standalone contract — its complete runtime lives at its own address, with no delegatecall and
    // no implementation to point at — so it is NOT a proxy and carries no proxy label on explorers. The
    // salt has no constructor args, so every launched token shares identical bytecode (verify one, all
    // match) and predict() can resolve the address before the pool parameters are known.
    function _deployToken(bytes32 salt) internal returns (address instance) {
        instance = address(new LaunchTokenSafe{salt: salt}());
        if (instance == address(0)) revert DeploymentFailed();
    }

    function _forceApprove(address token, address spender, uint256 amount) internal {
        (bool success, bytes memory returndata) = token.call(abi.encodeCall(IERC20Safe.approve, (spender, amount)));
        if (success && (returndata.length == 0 || abi.decode(returndata, (bool)))) return;

        (success, returndata) = token.call(abi.encodeCall(IERC20Safe.approve, (spender, 0)));
        if (!success || (returndata.length != 0 && !abi.decode(returndata, (bool)))) revert TokenCallFailed();
        (success, returndata) = token.call(abi.encodeCall(IERC20Safe.approve, (spender, amount)));
        if (!success || (returndata.length != 0 && !abi.decode(returndata, (bool)))) revert TokenCallFailed();
    }

    function _safeTransfer(address token, address recipient, uint256 amount) internal {
        (bool success, bytes memory returndata) = token.call(abi.encodeCall(IERC20Safe.transfer, (recipient, amount)));
        if (!success || (returndata.length != 0 && !abi.decode(returndata, (bool)))) revert TokenCallFailed();
    }

    function _safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        (bool success, bytes memory returndata) =
            token.call(abi.encodeCall(IERC20Safe.transferFrom, (from, to, amount)));
        if (!success || (returndata.length != 0 && !abi.decode(returndata, (bool)))) revert TokenCallFailed();
    }
}

project/contracts/LiquidityLockVault.sol

pragma solidity ^0.8.24;

interface ILockedPositionManager {
    function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;
    function ownerOf(uint256 tokenId) external view returns (address);
}

contract LiquidityLockVault {
    address public immutable factory;
    address public immutable positionManager;
    uint256 public immutable positionId;
    address public immutable currency0;
    address public immutable currency1;

    error Unauthorized();
    error InvalidPosition();

    constructor(
        address factory_,
        address positionManager_,
        uint256 positionId_,
        address currency0_,
        address currency1_
    ) {
        factory = factory_;
        positionManager = positionManager_;
        positionId = positionId_;
        currency0 = currency0_;
        currency1 = currency1_;
    }

    function received() public view returns (bool) {
        return ILockedPositionManager(positionManager).ownerOf(positionId) == address(this);
    }

    function collect(address recipient) external {
        if (msg.sender != factory) revert Unauthorized();
        if (!received() || recipient == address(0)) revert InvalidPosition();

        bytes[] memory params = new bytes[](2);
        params[0] = abi.encode(positionId, uint256(0), uint128(0), uint128(0), bytes(""));
        params[1] = abi.encode(currency0, currency1, recipient);

        ILockedPositionManager(positionManager).modifyLiquidities(
            abi.encode(hex"0111", params),
            block.timestamp + 300
        );
    }
}

project/test/LaunchpadFactorySafeTest.sol

pragma solidity ^0.8.24;

import {LaunchpadFactorySafe} from "../contracts/LaunchpadFactorySafe.sol";
import {LaunchTokenSafe} from "../contracts/LaunchTokenSafe.sol";
import {LiquidityLockVault} from "../contracts/LiquidityLockVault.sol";
import {MockERC20, MockPermit2, MockPoolManager, MockPositionManager, CallActor} from "./mocks/LaunchpadMocks.sol";

interface IOldLaunchpad {
    struct Params {
        string name;
        string symbol;
        uint256 supply;
        address pairedStock;
        uint256 seedAmount;
        bytes32 salt;
        string description;
        string image;
        string website;
        string twitter;
        bool holdersShare;
    }

    struct SeedBuys {
        address payAsset;
        uint256 totalPayIn;
        bytes preCommands;
        bytes[] preInputs;
        uint128[] amounts;
        address[] recipients;
    }

    function launch(Params calldata params, bytes calldata initCalldata, bytes calldata modifyCalldata, SeedBuys calldata buys)
        external
        payable
        returns (address token);
}

contract LaunchpadFactorySafeTest {
    uint256 private constant SUPPLY = 1_000_000 ether;
    uint256 private constant HOLDER_BALANCE = 100 ether;
    uint256 private constant PAIRED_FEE = 1_000_000_000;
    uint256 private constant TOKEN_FEE = 5 ether;

    MockERC20 private paired;
    MockPermit2 private permit2;
    MockPoolManager private poolManager;
    MockPositionManager private positionManager;
    LaunchpadFactorySafe private factory;
    CallActor private attacker;
    CallActor private keeper;
    CallActor private alice;
    CallActor private bob;

    function setUp() public {
        paired = new MockERC20("USD Coin", "USDC", 6);
        permit2 = new MockPermit2();
        poolManager = new MockPoolManager();
        positionManager = new MockPositionManager(permit2, poolManager);
        factory = new LaunchpadFactorySafe(address(permit2), address(positionManager), address(poolManager), new address[](0));
        factory.addPairToken(address(paired));
        attacker = new CallActor();
        keeper = new CallActor();
        alice = new CallActor();
        bob = new CallActor();
    }

    function testLaunchLocksPositionAndClearsEveryApproval() public {
        address token = _launch(keccak256("locked"));
        uint256 positionId = factory.positionIdOf(token);
        address vault = factory.vaultOf(token);

        require(positionManager.ownerOf(positionId) == vault, "vault must own position");
        require(positionManager.ownerOf(positionId) != address(factory), "factory must not own position");
        require(LiquidityLockVault(vault).received(), "vault did not receive NFT");
        require(LaunchTokenSafe(token).balanceOf(address(poolManager)) == SUPPLY, "supply not seeded");
        require(LaunchTokenSafe(token).balanceOf(address(factory)) == 0, "factory token balance");
        require(LaunchTokenSafe(token).allowance(address(factory), address(permit2)) == 0, "ERC20 approval remains");

        (uint160 amount, uint48 expiration) = permit2.approvals(address(factory), token, address(positionManager));
        require(amount == 0 && expiration == 0, "Permit2 approval remains");
        require(LaunchTokenSafe(token).launcher() == address(this), "wrong launcher");
        require(LaunchTokenSafe(token).rewardEligibleSupply() == 0, "pool counted for rewards");
    }

    function testOriginalArbitraryCalldataExploitIsRejected() public {
        address token = _launch(keccak256("regression"));
        uint256 positionId = factory.positionIdOf(token);
        address vault = factory.vaultOf(token);

        bytes memory exploitCalldata = abi.encodeCall(
            MockPositionManager.setApprovalForAll,
            (address(attacker), true)
        );
        IOldLaunchpad.Params memory oldParams = IOldLaunchpad.Params({
            name: "Exploit",
            symbol: "EXP",
            supply: SUPPLY,
            pairedStock: address(paired),
            seedAmount: SUPPLY,
            salt: keccak256("old-interface"),
            description: "",
            image: "",
            website: "",
            twitter: "",
            holdersShare: true
        });
        IOldLaunchpad.SeedBuys memory buys = IOldLaunchpad.SeedBuys({
            payAsset: address(paired),
            totalPayIn: 0,
            preCommands: "",
            preInputs: new bytes[](0),
            amounts: new uint128[](0),
            recipients: new address[](0)
        });

        (bool accepted,) = address(factory).call(
            abi.encodeCall(IOldLaunchpad.launch, (oldParams, exploitCalldata, exploitCalldata, buys))
        );
        require(!accepted, "old arbitrary-calldata launch accepted");
        require(!positionManager.isApprovedForAll(vault, address(attacker)), "attacker approved by vault");
        require(!positionManager.isApprovedForAll(address(factory), address(attacker)), "attacker approved by factory");
        require(positionManager.ownerOf(positionId) == vault, "position owner changed");
    }

    function testAttackerCannotCollectBurnOrTransferLockedPosition() public {
        address token = _launch(keccak256("attacks"));
        uint256 positionId = factory.positionIdOf(token);
        address vault = factory.vaultOf(token);
        uint128 liquidityBefore = positionManager.liquidityOf(positionId);

        bool collected = attacker.tryCall(vault, abi.encodeCall(LiquidityLockVault.collect, (address(attacker))));
        bool burnt = attacker.tryCall(address(positionManager), abi.encodeCall(MockPositionManager.burn, (positionId)));
        bool transferred = attacker.tryCall(
            address(positionManager),
            abi.encodeCall(MockPositionManager.transferFrom, (vault, address(attacker), positionId))
        );

        require(!collected, "attacker collected");
        require(!burnt, "attacker burnt position");
        require(!transferred, "attacker transferred position");
        require(positionManager.ownerOf(positionId) == vault, "position escaped vault");
        require(positionManager.liquidityOf(positionId) == liquidityBefore, "principal changed");
    }

    function testHarvestBurnsTokenFeesAndUsesPullRewards() public {
        address token = _launch(keccak256("harvest"));
        uint256 positionId = factory.positionIdOf(token);
        uint128 liquidityBefore = positionManager.liquidityOf(positionId);

        poolManager.pay(token, address(alice), HOLDER_BALANCE);
        _fundFees(token, positionId, TOKEN_FEE, PAIRED_FEE);

        bool harvested = keeper.tryCall(address(factory), abi.encodeCall(LaunchpadFactorySafe.harvest, (token)));
        require(harvested, "harvest failed");
        require(positionManager.liquidityOf(positionId) == liquidityBefore, "principal decreased");
        require(LaunchTokenSafe(token).totalSupply() == SUPPLY - TOKEN_FEE, "token fees not burnt");
        require(paired.balanceOf(address(this)) == 100_000_000, "protocol cut");
        require(paired.balanceOf(address(keeper)) == 10_000_000, "keeper cut");
        require(LaunchTokenSafe(token).withdrawableRewardOf(address(alice)) == 890_000_000, "holder reward");

        bool claimed = alice.tryCall(token, abi.encodeCall(LaunchTokenSafe.claimReward, ()));
        require(claimed, "claim failed");
        require(paired.balanceOf(address(alice)) == 890_000_000, "claim amount");
        require(LaunchTokenSafe(token).rewardReserve() == 0, "reward reserve");
    }

    function testRewardsRemainCorrectAcrossTransfers() public {
        address token = _launch(keccak256("transfers"));
        uint256 positionId = factory.positionIdOf(token);
        poolManager.pay(token, address(alice), HOLDER_BALANCE);

        _fundFees(token, positionId, 0, PAIRED_FEE);
        require(keeper.tryCall(address(factory), abi.encodeCall(LaunchpadFactorySafe.harvest, (token))), "first harvest");

        require(
            alice.tryCall(token, abi.encodeCall(LaunchTokenSafe.transfer, (address(bob), HOLDER_BALANCE / 2))),
            "holder transfer"
        );

        _fundFees(token, positionId, 0, PAIRED_FEE);
        require(keeper.tryCall(address(factory), abi.encodeCall(LaunchpadFactorySafe.harvest, (token))), "second harvest");

        require(LaunchTokenSafe(token).withdrawableRewardOf(address(alice)) == 1_335_000_000, "alice accrual");
        require(LaunchTokenSafe(token).withdrawableRewardOf(address(bob)) == 445_000_000, "bob accrual");
        require(alice.tryCall(token, abi.encodeCall(LaunchTokenSafe.claimReward, ())), "alice claim");
        require(bob.tryCall(token, abi.encodeCall(LaunchTokenSafe.claimReward, ())), "bob claim");
        require(paired.balanceOf(address(alice)) == 1_335_000_000, "alice paid");
        require(paired.balanceOf(address(bob)) == 445_000_000, "bob paid");
    }

    function testNoHolderHarvestRoutesUserCutToLauncher() public {
        address token = _launch(keccak256("no-holders"));
        uint256 positionId = factory.positionIdOf(token);
        _fundFees(token, positionId, 0, PAIRED_FEE);

        require(keeper.tryCall(address(factory), abi.encodeCall(LaunchpadFactorySafe.harvest, (token))), "harvest failed");
        require(paired.balanceOf(address(this)) == 990_000_000, "launcher and protocol cuts");
        require(paired.balanceOf(token) == 0, "unclaimable rewards sent");
    }

    function testValidationRejectsUnapprovedPairsBadRangesAndBadSymbols() public {
        MockERC20 unapproved = new MockERC20("Unapproved", "NO", 18);
        LaunchpadFactorySafe.Params memory params = _params(keccak256("invalid-pair"));
        params.pairedStock = address(unapproved);
        require(!_tryLaunch(params), "unapproved pair accepted");

        params = _params(keccak256("invalid-range"));
        params.tickUpper -= 200;
        require(!_tryLaunch(params), "bad range accepted");

        params = _params(keccak256("invalid-symbol"));
        params.symbol = "bad";
        require(!_tryLaunch(params), "lowercase symbol accepted");
    }

    function testInitializeFailureSentinelIsRejectedForCurrency1() public {
        bytes32 salt;
        address predicted;
        for (uint256 i; i < 100; ++i) {
            salt = bytes32(i);
            predicted = factory.predict(address(this), salt);
            if (uint160(predicted) > uint160(address(paired))) break;
        }
        require(uint160(predicted) > uint160(address(paired)), "could not select currency1");

        positionManager.setInitializeFailure(true);
        require(!_tryLaunch(_params(salt)), "initialize failure accepted");
        positionManager.setInitializeFailure(false);
    }

    function testRejectsMismatchedPositionManagerInfrastructure() public {
        MockPoolManager wrongPoolManager = new MockPoolManager();
        try new LaunchpadFactorySafe(address(permit2), address(positionManager), address(wrongPoolManager), new address[](0)) returns (
            LaunchpadFactorySafe candidate
        ) {
            candidate;
            revert("mismatched infrastructure accepted");
        } catch {}
    }

    function testConstructorRegistersInitialPairTokens() public {
        address[] memory initialPairs = new address[](1);
        initialPairs[0] = address(paired);

        LaunchpadFactorySafe candidate = new LaunchpadFactorySafe(
            address(permit2), address(positionManager), address(poolManager), initialPairs
        );

        require(candidate.pairAllowed(address(paired)), "initial pair not allowed");
        require(candidate.pairTokensCount() == 1, "initial pair count mismatch");
        require(candidate.pairTokens(0) == address(paired), "initial pair not stored");
    }

    function testPauseAndTwoStepOwnership() public {
        factory.setPaused(true);
        require(!_tryLaunch(_params(keccak256("paused"))), "paused launch accepted");
        factory.setPaused(false);

        factory.transferOwnership(address(alice));
        require(factory.owner() == address(this), "ownership changed early");
        require(
            alice.tryCall(address(factory), abi.encodeCall(LaunchpadFactorySafe.acceptOwnership, ())),
            "pending owner cannot accept"
        );
        require(factory.owner() == address(alice), "ownership not accepted");
    }

    function testLaunchedTokenIsStandaloneNotProxy() public {
        address a = _launch(keccak256("standalone-a"));
        address b = _launch(keccak256("standalone-b"));

        // An EIP-1167 minimal-proxy clone is 45 bytes; a real standalone contract is far larger. Every
        // launch must carry full, identical runtime bytecode (so verifying one on an explorer matches all).
        require(a.code.length > 1000, "token A is not a full contract");
        require(b.code.length > 1000, "token B is not a full contract");
        require(a.code.length == b.code.length, "token bytecode length differs between launches");
        require(keccak256(a.code) == keccak256(b.code), "token bytecode not identical between launches");
    }

    function testDevBuyDeliversTokensToRecipientAndLeavesFactoryEmpty() public {
        uint256 spend = 500_000_000;
        paired.mint(address(this), spend);
        paired.approve(address(factory), spend);

        uint256[] memory amounts = new uint256[](1);
        address[] memory recipients = new address[](1);
        amounts[0] = spend;
        recipients[0] = address(alice);

        address token = _launchWithBundle(keccak256("devbuy"), amounts, recipients);

        // Funder (this) pays; the named recipient (alice) receives the tokens.
        require(LaunchTokenSafe(token).balanceOf(address(alice)) == spend, "recipient did not receive bought tokens");
        require(paired.balanceOf(address(this)) == 0, "funder paired not spent");
        require(paired.balanceOf(address(factory)) == 0, "factory kept paired");
        require(LaunchTokenSafe(token).balanceOf(address(factory)) == 0, "factory kept token");
        require(paired.balanceOf(address(poolManager)) == spend, "pool did not receive the paired input");
    }

    function testDevBuyBundleDeliversToFiveWallets() public {
        uint256 each = 100_000_000;
        uint256 total = each * 5;
        paired.mint(address(this), total);
        paired.approve(address(factory), total);

        uint256[] memory amounts = new uint256[](5);
        address[] memory recipients = new address[](5);
        recipients[0] = address(0xA1);
        recipients[1] = address(0xA2);
        recipients[2] = address(0xA3);
        recipients[3] = address(0xA4);
        recipients[4] = address(0xA5);
        for (uint256 i; i < 5; ++i) {
            amounts[i] = each;
        }

        address token = _launchWithBundle(keccak256("bundle"), amounts, recipients);

        for (uint256 i; i < 5; ++i) {
            require(LaunchTokenSafe(token).balanceOf(recipients[i]) == each, "a bundle wallet did not receive its buy");
        }
        require(paired.balanceOf(address(this)) == 0, "funder paired not fully spent");
        require(paired.balanceOf(address(factory)) == 0, "factory kept paired");
        require(LaunchTokenSafe(token).balanceOf(address(factory)) == 0, "factory kept token");
        require(paired.balanceOf(address(poolManager)) == total, "pool did not receive total input");
    }

    function testDevBuyRefundsUnspentPaired() public {
        poolManager.setConsumeBps(6_000);
        uint256 spend = 1_000_000_000;
        paired.mint(address(this), spend);
        paired.approve(address(factory), spend);

        uint256[] memory amounts = new uint256[](1);
        address[] memory recipients = new address[](1);
        amounts[0] = spend;
        recipients[0] = address(this);

        address token = _launchWithBundle(keccak256("devbuy-refund"), amounts, recipients);

        require(paired.balanceOf(address(this)) == 400_000_000, "unspent paired not refunded");
        require(LaunchTokenSafe(token).balanceOf(address(this)) == 600_000_000, "bought token mismatch");
        require(paired.balanceOf(address(factory)) == 0, "factory kept paired");
        require(LaunchTokenSafe(token).balanceOf(address(factory)) == 0, "factory kept token");
    }

    function testDevBuyRejectsOverflowAndMismatchedArrays() public {
        paired.mint(address(this), 10_000_000_000);
        paired.approve(address(factory), 10_000_000_000);

        uint256[] memory a6 = new uint256[](6);
        address[] memory r6 = new address[](6);
        for (uint256 i; i < 6; ++i) {
            a6[i] = 1_000_000;
            r6[i] = address(uint160(i + 1));
        }
        LaunchpadFactorySafe.Params memory tooMany = _params(keccak256("too-many"));
        tooMany.devBuyAmounts = a6;
        tooMany.devBuyRecipients = r6;
        require(!_tryLaunch(tooMany), "accepted more than MAX_DEV_BUYS buys");

        uint256[] memory a2 = new uint256[](2);
        address[] memory r1 = new address[](1);
        a2[0] = 1_000_000;
        a2[1] = 1_000_000;
        r1[0] = address(0xB1);
        LaunchpadFactorySafe.Params memory mismatch = _params(keccak256("mismatch"));
        mismatch.devBuyAmounts = a2;
        mismatch.devBuyRecipients = r1;
        require(!_tryLaunch(mismatch), "accepted mismatched dev-buy arrays");
    }

    function testDevAllocationSendsSupplyToLauncherAndSeedsRest() public {
        LaunchpadFactorySafe.Params memory params = _params(keccak256("dev-alloc"));
        params.devAllocationBps = 2000;
        positionManager.setNextInitializedTick(0);
        address token = factory.launch(params);

        uint256 expectedAlloc = (SUPPLY * 2000) / 10000;
        require(LaunchTokenSafe(token).balanceOf(address(this)) == expectedAlloc, "launcher allocation wrong");
        require(LaunchTokenSafe(token).balanceOf(address(poolManager)) == SUPPLY - expectedAlloc, "seed amount wrong");
        require(LaunchTokenSafe(token).balanceOf(address(factory)) == 0, "factory retained supply");
        require(LaunchTokenSafe(token).totalSupply() == SUPPLY, "supply changed");
        require(LaunchTokenSafe(token).rewardEligibleSupply() == expectedAlloc, "allocation not reward-eligible");
    }

    function testDevAllocationRejectsOverCap() public {
        LaunchpadFactorySafe.Params memory params = _params(keccak256("alloc-over"));
        params.devAllocationBps = 2001;
        require(!_tryLaunch(params), "accepted a dev allocation above 20%");
    }

    function testDevAllocationZeroSeedsFullSupply() public {
        address token = _launch(keccak256("alloc-zero"));
        require(LaunchTokenSafe(token).balanceOf(address(poolManager)) == SUPPLY, "not fully seeded");
        require(LaunchTokenSafe(token).balanceOf(address(this)) == 0, "unexpected allocation");
    }

    function testDevBuyDonationDoesNotBrickOrLeak() public {
        uint256 spend = 500_000_000;
        uint256 donation = 900_000_000;
        paired.mint(address(this), spend);
        paired.approve(address(factory), spend);
        paired.mint(address(factory), donation);

        uint256[] memory amounts = new uint256[](1);
        address[] memory recipients = new address[](1);
        amounts[0] = spend;
        recipients[0] = address(alice);

        address token = _launchWithBundle(keccak256("donation"), amounts, recipients);

        require(LaunchTokenSafe(token).balanceOf(address(alice)) == spend, "recipient tokens wrong");
        require(paired.balanceOf(address(this)) == 0, "launcher over-refunded: donation leaked");
        require(paired.balanceOf(address(factory)) == donation, "donation not retained in factory");
        require(LaunchTokenSafe(token).balanceOf(address(factory)) == 0, "factory kept token");
    }

    function testUnlockCallbackRejectsWhenNoSwapInFlight() public {
        (bool ok,) = address(poolManager).call(
            abi.encodeCall(MockPoolManager.pokeCallback, (address(factory), bytes("")))
        );
        require(!ok, "unlockCallback accepted with no swap in flight");
    }

    function testPairAllowlistAddRemoveReAddBookkeeping() public {
        MockERC20 a = new MockERC20("A", "A", 18);
        MockERC20 b = new MockERC20("B", "B", 18);
        MockERC20 c = new MockERC20("C", "C", 18);
        factory.addPairToken(address(a));
        factory.addPairToken(address(b));
        factory.addPairToken(address(c));

        factory.removePairToken(address(b));
        require(!factory.pairAllowed(address(b)), "b still allowed after remove");
        require(factory.pairAllowed(address(a)) && factory.pairAllowed(address(c)), "swap-pop dropped a or c");

        factory.addPairToken(address(b));
        require(factory.pairAllowed(address(b)), "b not re-added");

        MockERC20 d = new MockERC20("D", "D", 18);
        address[] memory batch = new address[](2);
        batch[0] = address(a);
        batch[1] = address(d);
        factory.addPairTokens(batch);
        require(factory.pairAllowed(address(d)), "batch did not add new pair");
        require(factory.pairAllowed(address(a)), "batch dropped duplicate");
    }

    function testDevBuyZeroSkipsSwapAndStillLaunches() public {
        address token = _launch(keccak256("no-devbuy"));
        require(factory.launcherOf(token) == address(this), "launch failed without a dev buy");
        require(LaunchTokenSafe(token).balanceOf(address(this)) == 0, "unexpected dev buy occurred");
    }

    function testUnlockCallbackRejectsForeignCaller() public {
        require(
            !attacker.tryCall(address(factory), abi.encodeCall(LaunchpadFactorySafe.unlockCallback, (bytes("")))),
            "unlockCallback accepted a caller other than the pool manager"
        );
    }

    function _launch(bytes32 salt) internal returns (address token) {
        LaunchpadFactorySafe.Params memory params = _params(salt);
        positionManager.setNextInitializedTick(0);
        token = factory.launch(params);
        require(token == factory.predict(address(this), salt), "prediction mismatch");
    }

    function _launchWithBundle(bytes32 salt, uint256[] memory amounts, address[] memory recipients)
        internal
        returns (address token)
    {
        LaunchpadFactorySafe.Params memory params = _params(salt);
        params.devBuyAmounts = amounts;
        params.devBuyRecipients = recipients;
        positionManager.setNextInitializedTick(0);
        token = factory.launch(params);
        require(token == factory.predict(address(this), salt), "prediction mismatch");
    }

    function _params(bytes32 salt) internal view returns (LaunchpadFactorySafe.Params memory params) {
        address predicted = factory.predict(address(this), salt);
        bool tokenIsCurrency0 = uint160(predicted) < uint160(address(paired));
        int24 tickLower = tokenIsCurrency0 ? int24(200) : int24(-60_200);
        int24 tickUpper = tokenIsCurrency0 ? int24(60_200) : int24(-200);
        params = LaunchpadFactorySafe.Params({
            name: "Validated Token",
            symbol: "VALID",
            supply: SUPPLY,
            pairedStock: address(paired),
            salt: salt,
            description: "Security regression test token",
            image: "",
            website: "https://unistreet.org",
            twitter: "",
            holdersShare: true,
            sqrtPriceX96: uint160(1 << 96),
            tickLower: tickLower,
            tickUpper: tickUpper,
            liquidity: 1 ether,
            devAllocationBps: 0,
            devBuyAmounts: new uint256[](0),
            devBuyRecipients: new address[](0)
        });
    }

    function _tryLaunch(LaunchpadFactorySafe.Params memory params) internal returns (bool success) {
        positionManager.setNextInitializedTick(0);
        (success,) = address(factory).call(abi.encodeCall(LaunchpadFactorySafe.launch, (params)));
    }

    function _fundFees(address token, uint256 positionId, uint256 tokenFee, uint256 pairedFee) internal {
        address currency0 = uint160(token) < uint160(address(paired)) ? token : address(paired);
        if (pairedFee != 0) paired.mint(address(poolManager), pairedFee);
        if (currency0 == token) {
            positionManager.setFees(positionId, tokenFee, pairedFee);
        } else {
            positionManager.setFees(positionId, pairedFee, tokenFee);
        }
    }
}

project/test/mocks/LaunchpadMocks.sol

pragma solidity ^0.8.24;

interface IERC20Mock {
    function transfer(address recipient, uint256 amount) external returns (bool);
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}

contract MockERC20 {
    string public name;
    string public symbol;
    uint8 public immutable decimals;
    uint256 public totalSupply;

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

    constructor(string memory name_, string memory symbol_, uint8 decimals_) {
        name = name_;
        symbol = symbol_;
        decimals = decimals_;
    }

    function mint(address recipient, uint256 amount) external {
        totalSupply += amount;
        balanceOf[recipient] += amount;
    }

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

    function transfer(address recipient, uint256 amount) external returns (bool) {
        _transfer(msg.sender, recipient, amount);
        return true;
    }

    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {
        uint256 allowed = allowance[sender][msg.sender];
        require(allowed >= amount, "allowance");
        if (allowed != type(uint256).max) allowance[sender][msg.sender] = allowed - amount;
        _transfer(sender, recipient, amount);
        return true;
    }

    function _transfer(address sender, address recipient, uint256 amount) internal {
        require(recipient != address(0), "zero");
        uint256 balance = balanceOf[sender];
        require(balance >= amount, "balance");
        unchecked {
            balanceOf[sender] = balance - amount;
            balanceOf[recipient] += amount;
        }
    }
}

interface IUnlockCallback {
    function unlockCallback(bytes calldata data) external returns (bytes memory);
}

interface IBalance {
    function balanceOf(address account) external view returns (uint256);
}

contract MockPoolManager {
    struct PoolKey {
        address currency0;
        address currency1;
        uint24 fee;
        int24 tickSpacing;
        address hooks;
    }

    struct SwapParams {
        bool zeroForOne;
        int256 amountSpecified;
        uint160 sqrtPriceLimitX96;
    }

    address private unlocker;
    address private syncedCurrency;
    uint256 private syncedBalance;
    // Knobs so tests can drive the exact-input swap: consume only part of the input (to exercise the
    // factory's paired-refund path) and set the token-out rate (to exercise the slippage floor).
    uint256 public consumeBps = 10_000;
    uint256 public rate = 1;

    function pay(address token, address recipient, uint256 amount) external {
        require(IERC20Mock(token).transfer(recipient, amount), "transfer");
    }

    function setConsumeBps(uint256 bps) external {
        consumeBps = bps;
    }

    function setRate(uint256 r) external {
        rate = r;
    }

    function unlock(bytes calldata data) external returns (bytes memory result) {
        require(unlocker == address(0), "locked");
        unlocker = msg.sender;
        result = IUnlockCallback(msg.sender).unlockCallback(data);
        unlocker = address(0);
    }

    // Test hook: invoke a target's unlockCallback AS the pool manager but with NO swap in flight, to
    // exercise the factory's `_swap.active` guard (msg.sender==poolManager passes; active is false).
    function pokeCallback(address target, bytes calldata data) external returns (bytes memory) {
        return IUnlockCallback(target).unlockCallback(data);
    }

    function swap(PoolKey calldata, SwapParams calldata params, bytes calldata) external returns (int256) {
        require(msg.sender == unlocker, "unlocker");
        require(params.amountSpecified < 0, "exact-in");
        uint256 amountIn = uint256(-params.amountSpecified);
        uint256 consumed = (amountIn * consumeBps) / 10_000;
        uint256 out = consumed * rate;

        int128 amount0;
        int128 amount1;
        if (params.zeroForOne) {
            amount0 = -int128(int256(consumed));
            amount1 = int128(int256(out));
        } else {
            amount1 = -int128(int256(consumed));
            amount0 = int128(int256(out));
        }
        return (int256(amount0) << 128) | int256(uint256(uint128(amount1)));
    }

    function sync(address currency) external {
        syncedCurrency = currency;
        syncedBalance = IBalance(currency).balanceOf(address(this));
    }

    function settle() external payable returns (uint256 paid) {
        paid = IBalance(syncedCurrency).balanceOf(address(this)) - syncedBalance;
        syncedCurrency = address(0);
        syncedBalance = 0;
    }

    function take(address currency, address to, uint256 amount) external {
        require(msg.sender == unlocker, "unlocker");
        require(IERC20Mock(currency).transfer(to, amount), "take");
    }
}

contract MockPermit2 {
    struct Approval {
        uint160 amount;
        uint48 expiration;
    }

    mapping(address => mapping(address => mapping(address => Approval))) public approvals;

    function approve(address token, address spender, uint160 amount, uint48 expiration) external {
        approvals[msg.sender][token][spender] = Approval(amount, expiration);
    }

    function transferFrom(address sender, address recipient, uint160 amount, address token) external {
        Approval storage approval = approvals[sender][token][msg.sender];
        require(approval.expiration >= block.timestamp, "expired");
        require(approval.amount >= amount, "permit2 allowance");
        approval.amount -= amount;
        require(IERC20Mock(token).transferFrom(sender, recipient, amount), "transferFrom");
    }
}

contract MockPositionManager {
    struct PoolKey {
        address currency0;
        address currency1;
        uint24 fee;
        int24 tickSpacing;
        address hooks;
    }

    struct Position {
        uint128 liquidity;
        address currency0;
        address currency1;
    }

    MockPermit2 public immutable permit2;
    MockPoolManager public immutable poolManager;
    uint256 public nextTokenId = 1;
    int24 public nextInitializedTick;
    bool public initializeFailure;

    mapping(uint256 => address) public ownerOf;
    mapping(address => mapping(address => bool)) public isApprovedForAll;
    mapping(uint256 => Position) public positionOf;
    mapping(uint256 => uint256) public fee0Of;
    mapping(uint256 => uint256) public fee1Of;

    constructor(MockPermit2 permit2_, MockPoolManager poolManager_) {
        permit2 = permit2_;
        poolManager = poolManager_;
    }

    function setNextInitializedTick(int24 tick) external {
        nextInitializedTick = tick;
    }

    function setInitializeFailure(bool value) external {
        initializeFailure = value;
    }

    function initializePool(PoolKey calldata key, uint160 sqrtPriceX96) external returns (int24 tick) {
        require(key.currency0 < key.currency1, "sort");
        require(key.fee == 10_000 && key.tickSpacing == 200 && key.hooks == address(0), "key");
        require(sqrtPriceX96 != 0, "price");
        if (initializeFailure) return type(int24).max;
        return nextInitializedTick;
    }

    function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external {
        require(deadline >= block.timestamp, "deadline");
        (bytes memory actions, bytes[] memory params) = abi.decode(unlockData, (bytes, bytes[]));

        if (keccak256(actions) == keccak256(hex"020d")) {
            _mintPosition(params);
            return;
        }
        if (keccak256(actions) == keccak256(hex"0111")) {
            _collect(params);
            return;
        }
        revert("actions");
    }

    function setFees(uint256 tokenId, uint256 amount0, uint256 amount1) external {
        fee0Of[tokenId] = amount0;
        fee1Of[tokenId] = amount1;
    }

    function setApprovalForAll(address operator, bool approved) external {
        isApprovedForAll[msg.sender][operator] = approved;
    }

    function transferFrom(address sender, address recipient, uint256 tokenId) external {
        require(ownerOf[tokenId] == sender, "owner");
        require(msg.sender == sender || isApprovedForAll[sender][msg.sender], "approval");
        ownerOf[tokenId] = recipient;
    }

    function burn(uint256 tokenId) external {
        address positionOwner = ownerOf[tokenId];
        require(msg.sender == positionOwner || isApprovedForAll[positionOwner][msg.sender], "approval");
        delete ownerOf[tokenId];
        delete positionOf[tokenId];
    }

    function liquidityOf(uint256 tokenId) external view returns (uint128) {
        return positionOf[tokenId].liquidity;
    }

    function _mintPosition(bytes[] memory params) internal {
        require(params.length == 2, "params");
        (
            PoolKey memory key,
            int24 tickLower,
            int24 tickUpper,
            uint256 liquidity,
            uint128 amount0Max,
            uint128 amount1Max,
            address recipient,
            bytes memory hookData
        ) = abi.decode(params[0], (PoolKey, int24, int24, uint256, uint128, uint128, address, bytes));

        require(tickUpper - tickLower == 60_000, "range");
        require(liquidity != 0 && liquidity <= type(uint128).max, "liquidity");
        require(hookData.length == 0, "hookData");
        require((amount0Max == 0) != (amount1Max == 0), "one sided");

        address token = amount0Max != 0 ? key.currency0 : key.currency1;
        uint160 amount = amount0Max != 0 ? amount0Max : amount1Max;
        permit2.transferFrom(msg.sender, address(poolManager), amount, token);

        uint256 tokenId = nextTokenId++;
        ownerOf[tokenId] = recipient;
        positionOf[tokenId] = Position(uint128(liquidity), key.currency0, key.currency1);
    }

    function _collect(bytes[] memory params) internal {
        require(params.length == 2, "params");
        (uint256 tokenId, uint256 liquidity, uint128 amount0Min, uint128 amount1Min, bytes memory hookData) =
            abi.decode(params[0], (uint256, uint256, uint128, uint128, bytes));
        (address currency0, address currency1, address recipient) =
            abi.decode(params[1], (address, address, address));

        Position memory position = positionOf[tokenId];
        require(ownerOf[tokenId] == msg.sender, "owner");
        require(position.currency0 == currency0 && position.currency1 == currency1, "currencies");
        require(liquidity == 0 && amount0Min == 0 && amount1Min == 0 && hookData.length == 0, "principal");

        uint256 amount0 = fee0Of[tokenId];
        uint256 amount1 = fee1Of[tokenId];
        delete fee0Of[tokenId];
        delete fee1Of[tokenId];
        if (amount0 != 0) poolManager.pay(currency0, recipient, amount0);
        if (amount1 != 0) poolManager.pay(currency1, recipient, amount1);
    }
}

contract CallActor {
    function tryCall(address target, bytes calldata data) external returns (bool success) {
        (success,) = target.call(data);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "evmVersion": "shanghai",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.