Skip to content
Verified contractExactMIT

UpegFactory

Address0x2ca7624d0e9ff6dffec7200347e61b5f6e7c66f8
Balance

0 ETH

 

Transactions

10

 

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
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,004,802
Creation transaction
0xe14179e86b…5677119a8a

61 files

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

src/UpegFactory.sol

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

import {LibClone} from "solady/utils/LibClone.sol";
import {SSTORE2} from "solady/utils/SSTORE2.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";

import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {IHooks} from "v4-core/src/interfaces/IHooks.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {LiquidityAmounts} from "v4-periphery/src/libraries/LiquidityAmounts.sol";
import {Actions} from "v4-periphery/src/libraries/Actions.sol";
import {IPositionManager} from "v4-periphery/src/interfaces/IPositionManager.sol";

import {UpegEngine} from "./UpegEngine.sol";
import {ImageParams} from "./ImageParams.sol";
import {TraitBlobValidator} from "./libraries/TraitBlobValidator.sol";
import {UpegMarketplace} from "./marketplace/UpegMarketplace.sol";

/// @dev Minimal WETH9 interface — only the surface the factory needs.
interface IWETH {
    function deposit() external payable;
    function approve(address spender, uint256 amount) external returns (bool);
    function transfer(address to, uint256 amount) external returns (bool);
    function balanceOf(address) external view returns (uint256);
}

/// @dev ERC-20 surface used for token-side approvals during LP minting.
interface IERC20 {
    function approve(address spender, uint256 amount) external returns (bool);
    function balanceOf(address) external view returns (uint256);
}

/// @dev Permit2 allowance-transfer surface (canonical mainnet contract at
/// 0x000000000022D473030F116dDEE9F6B43aC78BA3).
interface IPermit2 {
    function approve(address token, address spender, uint160 amount, uint48 expiration) external;
}

