Skip to content
Verified contractPartialMIT

HeptadFactory

Address0x9be5a0f441f883e0986bd9c932cd4707be2f3ce5
Balance

0 ETH

 

Transactions

12

 

Compiler

solc 0.8.26

 

Same code

Only this 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,270,918
Creation transaction
0x030264ac31…ceae44023a

93 files

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

src/HeptadFactory.sol

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

import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {IHooks} from "v4-core/src/interfaces/IHooks.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol";
import {Currency, CurrencyLibrary} from "v4-core/src/types/Currency.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "v4-core/src/types/PoolOperation.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {FullMath} from "v4-core/src/libraries/FullMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {OptionsBuilder} from "@layerzerolabs/oapp-evm/contracts/oapp/libs/OptionsBuilder.sol";
import {EnforcedOptionParam} from "@layerzerolabs/oapp-evm/contracts/oapp/libs/OAppOptionsType3.sol";
import {HeptadKey} from "./HeptadKey.sol";
import {HeptadToken} from "./HeptadToken.sol";
import {HeptadTokenDeployer} from "./HeptadTokenDeployer.sol";
import {HeptadHook} from "./HeptadHook.sol";

/// @dev minimal LayerZero endpoint surface used to pin a token's routes at launch
interface ILZEndpointPin {
    function setSendLibrary(address oapp, uint32 eid, address lib) external;
    function setReceiveLibrary(address oapp, uint32 eid, address lib, uint256 gracePeriod) external;
    function setConfig(address oapp, address lib, LZSetConfigParam[] calldata params) external;
}

struct LZSetConfigParam {
    uint32 eid;
    uint32 configType;
    bytes config;
}

/// @dev ABI-identical to LayerZero's ULN `UlnConfig` / `ExecutorConfig`
struct LZUlnConfig {
    uint64 confirmations;
    uint8 requiredDVNCount;
    uint8 optionalDVNCount;
    uint8 optionalDVNThreshold;
    address[] requiredDVNs;
    address[] optionalDVNs;
}

struct LZExecutorConfig {
    uint32 maxMessageSize;
    address executor;
}