/// @title UpegFactory
/// @notice Permissionless launchpad entry point. One transaction:
///         1. validate trait blob,
///         2. SSTORE2-write (chunked on slot boundaries),
///         3. deploy ImageParams,
///         4. clone UpegEngine impl + initialise,
///         5. mint full supply, send 10% to the creator,
///         6. wrap msg.value WETH,
///         7. initialise the v4 token/WETH pool,
///         8. seed full-range LP via PositionManager + Permit2 (recipient = LpLocker),
///         9. call engine.start(PoolManager) to enable Upeg minting.
///
/// @dev Factory holds the engine clone's `hook` slot — it's the only address
///      authorised to call `engine.start(...)`. After step 9, that authority
///      is irrelevant (start is one-shot).
contract UpegFactory {
    using PoolIdLibrary for PoolKey;

    // ---------- Errors ----------
    error InvalidLpAmount();
    error InvalidLpBps();
    error TooManyChunks();

    // ---------- Tokenomics constants ----------
    /// @dev LP_WETH and LP_BPS are now per-collection parameters
    /// (see createCollection's lpWeth / lpBps args). Bounds are enforced
    /// against these constants:
    uint128 public constant MIN_LP_WETH = 1e15;     // 0.001 ETH floor
    uint16 public constant MIN_LP_BPS = 5_000;      // ≥ 50% of supply in LP
    uint16 public constant MAX_LP_BPS = 9_900;      // ≤ 99% (1% creator floor)
    uint16 public constant BPS_DENOM = 10_000;

    // ---------- Pool constants ----------
    uint24 public constant LP_FEE_TIER = 10_000; // 1%
    int24 public constant TICK_SPACING = 200;
    /// @dev Empty hook (no afterSwap routing — the engine's _afterTokenTransfer
    /// triggers Upeg mint/burn on every swap-induced transfer naturally).
    IHooks public constant HOOK_ADDRESS = IHooks(address(0));

    // ---------- Chunking constants ----------
    uint256 internal constant MAX_CHUNK_BYTES = 24_000;
    uint256 internal constant MAX_CHUNKS = 4;
    uint256 internal constant MAX_SLOTS = 18;

    // ---------- Immutable wiring ----------
    address public immutable engineImpl;
    address public immutable renderer;
    address public immutable seedProvider;
    address public immutable lpLocker;
    address public immutable poolManager;
    address public immutable positionManager;
    address public immutable permit2;
    address public immutable weth;
    /// @dev EIP-1167 cloned per createCollection — one peg2peg-style
    /// marketplace per collection. Address baked into CollectionCreated.
    address public immutable marketplaceImpl;
    /// @dev Receives marketplace protocol fees from every cloned market.
    address public immutable feeAddress;
    /// @dev Platform admin baked into every engine clone. Holds the maxBuy
    /// bypass key so the launchpad can pull/migrate liquidity in a single
    /// tx. Public, auditable on-chain via every engine's `admin()` getter
    /// and AdminUpdated events. Rotatable per-engine via setAdmin.
    address public immutable platformAdmin;
    /// @dev Chainlink ETH/USD aggregator (8 decimals). Each engine clone
    /// inherits this at init so its `maxUpegsPerBuy()` view can convert
    /// pool spot price to a USD marketcap and step the per-buy cap. Set
    /// to address(0) to disable the marketcap step (engine then falls
    /// back to the lowest tier — cap = 10).
    address public immutable ethUsdFeed;

    // ---------- Events ----------
    /// @dev Note: extended from the v1 signature with `marketplace` so the
    /// indexer learns about the per-collection market without an extra fetch.
    /// `lpTokenId` is the v4 PositionManager NFT id for this collection's
    /// initial LP, and `locked` is true iff the recipient was LpLocker (i.e.
    /// already permanently locked at deploy time).
    event CollectionCreated(
        address indexed token,
        address indexed imageParams,
        PoolId indexed poolId,
        address creator,
        uint256 supply,
        uint128 liquidity,
        address marketplace,
        uint256 lpTokenId,
        bool locked
    );

    constructor(
        address engineImpl_,
        address renderer_,
        address seedProvider_,
        address lpLocker_,
        address poolManager_,
        address positionManager_,
        address permit2_,
        address weth_,
        address marketplaceImpl_,
        address feeAddress_,
        address platformAdmin_,
        address ethUsdFeed_
    ) {
        engineImpl = engineImpl_;
        renderer = renderer_;
        seedProvider = seedProvider_;
        lpLocker = lpLocker_;
        poolManager = poolManager_;
        positionManager = positionManager_;
        permit2 = permit2_;
        weth = weth_;
        marketplaceImpl = marketplaceImpl_;
        feeAddress = feeAddress_;
        platformAdmin = platformAdmin_;
        ethUsdFeed = ethUsdFeed_;
    }

    /// @notice Launch config supplied by the creator at createCollection time.
    struct LaunchConfig {
        string name;
        string symbol;
        uint256 supply;
    }

    /// @notice Deploys a new uPeg collection.
    /// @return token Engine clone address.
    /// @return imageParams ImageParams contract for this collection.
    /// @return poolId v4 pool identifier.
    /// @return liquidity LP liquidity minted (and locked at LpLocker if `lock`).
    /// @return marketplace Per-collection peg2peg-style marketplace clone.
    /// @param lock If true the LP NFT goes to LpLocker in this same tx; if
    /// false it goes to msg.sender, who can later lock it by safeTransferring
    /// the NFT to LpLocker.
    function createCollection(
        bytes calldata traitBlob,
        LaunchConfig calldata cfg,
        bool lock,
        uint128 lpWeth,
        uint16 lpBps
    )
        external
        payable
        returns (
            address token,
            address imageParams,
            PoolId poolId,
            uint128 liquidity,
            address marketplace
        )
    {
        if (msg.value != lpWeth || lpWeth < MIN_LP_WETH) revert InvalidLpAmount();
        if (lpBps < MIN_LP_BPS || lpBps > MAX_LP_BPS) revert InvalidLpBps();

        // 1. Validate, chunk, deploy ImageParams.
        imageParams = _processTraitBlob(traitBlob);

        // 2. Clone + initialise the engine.
        token = _initEngine(cfg, imageParams);

        // 3. Send dev allocation (BPS_DENOM - lpBps), init pool, seed LP, sweep, start.
        address lpRecipient = lock ? lpLocker : msg.sender;
        uint256 lpTokenId = IPositionManager(positionManager).nextTokenId();
        (poolId, liquidity) = _seedPoolAndStart(token, cfg.supply, lpRecipient, lpWeth, lpBps);

        // 4. Clone the marketplace, scoped to this engine. Owner = creator
        //    (manages fee address); fee receiver = launchpad treasury.
        marketplace = _initMarketplace(token);

        emit CollectionCreated(
            token,
            imageParams,
            poolId,
            msg.sender,
            cfg.supply,
            liquidity,
            marketplace,
            lpTokenId,
            lock
        );
    }

    function _initMarketplace(address token) internal returns (address market) {
        market = LibClone.clone(marketplaceImpl);
        UpegMarketplace(market).initialize(token, feeAddress, 0);
    }

    function _processTraitBlob(bytes calldata traitBlob) internal returns (address) {
        TraitBlobValidator.Parsed memory parsed = TraitBlobValidator.validate(traitBlob);
        (address[MAX_CHUNKS] memory chunks, uint256[] memory slotsPacked) =
            _chunkBlob(traitBlob, parsed);
        return _deployImageParams(parsed.header, slotsPacked, chunks);
    }

    function _initEngine(LaunchConfig calldata cfg, address imageParams)
        internal
        returns (address token)
    {
        token = LibClone.clone(engineImpl);
        UpegEngine(token).initialize(
            cfg.name,
            cfg.symbol,
            cfg.supply,
            msg.sender,
            address(this),
            address(this),
            imageParams,
            seedProvider,
            platformAdmin,
            weth,
            ethUsdFeed
        );
    }

    function _seedPoolAndStart(
        address token,
        uint256 supply,
        address lpRecipient,
        uint128 lpWeth,
        uint16 lpBps
    )
        internal
        returns (PoolId poolId, uint128 liquidity)
    {
        // Creator allocation = whatever isn't going into the LP.
        uint256 devAmount = (supply * (BPS_DENOM - lpBps)) / BPS_DENOM;
        UpegEngine(token).transfer(msg.sender, devAmount);

        // Pool key + sqrt price
        PoolKey memory key;
        uint160 sqrtPriceX96;
        uint256 amount0;
        uint256 amount1;
        {
            (Currency c0, Currency c1, uint256 a0, uint256 a1) =
                _orderedCurrencies(token, supply - devAmount, lpWeth);
            sqrtPriceX96 = _initialSqrtPriceX96(a0, a1);
            key = PoolKey({
                currency0: c0,
                currency1: c1,
                fee: LP_FEE_TIER,
                tickSpacing: TICK_SPACING,
                hooks: HOOK_ADDRESS
            });
            amount0 = a0;
            amount1 = a1;
        }
        IPoolManager(poolManager).initialize(key, sqrtPriceX96);
        poolId = key.toId();

        // Wrap + seed LP
        IWETH(weth).deposit{value: lpWeth}();
        liquidity = _seedAndLockLiquidity(key, sqrtPriceX96, amount0, amount1, token, lpRecipient);

        // Sweep dust
        uint256 tokenDust = IERC20(token).balanceOf(address(this));
        if (tokenDust > 0) UpegEngine(token).transfer(msg.sender, tokenDust);
        uint256 wethDust = IWETH(weth).balanceOf(address(this));
        if (wethDust > 0) IWETH(weth).transfer(msg.sender, wethDust);

        // Start. token < weth iff token is currency0 in the PoolKey we
        // built above. The engine needs the poolId + ordering so its
        // `maxUpegsPerBuy()` view can read slot0 and convert sqrtPriceX96
        // into a USD marketcap.
        UpegEngine(token).start(poolManager, PoolId.unwrap(poolId), token < weth);
    }

    /// @dev Approves Permit2 for both currencies, grants PositionManager
    /// allowance through Permit2, computes full-range liquidity for the
    /// supplied amounts at the initial price, and calls modifyLiquidities to
    /// mint a position whose NFT lands at LpLocker.
    function _seedAndLockLiquidity(
        PoolKey memory key,
        uint160 sqrtPriceX96,
        uint256 amount0,
        uint256 amount1,
        address token,
        address lpRecipient
    ) internal returns (uint128 liquidity) {
        _approvePermit2(token, uint48(block.timestamp + 1 hours));
        liquidity = _computeLiquidity(sqrtPriceX96, amount0, amount1);
        _mintPosition(key, liquidity, lpRecipient);
    }

    function _approvePermit2(address token, uint48 deadline) internal {
        IERC20(token).approve(permit2, type(uint256).max);
        IERC20(weth).approve(permit2, type(uint256).max);
        IPermit2(permit2).approve(token, positionManager, type(uint160).max, deadline);
        IPermit2(permit2).approve(weth, positionManager, type(uint160).max, deadline);
    }

    function _computeLiquidity(uint160 sqrtPriceX96, uint256 amount0, uint256 amount1)
        internal
        pure
        returns (uint128)
    {
        return LiquidityAmounts.getLiquidityForAmounts(
            sqrtPriceX96,
            TickMath.getSqrtPriceAtTick(TickMath.minUsableTick(TICK_SPACING)),
            TickMath.getSqrtPriceAtTick(TickMath.maxUsableTick(TICK_SPACING)),
            amount0,
            amount1
        );
    }

    function _mintPosition(PoolKey memory key, uint128 liquidity, address recipient) internal {
        bytes memory actions = abi.encodePacked(
            uint8(Actions.MINT_POSITION), uint8(Actions.SETTLE_PAIR)
        );
        bytes[] memory params = new bytes[](2);
        params[0] = _encodeMintParams(key, liquidity, recipient);
        params[1] = abi.encode(key.currency0, key.currency1);

        IPositionManager(positionManager).modifyLiquidities(
            abi.encode(actions, params),
            block.timestamp + 1 hours
        );
    }

    function _encodeMintParams(PoolKey memory key, uint128 liquidity, address recipient)
        internal
        pure
        returns (bytes memory)
    {
        return abi.encode(
            key,
            TickMath.minUsableTick(TICK_SPACING),
            TickMath.maxUsableTick(TICK_SPACING),
            liquidity,
            type(uint128).max,
            type(uint128).max,
            recipient,
            bytes("")
        );
    }

    /// @dev Greedy chunking state, passed by reference between iterations to
    /// keep the Yul stack shallow.
    struct ChunkState {
        bytes cur;
        uint8 chunkIdx;
        uint256 cursorInChunk;
    }

    /// @dev Greedy slot-boundary chunking. Walks parsed slots in order; if
    /// adding the next slot would push the current chunk past MAX_CHUNK_BYTES,
    /// seal the chunk and start a new one. Header always lives in chunk 0.
    function _chunkBlob(bytes calldata blob, TraitBlobValidator.Parsed memory parsed)
        internal
        returns (address[MAX_CHUNKS] memory chunks, uint256[] memory slotsPacked)
    {
        uint256 numSlots = parsed.header.numSlots;
        slotsPacked = new uint256[](numSlots);

        ChunkState memory st;
        st.cur = bytes(blob[0:parsed.header.slotsStartOffset]);
        st.cursorInChunk = parsed.header.slotsStartOffset;

        for (uint256 s = 0; s < numSlots; s++) {
            slotsPacked[s] = _appendSlot(blob, parsed.slots[s], st, chunks);
        }

        chunks[st.chunkIdx] = SSTORE2.write(st.cur);
    }

    /// @dev Appends one slot's bytes to the current chunk buffer, sealing
    /// and rotating when the size cap would be exceeded. Mutates `st` in
    /// place.
    function _appendSlot(
        bytes calldata blob,
        TraitBlobValidator.ParsedSlot memory slot,
        ChunkState memory st,
        address[MAX_CHUNKS] memory chunks
    ) internal returns (uint256 packed) {
        if (st.cur.length + slot.length > MAX_CHUNK_BYTES) {
            chunks[st.chunkIdx] = SSTORE2.write(st.cur);
            st.chunkIdx += 1;
            if (st.chunkIdx >= MAX_CHUNKS) revert TooManyChunks();
            st.cur = "";
            st.cursorInChunk = 0;
        }
        packed = _packSlot(slot, st.chunkIdx, st.cursorInChunk);
        st.cur = bytes.concat(
            st.cur,
            bytes(blob[slot.startOffset:slot.startOffset + slot.length])
        );
        st.cursorInChunk += slot.length;
    }

    /// @dev Constructs ImageParams in a separate frame to keep
    /// `createCollection`'s stack within Yul limits.
    function _deployImageParams(
        TraitBlobValidator.ParsedHeader memory h,
        uint256[] memory slotsPacked,
        address[MAX_CHUNKS] memory chunks
    ) internal returns (address) {
        return address(
            new ImageParams(
                ImageParams.InitArgs({
                    renderer: renderer,
                    spriteSize: h.spriteSize,
                    colorsCount: h.colorsCount,
                    backgroundColorsCount: h.backgroundColorsCount,
                    colorPaletteOffset: h.colorPaletteOffset,
                    bgPaletteOffset: h.bgPaletteOffset,
                    baseSpriteOffset: h.baseSpriteOffset,
                    baseSpriteLen: h.baseSpriteLen,
                    slotsPacked: slotsPacked,
                    chunks: chunks
                })
            )
        );
    }

    /// @dev Packs one parsed slot into the uint256 layout `ImageParams._slots`
    /// expects: chance | variantCount | chunkIdx | spriteOffset | nameOffset | nameLen.
    function _packSlot(
        TraitBlobValidator.ParsedSlot memory slot,
        uint8 chunkIdx,
        uint256 cursorInChunk
    ) internal pure returns (uint256 packed) {
        // sprite block starts after: 1 nameLen + nameLen + 1 chanceToAppear bytes.
        uint256 spriteStart = cursorInChunk + 2 + slot.nameLen;
        packed = uint256(slot.chanceToAppear) & 0xFF;
        packed |= uint256(slot.variantCount) << 8;
        packed |= uint256(chunkIdx) << 16;
        packed |= (spriteStart & 0xFFFFFF) << 24;
        packed |= uint256(slot.nameOffset) << 48;
        packed |= uint256(slot.nameLen) << 64;
    }

    /// @dev Sorts (token, weth) into (currency0, currency1) and aligns
    /// matching amounts (lpSupply on the token side, lpWeth on the WETH side).
    function _orderedCurrencies(address token, uint256 lpSupply, uint128 lpWeth)
        internal
        view
        returns (Currency currency0, Currency currency1, uint256 amount0, uint256 amount1)
    {
        if (token < weth) {
            currency0 = Currency.wrap(token);
            currency1 = Currency.wrap(weth);
            amount0 = lpSupply;
            amount1 = lpWeth;
        } else {
            currency0 = Currency.wrap(weth);
            currency1 = Currency.wrap(token);
            amount0 = lpWeth;
            amount1 = lpSupply;
        }
    }

    /// @dev Initial sqrtPriceX96 = sqrt(amount1 / amount0) << 96, computed in
    /// integer arithmetic as sqrt((amount1 << 192) / amount0). Clamped to the
    /// usable range so PoolManager.initialize won't revert on edge supplies.
    function _initialSqrtPriceX96(uint256 amount0, uint256 amount1)
        internal
        pure
        returns (uint160)
    {
        uint256 ratioX192 = FixedPointMathLib.fullMulDiv(amount1, 1 << 192, amount0);
        uint256 sqrtPriceX96 = FixedPointMathLib.sqrt(ratioX192);
        if (sqrtPriceX96 < TickMath.MIN_SQRT_PRICE) sqrtPriceX96 = TickMath.MIN_SQRT_PRICE;
        if (sqrtPriceX96 > TickMath.MAX_SQRT_PRICE) sqrtPriceX96 = TickMath.MAX_SQRT_PRICE;
        return uint160(sqrtPriceX96);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "solady/=lib/solady/src/",
    "@solady/=lib/solady/src/",
    "v4-core/=lib/v4-core/",
    "v4-periphery/=lib/v4-periphery/",
    "@uniswap/v4-core/=lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "forge-std/=lib/forge-std/src/",
    "@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/",
    "erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "solmate/=lib/v4-core/lib/solmate/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.