/// @title HeptadFactory
/// @notice Launches a token on THIS chain and holds the launch-fee escrow. A launch is one signed request that the platform
///         relayer runs on every Heptad chain. Each chain has its OWN contracts, so the same token has a different address on
///         each chain; the factories know each other (registry set once, then locked) and use that to wire the LayerZero
///         peers to the right remote addresses. The creator pays once, on one chain (the "origin" chain, which must be a chain
///         with a launch fee), into an escrow; the relayer then runs `launch` on every chain, each time proving the creator's
///         signed parameters and the platform signer's price quote for that chain.
///
///         A launch deploys the token (a LayerZero OFT), registers its tax config on the hook, creates the NATIVE/token
///         pool, adds ALL of the supply as locked single-sided liquidity, pins the token's LayerZero routes, and seals them.
///
/// @dev    Trust model. The relayer can only launch exactly what the creator signed (EIP-712, no chain id so one
///         signature works on every chain), at a price the signer approved for that chain, inside the tick bounds the owner
///         set. It can never touch escrowed funds except to move them through a completed launch. Creators can cancel a
///         pending deposit at any time, and reclaim a stuck one once the signed deadline has passed.
///         Liquidity is owned by this contract, which has no function to remove it, so it is locked forever.
contract HeptadFactory is IUnlockCallback, EIP712, Ownable2Step, ReentrancyGuard {
    using HeptadKey for address;
    using PoolIdLibrary for PoolKey;
    using OptionsBuilder for bytes;

    uint256 public constant TOTAL_SUPPLY = 1_000_000_000 ether;
    uint160 private constant Q96 = 2 ** 96;
    int24 private constant TICK_MARGIN = 20 * 200;
    address private constant DEAD = 0x000000000000000000000000000000000000dEaD;
    uint16 private constant BPS = 10_000;
    /// @notice A deposit's signed deadline may be at most this far in the future
    uint64 public constant MAX_WINDOW = 2 hours;
    /// @notice The relayer may only start processing a deposit if at least this much time is left
    uint64 public constant MIN_PROCESS_WINDOW = 5 minutes;

    bytes32 private constant LAUNCH_TYPEHASH = keccak256(
        "Launch(address creator,string name,string symbol,string uri,uint16 taxBps,uint16 toCreator,uint16 toHolders,uint16 toBurn,uint16 toPool,uint256 devBuy,bytes32 salt,uint64 deadline,uint256 originChainId)"
    );
    /// @dev the creator's domain has NO chain id and NO verifying contract: one signature is valid on every chain
    bytes32 private constant CREATOR_DOMAIN =
        keccak256(abi.encode(keccak256("EIP712Domain(string name,string version)"), keccak256("Heptad"), keccak256("1")));
    bytes32 private constant QUOTE_TYPEHASH = keccak256("Quote(bytes32 launchHash,int24 startTick)");

    // ---------------------------------------------------------------- immutables / config

    IPoolManager public immutable poolManager;
    HeptadHook public immutable hook;
    HeptadTokenDeployer public immutable deployer;
    /// @notice LayerZero EndpointV2 of this chain (read by every token at construction)
    address public immutable lzEndpoint;
    /// @notice Flat launch fee in native wei, charged once on the origin chain. Permanent. ZERO on chains that only
    ///         receive launches (deposits are disabled there).
    uint256 public immutable launchFee;
    /// @notice The wallet that deployed this factory; besides the owner it may call `setRemotes` (once, then locked)
    address public immutable bootstrapper;

    address public treasury;
    address public relayer;
    address public signer;
    bool public paused;
    /// @notice Share of the launch fee (bps) that reimburses the relayer wallet; the rest goes to the treasury
    uint16 public relayerFeeBps = BPS;
    /// @notice Allowed opening tick range on this chain (sanity bound on the signer's price)
    int24 public minTick;
    int24 public maxTick;

    /// @dev LayerZero settings for ONE path (this chain <-> one remote chain). Read from the chain's LayerZero defaults at
    ///      deploy time, so each path uses exactly the verifiers LayerZero itself runs for that pair of chains.
    struct Path {
        uint32 eid; // the remote chain's LayerZero endpoint id
        address sendLib;
        address recvLib;
        address executor;
        uint32 maxMessageSize;
        uint64 sendConfirmations; // confirmations required on THIS chain for messages it sends to `eid`
        uint64 recvConfirmations; // confirmations required on `eid` for messages it sends to this chain
        address[] sendDvns; // required verifiers for messages sent to `eid`, sorted ascending
        address[] recvDvns; // required verifiers for messages received from `eid`, sorted ascending
    }

    struct Route {
        uint128 lzReceiveGas;
        Path[] paths; // one per other Heptad chain
    }

    /// @notice The other Heptad chains' deployer and factory, used to predict token addresses there
    struct Remote {
        address deployer;
        address factory;
    }

    mapping(uint32 eid => Remote) public remotes;
    bool public remotesLocked;

    Route private _route;

    struct LaunchParams {
        address creator;
        string name;
        string symbol;
        string uri; // metadata reference (image, links); indexed off-chain
        uint16 taxBps; // 100..1000, whole percents (1% to 10%)
        uint16 toCreator; // how the creator side (70% of the tax) is split, in bps of that side; the four sum to 10_000
        uint16 toHolders;
        uint16 toBurn;
        uint16 toPool;
        uint256 devBuy; // creator's first buy in native wei, executed on the origin chain only (untaxed)
        bytes32 salt; // CREATE2 salt, the same on every chain (token addresses still differ: the deployers differ)
        uint64 deadline; // the launch must happen before this time on every chain
        uint256 originChainId; // the chain where the creator pays the fee
    }

    enum State {
        None,
        Pending, // fee deposited, relayer has not started: creator can cancel instantly
        Processing, // relayer started: creator can reclaim only after the deadline
        Done,
        Refunded
    }

    struct Escrow {
        address creator;
        State state;
        uint64 deadline;
        uint256 devBuy;
        uint256 amount;
    }

    mapping(bytes32 launchHash => Escrow) public escrows;

    struct LaunchCtx {
        address token;
        address creator;
        uint256 devBuy;
        int24 startTick;
        PoolKey key;
    }

    address[] public allTokens;
    mapping(address => bool) public isHeptadToken;
    /// @notice Start tick of each token's locked liquidity position (the upper edge of its range)
    mapping(address => int24) public startTickOf;

    // ---------------------------------------------------------------- events / errors

    event Deposited(bytes32 indexed launchHash, address indexed creator, uint64 deadline, uint256 devBuy, uint256 amount);
    event Cancelled(bytes32 indexed launchHash, address indexed creator, uint256 amount);
    event Begun(bytes32 indexed launchHash);
    event Reclaimed(bytes32 indexed launchHash, address indexed creator, uint256 amount);
    event TokenLaunched(
        address indexed token,
        address indexed creator,
        uint16 taxBps,
        bytes32 launchHash,
        bytes32 poolId,
        int24 startTick,
        uint256 devBuyNative,
        uint256 devBuyTokens,
        uint256 originChainId
    );
    event TokenMetadata(address indexed token, string name, string symbol, string uri);
    event SignerChanged(address indexed signer);
    event RelayerChanged(address indexed relayer);
    event TreasuryChanged(address indexed treasury);
    event PausedChanged(bool paused);
    event TickBoundsChanged(int24 minTick, int24 maxTick);
    event RelayerFeeBpsChanged(uint16 bps);
    event RouteChanged();
    event RemotesLocked();

    error NotRelayer();
    error Paused();
    error InvalidParams();
    error BadSignature();
    error Expired();
    error WrongOrigin();
    error BadEscrow();
    error NotCreator();
    error TooEarly();
    error NotPoolManager();
    error TransferFailed();
    error BadPrice();
    error BadRoute();
    error DepositWrong();
    error OriginDisabled();
    error NotAllowed();
    error RemotesNotReady();

    modifier onlyRelayer() {
        if (msg.sender != relayer) revert NotRelayer();
        _;
    }

    constructor(
        IPoolManager poolManager_,
        HeptadHook hook_,
        HeptadTokenDeployer deployer_,
        address lzEndpoint_,
        address owner_,
        address treasury_,
        address relayer_,
        address signer_,
        uint256 launchFee_,
        int24 minTick_,
        int24 maxTick_,
        Route memory route_
    ) EIP712("Heptad Quote", "1") Ownable(owner_) {
        if (treasury_ == address(0) || relayer_ == address(0) || signer_ == address(0) || lzEndpoint_ == address(0)) {
            revert InvalidParams();
        }
        poolManager = poolManager_;
        hook = hook_;
        deployer = deployer_;
        lzEndpoint = lzEndpoint_;
        launchFee = launchFee_;
        bootstrapper = msg.sender;
        treasury = treasury_;
        relayer = relayer_;
        signer = signer_;
        _setBounds(minTick_, maxTick_);
        _setRoute(route_);
    }

    // ---------------------------------------------------------------- owner controls (apply to FUTURE launches only)

    function setSigner(address s) external onlyOwner {
        if (s == address(0)) revert InvalidParams();
        signer = s;
        emit SignerChanged(s);
    }

    function setRelayer(address r) external onlyOwner {
        if (r == address(0)) revert InvalidParams();
        relayer = r;
        emit RelayerChanged(r);
    }

    function setTreasury(address t) external onlyOwner {
        if (t == address(0)) revert InvalidParams();
        treasury = t;
        emit TreasuryChanged(t);
    }

    /// @notice Stops new deposits and launches. Cancel/reclaim and every existing token keep working.
    function setPaused(bool p) external onlyOwner {
        paused = p;
        emit PausedChanged(p);
    }

    function setTickBounds(int24 lo, int24 hi) external onlyOwner {
        _setBounds(lo, hi);
    }

    function setRelayerFeeBps(uint16 bps) external onlyOwner {
        if (bps > BPS) revert InvalidParams();
        relayerFeeBps = bps;
        emit RelayerFeeBpsChanged(bps);
    }

    /// @notice Only before the remotes are locked: later route changes could re-point a token's verifiers, but they only
    ///         ever affect FUTURE launches (a launched token pins its own route and renounces control).
    function setRoute(Route calldata r) external onlyOwner {
        _setRoute(r);
    }

    /// @notice One time: tell this factory where the other chains' deployers and factories are, then lock. Launches that
    ///         wire LayerZero peers are impossible before this is done.
    function setRemotes(uint32[] calldata eids, address[] calldata deployers, address[] calldata factories)
        external
    {
        if (msg.sender != owner() && msg.sender != bootstrapper) revert NotAllowed();
        if (remotesLocked || eids.length != deployers.length || eids.length != factories.length) revert InvalidParams();
        Path[] storage ps = _route.paths;
        if (eids.length != ps.length) revert InvalidParams();
        for (uint256 i = 0; i < eids.length; i++) {
            if (deployers[i] == address(0) || factories[i] == address(0)) revert InvalidParams();
            remotes[eids[i]] = Remote(deployers[i], factories[i]);
        }
        // every remote eid of the route must be covered
        for (uint256 i = 0; i < ps.length; i++) {
            if (remotes[ps[i].eid].factory == address(0)) revert InvalidParams();
        }
        remotesLocked = true;
        emit RemotesLocked();
    }

    function route() external view returns (Route memory) {
        return _route;
    }

    function allTokensLength() external view returns (uint256) {
        return allTokens.length;
    }

    // ---------------------------------------------------------------- views for the backend / UI

    /// @notice The token address a launch will get (on THIS chain; other chains have other addresses)
    function predictToken(string calldata name, string calldata symbol, address creator, bytes32 salt)
        external
        view
        returns (address)
    {
        return deployer.predict(name, symbol, creator, salt);
    }

    /// @notice The EIP-712 struct hash of the launch parameters; it is also the escrow key
    function launchHash(LaunchParams calldata p) public pure returns (bytes32) {
        bytes32 nameH = keccak256(bytes(p.name));
        bytes32 symbolH = keccak256(bytes(p.symbol));
        bytes32 uriH = keccak256(bytes(p.uri));
        // all fields are 32-byte words, so two concatenated abi.encode calls equal one big abi.encode
        return keccak256(
            bytes.concat(
                abi.encode(LAUNCH_TYPEHASH, p.creator, nameH, symbolH, uriH),
                abi.encode(p.taxBps, p.toCreator, p.toHolders, p.toBurn, p.toPool),
                abi.encode(p.devBuy, p.salt, p.deadline, p.originChainId)
            )
        );
    }

    /// @notice The digest the creator signs (no chain id: valid on every chain)
    function creatorDigest(bytes32 lh) public pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", CREATOR_DOMAIN, lh));
    }

    /// @notice The digest the platform signer signs for ONE chain (domain includes this chain id and this factory)
    function quoteDigest(bytes32 lh, int24 startTick) public view returns (bytes32) {
        return _hashTypedDataV4(keccak256(abi.encode(QUOTE_TYPEHASH, lh, startTick)));
    }

    /// @notice The tick a launch with this opening fully diluted value (in native wei) starts at.
    ///         Reverts with BadPrice if out of range. The backend uses it so its ticks match the contract's maths.
    function previewStartTick(uint256 fdvWei) public pure returns (int24 tick) {
        if (fdvWei == 0 || fdvWei >= 2 ** 128) revert BadPrice();
        // token is currency1: price = tokens per native wei = supply / fdv, sqrtP = sqrt(supply / fdv) * 2^96
        uint256 sa = Math.sqrt(TOTAL_SUPPLY << 64);
        uint256 sb = Math.sqrt(fdvWei << 64);
        uint256 sqrtP = FullMath.mulDiv(sa, Q96, sb);
        if (sqrtP <= TickMath.MIN_SQRT_PRICE || sqrtP >= TickMath.MAX_SQRT_PRICE) revert BadPrice();
        int24 raw = TickMath.getTickAtSqrtPrice(uint160(sqrtP));
        int24 sp = HeptadKey.TICK_SPACING;
        int24 floored = (raw / sp) * sp;
        if (raw < 0 && raw % sp != 0) floored -= sp; // floor division for negatives
        tick = floored;
        if (tick < TickMath.MIN_TICK + TICK_MARGIN || tick > TickMath.MAX_TICK - TICK_MARGIN) revert BadPrice();
    }

    // ---------------------------------------------------------------- escrow (origin chain)

    /// @notice Creator pays the launch fee (+ optional first buy) into escrow. `lh` is `launchHash(params)`.
    function deposit(bytes32 lh, uint64 deadline, uint256 devBuy) external payable nonReentrant {
        if (paused) revert Paused();
        if (launchFee == 0) revert OriginDisabled(); // chains without a launch fee only receive launches
        if (escrows[lh].state != State.None) revert BadEscrow();
        if (msg.value != launchFee + devBuy) revert DepositWrong();
        if (deadline <= block.timestamp || deadline > block.timestamp + MAX_WINDOW) revert InvalidParams();
        escrows[lh] = Escrow({
            creator: msg.sender, state: State.Pending, deadline: deadline, devBuy: devBuy, amount: msg.value
        });
        emit Deposited(lh, msg.sender, deadline, devBuy, msg.value);
    }

    /// @notice Cancel a deposit the relayer has not started on. Full refund, any time.
    function cancel(bytes32 lh) external nonReentrant {
        Escrow storage e = escrows[lh];
        if (e.state != State.Pending) revert BadEscrow();
        if (msg.sender != e.creator) revert NotCreator();
        e.state = State.Refunded;
        _send(e.creator, e.amount);
        emit Cancelled(lh, e.creator, e.amount);
    }

    /// @notice The relayer marks a deposit as being processed; this locks the creator's instant cancel
    function begin(bytes32 lh) external onlyRelayer {
        if (paused) revert Paused();
        Escrow storage e = escrows[lh];
        if (e.state != State.Pending) revert BadEscrow();
        if (e.deadline < block.timestamp + MIN_PROCESS_WINDOW) revert Expired();
        e.state = State.Processing;
        emit Begun(lh);
    }

    /// @notice If processing stalled, the creator takes the whole deposit back after the signed deadline.
    ///         After the deadline the signed parameters are void on every chain, so no launch can follow.
    function reclaim(bytes32 lh) external nonReentrant {
        Escrow storage e = escrows[lh];
        if (e.state != State.Processing) revert BadEscrow();
        if (msg.sender != e.creator) revert NotCreator();
        if (block.timestamp <= e.deadline) revert TooEarly();
        e.state = State.Refunded;
        _send(e.creator, e.amount);
        emit Reclaimed(lh, e.creator, e.amount);
    }

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

    /// @notice Launch the token on this chain. Relayer only. On the origin chain it settles the escrow; elsewhere the
    ///         fee was already paid on the origin chain.
    function launch(LaunchParams calldata p, bytes calldata creatorSig, int24 startTick, bytes calldata signerSig)
        external
        nonReentrant
        onlyRelayer
        returns (address token)
    {
        if (paused) revert Paused();
        _validate(p);
        bytes32 lh = launchHash(p);
        _verify(lh, p.creator, creatorSig, startTick, signerSig);
        uint256 devBuy = _settleEscrow(p, lh);

        Result memory r;
        r.launchHash = lh;
        r.startTick = startTick;
        token = _deploy(p, startTick, devBuy, r);
        r.token = token;

        // LayerZero: wire the peers and routes, then seal them forever
        _wire(token, p);

        // pay out the launch fee (origin chain only)
        if (p.originChainId == block.chainid && launchFee > 0) {
            uint256 toRelayer = (launchFee * relayerFeeBps) / BPS;
            if (toRelayer > 0) _send(relayer, toRelayer);
            if (launchFee > toRelayer) _send(treasury, launchFee - toRelayer);
        }
        _emitLaunched(p, r);
    }

    struct Result {
        address token;
        bytes32 launchHash;
        bytes32 poolId;
        int24 startTick;
        uint256 devBuyNative;
        uint256 devBuyTokens;
    }

    function _validate(LaunchParams calldata p) private view {
        if (block.timestamp > p.deadline) revert Expired();
        if (
            p.creator == address(0) || p.taxBps < 100 || p.taxBps > 1000 || p.taxBps % 100 != 0
                || uint256(p.toCreator) + p.toHolders + p.toBurn + p.toPool != BPS
                || bytes(p.name).length == 0 || bytes(p.name).length > 32 || bytes(p.symbol).length == 0
                || bytes(p.symbol).length > 10 || bytes(p.uri).length > 512
        ) revert InvalidParams();
    }

    function _verify(bytes32 lh, address creator, bytes calldata creatorSig, int24 startTick, bytes calldata signerSig)
        private
        view
    {
        if (!SignatureChecker.isValidSignatureNow(creator, creatorDigest(lh), creatorSig)) revert BadSignature();
        if (ECDSA.recover(quoteDigest(lh, startTick), signerSig) != signer) revert BadSignature();
        if (startTick % HeptadKey.TICK_SPACING != 0 || startTick < minTick || startTick > maxTick) revert BadPrice();
    }

    /// @dev On the origin chain the deposit must be in `Processing`; it is consumed here. Elsewhere there is no escrow.
    function _settleEscrow(LaunchParams calldata p, bytes32 lh) private returns (uint256 devBuy) {
        if (p.originChainId != block.chainid) return 0;
        Escrow storage e = escrows[lh];
        if (e.state != State.Processing || e.creator != p.creator || e.devBuy != p.devBuy) revert BadEscrow();
        e.state = State.Done;
        devBuy = e.devBuy;
    }

    /// @dev token (CREATE2: same address on every chain) + tax config + pool + locked liquidity + first buy
    function _deploy(LaunchParams calldata p, int24 startTick, uint256 devBuy, Result memory r)
        private
        returns (address token)
    {
        token = deployer.deploy(p.salt, p.name, p.symbol, p.creator);
        isHeptadToken[token] = true;
        allTokens.push(token);

        hook.registerToken(token, p.creator, p.taxBps, p.toCreator, p.toHolders, p.toBurn, p.toPool);
        PoolKey memory key = token.keyFor(IHooks(address(hook)));
        startTickOf[token] = startTick;
        poolManager.initialize(key, TickMath.getSqrtPriceAtTick(startTick));

        bytes memory res = poolManager.unlock(
            abi.encode(LaunchCtx({token: token, creator: p.creator, devBuy: devBuy, startTick: startTick, key: key}))
        );
        (r.devBuyTokens, r.devBuyNative) = abi.decode(res, (uint256, uint256));
        r.poolId = PoolId.unwrap(key.toId());
    }

    function _emitLaunched(LaunchParams calldata p, Result memory r) private {
        emit TokenLaunched(
            r.token, p.creator, p.taxBps, r.launchHash, r.poolId, r.startTick, r.devBuyNative, r.devBuyTokens, p.originChainId
        );
        emit TokenMetadata(r.token, p.name, p.symbol, p.uri);
    }

    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        LaunchCtx memory c = abi.decode(data, (LaunchCtx));

        // single-sided token liquidity: token is currency1 -> [MIN_TICK, startTick]
        int24 lower = (TickMath.MIN_TICK / HeptadKey.TICK_SPACING) * HeptadKey.TICK_SPACING;
        int24 upper = c.startTick;
        uint160 sqrtLower = TickMath.getSqrtPriceAtTick(lower);
        uint160 sqrtUpper = TickMath.getSqrtPriceAtTick(upper);
        uint256 liq = FullMath.mulDiv(TOTAL_SUPPLY, Q96, uint256(sqrtUpper) - uint256(sqrtLower));
        liq -= liq / 1e12 + 1; // headroom so rounding-up in the pool manager can never exceed the supply

        (BalanceDelta d,) = poolManager.modifyLiquidity(
            c.key,
            ModifyLiquidityParams({tickLower: lower, tickUpper: upper, liquidityDelta: int256(liq), salt: bytes32(0)}),
            ""
        );
        require(d.amount1() < 0 && d.amount0() == 0, "bad liquidity delta");
        poolManager.sync(Currency.wrap(c.token));
        IERC20(c.token).transfer(address(poolManager), uint128(-d.amount1()));
        poolManager.settle();

        // creator's first buy: the hook does not tax swaps made by this factory
        uint256 boughtTokens;
        uint256 spent;
        if (c.devBuy > 0) {
            poolManager.settle{value: c.devBuy}();
            BalanceDelta s = poolManager.swap(
                c.key,
                SwapParams({
                    zeroForOne: true, amountSpecified: -int256(c.devBuy), sqrtPriceLimitX96: TickMath.MIN_SQRT_PRICE + 1
                }),
                ""
            );
            spent = uint128(-s.amount0());
            boughtTokens = uint128(s.amount1());
            poolManager.take(Currency.wrap(c.token), c.creator, boughtTokens);
            if (c.devBuy > spent) poolManager.take(CurrencyLibrary.ADDRESS_ZERO, c.creator, c.devBuy - spent);
        }

        // burn the rounding dust left from the liquidity math
        uint256 dust = IERC20(c.token).balanceOf(address(this));
        if (dust > 0) HeptadToken(c.token).burn(dust);

        return abi.encode(boughtTokens, spent);
    }

    receive() external payable {}

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

    /// @dev The token address of this launch on a remote chain, predicted from that chain's registered deployer and
    ///      factory. Virtual only so tests can simulate two chains inside one EVM.
    function _peerOf(address, uint32 eid, LaunchParams calldata p) internal view virtual returns (address) {
        Remote memory rm = remotes[eid];
        return deployer.predictRemote(rm.deployer, rm.factory, p.name, p.symbol, p.creator, p.salt);
    }

    /// @dev Peers, pinned libraries, verifiers and executor, enforced gas; then drop the delegate role and ownership.
    function _wire(address token, LaunchParams calldata p) private {
        Route storage r = _route;
        uint256 n = r.paths.length;
        HeptadToken t = HeptadToken(token);
        if (n > 0) {
            if (!remotesLocked) revert RemotesNotReady();
            ILZEndpointPin ep = ILZEndpointPin(lzEndpoint);
            EnforcedOptionParam[] memory eo = new EnforcedOptionParam[](n);
            bytes memory opt = OptionsBuilder.newOptions().addExecutorLzReceiveOption(r.lzReceiveGas, 0);
            for (uint256 i = 0; i < n; i++) {
                Path storage ph = r.paths[i];
                uint32 eid = ph.eid;
                t.setPeer(eid, bytes32(uint256(uint160(_peerOf(token, eid, p)))));
                eo[i] = EnforcedOptionParam({eid: eid, msgType: 1, options: opt});
                if (ph.sendLib != address(0)) {
                    ep.setSendLibrary(token, eid, ph.sendLib);
                    ep.setReceiveLibrary(token, eid, ph.recvLib, 0);
                    LZSetConfigParam[] memory sp = new LZSetConfigParam[](2);
                    sp[0] = LZSetConfigParam(eid, 1, abi.encode(LZExecutorConfig(ph.maxMessageSize, ph.executor)));
                    sp[1] = LZSetConfigParam(eid, 2, abi.encode(_uln(ph.sendConfirmations, ph.sendDvns)));
                    ep.setConfig(token, ph.sendLib, sp);
                    LZSetConfigParam[] memory rp = new LZSetConfigParam[](1);
                    rp[0] = LZSetConfigParam(eid, 2, abi.encode(_uln(ph.recvConfirmations, ph.recvDvns)));
                    ep.setConfig(token, ph.recvLib, rp);
                }
            }
            t.setEnforcedOptions(eo);
        }
        t.setDelegate(DEAD);
        t.renounceOwnership();
    }

    function _uln(uint64 confirmations, address[] memory dvns) private pure returns (LZUlnConfig memory u) {
        u.confirmations = confirmations;
        u.requiredDVNCount = uint8(dvns.length);
        u.requiredDVNs = dvns;
        u.optionalDVNs = new address[](0);
    }

    function _setBounds(int24 lo, int24 hi) private {
        int24 sp = HeptadKey.TICK_SPACING;
        if (lo >= hi || lo % sp != 0 || hi % sp != 0 || lo < TickMath.MIN_TICK + TICK_MARGIN || hi > TickMath.MAX_TICK - TICK_MARGIN) {
            revert InvalidParams();
        }
        minTick = lo;
        maxTick = hi;
        emit TickBoundsChanged(lo, hi);
    }

    function _setRoute(Route memory r) private {
        uint256 n = r.paths.length;
        for (uint256 i = 0; i < n; i++) {
            Path memory ph = r.paths[i];
            if (ph.eid == 0) revert BadRoute();
            if (ph.sendLib != address(0)) {
                if (
                    ph.recvLib == address(0) || ph.executor == address(0) || ph.maxMessageSize == 0
                        || ph.sendConfirmations == 0 || ph.recvConfirmations == 0
                ) revert BadRoute();
                _checkDvns(ph.sendDvns);
                _checkDvns(ph.recvDvns);
            }
        }
        Route storage s = _route;
        s.lzReceiveGas = r.lzReceiveGas;
        delete s.paths;
        for (uint256 i = 0; i < n; i++) {
            Path storage d = s.paths.push();
            d.eid = r.paths[i].eid;
            d.sendLib = r.paths[i].sendLib;
            d.recvLib = r.paths[i].recvLib;
            d.executor = r.paths[i].executor;
            d.maxMessageSize = r.paths[i].maxMessageSize;
            d.sendConfirmations = r.paths[i].sendConfirmations;
            d.recvConfirmations = r.paths[i].recvConfirmations;
            d.sendDvns = r.paths[i].sendDvns;
            d.recvDvns = r.paths[i].recvDvns;
        }
        emit RouteChanged();
    }

    function _checkDvns(address[] memory d) private pure {
        if (d.length == 0 || d.length > 8) revert BadRoute();
        for (uint256 i = 0; i < d.length; i++) {
            if (d[i] == address(0) || (i > 0 && d[i] <= d[i - 1])) revert BadRoute();
        }
    }

    function _send(address to, uint256 amount) private {
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert TransferFailed();
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "v4-core/=lib/v4-core/",
    "solmate/=lib/v4-core/lib/solmate/",
    "@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "@layerzerolabs/oft-evm/=node_modules/@layerzerolabs/oft-evm/",
    "@layerzerolabs/oapp-evm/=node_modules/@layerzerolabs/oapp-evm/",
    "@layerzerolabs/lz-evm-protocol-v2/=node_modules/@layerzerolabs/lz-evm-protocol-v2/",
    "@layerzerolabs/lz-evm-messagelib-v2/=node_modules/@layerzerolabs/lz-evm-messagelib-v2/",
    "@layerzerolabs/test-devtools-evm-foundry/=node_modules/@layerzerolabs/test-devtools-evm-foundry/",
    "solidity-bytes-utils/=node_modules/solidity-bytes-utils/",
    "@layerzerolabs/lz-evm-v1-0.7/=node_modules/@layerzerolabs/lz-evm-v1-0.7/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.