Skip to content
Verified contractPartialMIT

LeverageFactory

Address0x02cb17a3fad7c165da1ced7f43cf49b86a35743c
Balance

0 ETH

 

Transactions

5

 

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,478,350
Creation transaction
0xd9c2662368…fc2b9eb1e4

46 files

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

src/LeverageFactory.sol

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

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "v4-core/interfaces/callback/IUnlockCallback.sol";
import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {SwapParams} from "v4-core/types/PoolOperation.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {IPositionManager} from "v4-periphery/interfaces/IPositionManager.sol";
import {Actions} from "v4-periphery/libraries/Actions.sol";
import {LiquidityAmounts} from "v4-periphery/libraries/LiquidityAmounts.sol";
import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";
import {LibClone} from "solady/utils/LibClone.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {ReentrancyGuard} from "solady/utils/ReentrancyGuard.sol";

import {LeverageToken} from "./LeverageToken.sol";
import {LeverageVault} from "./LeverageVault.sol";
import {LaunchParams, Launch} from "./Types.sol";

interface ILeverageHook {
    function register(PoolKey calldata key, address token, address vault, uint16 feeBps) external;
    function treasury() external view returns (address);
}

interface IERC165 {
    function supportsInterface(bytes4) external view returns (bool);
}

/// @title LeverageFactory
/// @notice One transaction launches a coin for an ERC-721 collection: token (CREATE2), vault
///         (clone), fee registration in the hook, pool initialization, the whole supply as a
///         one-sided Uniswap v4 position against ETH, and an optional initial buy.
/// @dev    The factory holds every LP position NFT. The owner can pull a coin's liquidity to a
///         wallet in one transaction (`pullLiquidity`), or move a position out
///         (`withdrawPosition`); this is disclosed on the site. Fee rates and fee recipients
///         per pool live in the hook and cannot change.
contract LeverageFactory is IUnlockCallback, ReentrancyGuard {
    int24 public constant TICK_SPACING = 100;
    int24 public constant MIN_USABLE_TICK = -887200; // TickMath.MIN_TICK rounded toward 0 to spacing
    uint256 public constant SUPPLY = 1_000_000_000 ether;
    address internal constant DEAD = 0x000000000000000000000000000000000000dEaD;
    bytes4 internal constant ERC721_ID = 0x80ac58cd;
    address internal constant PUNKS = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB;

    IPoolManager public immutable poolManager;
    IPositionManager public immutable positionManager;
    IAllowanceTransfer public immutable permit2;
    address public immutable hook;
    address public immutable vaultImplementation;

    address public owner;
    address public keeper;
    address public market; // Seaport
    address public draws;
    uint256 public launchFee;
    bool public launchEnabled;
    int24 public startTick; // tick the pool opens at; sets the opening market cap

    Launch[] internal _launches;
    mapping(address => uint256) internal _launchIndexPlus1; // token => index + 1
    mapping(address => address[]) internal _tokensOf; // creator => tokens
    mapping(address => uint256[]) internal _byCollection; // collection => launch indexes
    address[] internal _collections;
    mapping(address => uint64) public firstLaunchAt;
    mapping(address => bool) public isVault;
    mapping(address => bool) public verified;

    event Launched(
        address indexed token, address indexed creator, address indexed collection, address vault, uint256 positionId, uint16 feeBps, uint8 policy
    );
    /// @notice Full token metadata (ERC-7572 JSON data URI) in the launch transaction's logs,
    ///         for indexers and terminals that read launch events instead of the token.
    event LaunchMetadata(address indexed token, string name, string symbol, string contractURI);
    event DevBuy(address indexed token, address indexed creator, uint256 ethIn, uint256 tokensOut);
    event OwnerSet(address owner);
    event KeeperSet(address keeper);
    event MarketSet(address market);
    event DrawsSet(address draws);
    event LaunchFeeSet(uint256 fee);
    event LaunchEnabledSet(bool enabled);
    event StartTickSet(int24 tick);
    event VerifiedSet(address collection, bool verified);
    event PositionWithdrawn(address indexed token, uint256 positionId, address to);
    event LiquidityPulled(address indexed token, uint256 positionId, address to, uint256 ethOut, uint256 tokensOut);

    error NotOwner();
    error LaunchClosed();
    error BadValue();
    error BadFee();
    error BadPolicy();
    error NotERC721();
    error BadName();
    error McapChanged();
    error Slippage();
    error NotPoolManager();
    error BadTick();
    error UnknownToken();
    error NoLiquidity();

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

    constructor(
        IPoolManager _poolManager,
        IPositionManager _positionManager,
        IAllowanceTransfer _permit2,
        address _hook,
        address _owner,
        address _keeper,
        address _market,
        uint256 _launchFee,
        int24 _startTick
    ) {
        poolManager = _poolManager;
        positionManager = _positionManager;
        permit2 = _permit2;
        hook = _hook;
        owner = _owner;
        keeper = _keeper;
        market = _market;
        launchFee = _launchFee;
        _setStartTick(_startTick);
        vaultImplementation = address(new LeverageVault());
    }

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

    function treasury() public view returns (address) {
        return ILeverageHook(hook).treasury();
    }

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

    function launchAt(uint256 i) external view returns (Launch memory) {
        return _launches[i];
    }

    function launchOf(address token) external view returns (Launch memory) {
        uint256 ip1 = _launchIndexPlus1[token];
        if (ip1 == 0) revert UnknownToken();
        return _launches[ip1 - 1];
    }

    function isLaunch(address token) external view returns (bool) {
        return _launchIndexPlus1[token] != 0;
    }

    function tokensOf(address creator) external view returns (address[] memory) {
        return _tokensOf[creator];
    }

    function collectionCount() external view returns (uint256) {
        return _collections.length;
    }

    function collectionAt(uint256 i) external view returns (address) {
        return _collections[i];
    }

    function launchesOfCollection(address c) external view returns (uint256[] memory) {
        return _byCollection[c];
    }

    function startSqrtPriceX96() public view returns (uint160) {
        return TickMath.getSqrtPriceAtTick(startTick);
    }

    /// @notice Opening market cap in wei of ETH for the full supply.
    function openingMcap() public view returns (uint256) {
        uint160 s = startSqrtPriceX96();
        return FullMath.mulDiv(FullMath.mulDiv(SUPPLY, 1 << 96, s), 1 << 96, s);
    }

    /// @notice True for ERC-721 contracts, plus the pre-standard CryptoPunks contract,
    ///         which vaults buy through its own onchain market.
    function isERC721(address c) public view returns (bool) {
        if (c == PUNKS) return true;
        if (c.code.length == 0) return false;
        try IERC165(c).supportsInterface(ERC721_ID) returns (bool ok) {
            return ok;
        } catch {
            return false;
        }
    }

    function predictTokenAddress(address creator, bytes32 salt, LaunchParams calldata p) external view returns (address) {
        bytes32 initHash = keccak256(
            abi.encodePacked(type(LeverageToken).creationCode, abi.encode(p.name, p.symbol, p.metadata, p.collection))
        );
        return address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), _salt(creator, salt), initHash)))));
    }

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

    function launch(LaunchParams calldata p)
        external
        payable
        nonReentrant
        returns (address token, address vault, uint256 positionId, uint256 devBuyTokens)
    {
        if (!launchEnabled) revert LaunchClosed();
        if (msg.value < launchFee) revert BadValue();
        if (p.feeBps < 100 || p.feeBps > 500 || p.feeBps % 100 != 0) revert BadFee();
        if (p.policy > 4) revert BadPolicy();
        if (!isERC721(p.collection)) revert NotERC721();
        if (bytes(p.name).length == 0 || bytes(p.name).length > 64) revert BadName();
        if (bytes(p.symbol).length == 0 || bytes(p.symbol).length > 16) revert BadName();
        if (p.expectedOpeningMcap != 0 && p.expectedOpeningMcap != openingMcap()) revert McapChanged();

        token = address(new LeverageToken{salt: _salt(msg.sender, p.salt)}(p.name, p.symbol, p.metadata, p.collection));
        vault = LibClone.clone(vaultImplementation);
        LeverageVault(payable(vault)).initialize(token, p.collection, msg.sender, p.policy);
        isVault[vault] = true;

        PoolKey memory key = PoolKey({
            currency0: Currency.wrap(address(0)),
            currency1: Currency.wrap(token),
            fee: 0,
            tickSpacing: TICK_SPACING,
            hooks: IHooks(hook)
        });
        ILeverageHook(hook).register(key, token, vault, p.feeBps);
        poolManager.initialize(key, startSqrtPriceX96());

        positionId = _mintPosition(key, token);
        emit LaunchMetadata(token, p.name, p.symbol, LeverageToken(token).contractURI());

        // launch fee to treasury, the rest is the initial buy
        uint256 fee = launchFee;
        if (fee > 0) SafeTransferLib.safeTransferETH(treasury(), fee);
        uint256 buyEth = msg.value - fee;
        if (buyEth > 0) {
            devBuyTokens = abi.decode(poolManager.unlock(abi.encode(key, buyEth, msg.sender)), (uint256));
            emit DevBuy(token, msg.sender, buyEth, devBuyTokens);
        }
        if (devBuyTokens < p.devBuyMinTokens) revert Slippage();

        _record(token, vault, p.collection, positionId, p.feeBps, key);
        emit Launched(token, msg.sender, p.collection, vault, positionId, p.feeBps, p.policy);
    }

    function _mintPosition(PoolKey memory key, address token) internal returns (uint256 positionId) {
        SafeTransferLib.safeApprove(token, address(permit2), type(uint256).max);
        permit2.approve(token, address(positionManager), uint160(SUPPLY), uint48(block.timestamp));

        uint160 sqrtLower = TickMath.getSqrtPriceAtTick(MIN_USABLE_TICK);
        uint160 sqrtUpper = TickMath.getSqrtPriceAtTick(startTick);
        uint128 liquidity = LiquidityAmounts.getLiquidityForAmount1(sqrtLower, sqrtUpper, SUPPLY);

        bytes memory actions = abi.encodePacked(uint8(Actions.MINT_POSITION), uint8(Actions.SETTLE_PAIR));
        bytes[] memory params = new bytes[](2);
        params[0] = abi.encode(key, MIN_USABLE_TICK, startTick, uint256(liquidity), uint128(0), uint128(SUPPLY), address(this), bytes(""));
        params[1] = abi.encode(key.currency0, key.currency1);

        positionId = positionManager.nextTokenId();
        positionManager.modifyLiquidities(abi.encode(actions, params), block.timestamp);

        // rounding dust that did not fit in the position is burned
        uint256 dust = LeverageToken(token).balanceOf(address(this));
        if (dust > 0) SafeTransferLib.safeTransfer(token, DEAD, dust);
    }

    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        (PoolKey memory key, uint256 ethIn, address to) = abi.decode(data, (PoolKey, uint256, address));
        BalanceDelta d = poolManager.swap(
            key,
            SwapParams({zeroForOne: true, amountSpecified: -int256(ethIn), sqrtPriceLimitX96: TickMath.MIN_SQRT_PRICE + 1}),
            ""
        );
        uint256 owed = uint256(int256(-d.amount0()));
        uint256 out = uint256(int256(d.amount1()));
        poolManager.settle{value: owed}();
        poolManager.take(key.currency1, to, out);
        // a buy that hit the price limit leaves ETH unspent: refund it
        if (owed < ethIn) SafeTransferLib.safeTransferETH(to, ethIn - owed);
        return abi.encode(out);
    }

    function _record(address token, address vault, address collection, uint256 positionId, uint16 feeBps, PoolKey memory key)
        internal
    {
        uint256 idx = _launches.length;
        _launches.push(Launch(token, msg.sender, vault, collection, positionId, feeBps, uint64(block.timestamp), key));
        _launchIndexPlus1[token] = idx + 1;
        _tokensOf[msg.sender].push(token);
        if (_byCollection[collection].length == 0) {
            _collections.push(collection);
            firstLaunchAt[collection] = uint64(block.timestamp);
        }
        _byCollection[collection].push(idx);
    }

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

    // ---------------------------------------------------------------- owner

    function setOwner(address o) external onlyOwner {
        owner = o;
        emit OwnerSet(o);
    }

    function setKeeper(address k) external onlyOwner {
        keeper = k;
        emit KeeperSet(k);
    }

    function setMarket(address m) external onlyOwner {
        market = m;
        emit MarketSet(m);
    }

    function setDraws(address d) external onlyOwner {
        draws = d;
        emit DrawsSet(d);
    }

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

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

    function setStartTick(int24 t) external onlyOwner {
        _setStartTick(t);
    }

    function setVerified(address c, bool v) external onlyOwner {
        verified[c] = v;
        emit VerifiedSet(c, v);
    }

    /// @notice Disclosed owner control: move a coin's LP position NFT out of the factory.
    function withdrawPosition(address token, address to) external onlyOwner {
        uint256 ip1 = _launchIndexPlus1[token];
        if (ip1 == 0) revert UnknownToken();
        uint256 id = _launches[ip1 - 1].positionId;
        IERC721Transfer(address(positionManager)).transferFrom(address(this), to, id);
        emit PositionWithdrawn(token, id, to);
    }

    /// @notice Liquidity controller: in one transaction, removes all of a coin's liquidity and
    ///         sends the ETH and tokens to `to`. The position NFT stays in the factory, empty.
    function pullLiquidity(address token, address to) external onlyOwner nonReentrant returns (uint256 ethOut, uint256 tokensOut) {
        uint256 ip1 = _launchIndexPlus1[token];
        if (ip1 == 0) revert UnknownToken();
        Launch storage l = _launches[ip1 - 1];
        uint128 liq = positionManager.getPositionLiquidity(l.positionId);
        if (liq == 0) revert NoLiquidity();

        uint256 eth0 = to.balance;
        uint256 tok0 = LeverageToken(token).balanceOf(to);

        bytes memory actions = abi.encodePacked(uint8(Actions.DECREASE_LIQUIDITY), uint8(Actions.TAKE_PAIR));
        bytes[] memory params = new bytes[](2);
        params[0] = abi.encode(l.positionId, uint256(liq), uint128(0), uint128(0), bytes(""));
        params[1] = abi.encode(l.key.currency0, l.key.currency1, to);
        positionManager.modifyLiquidities(abi.encode(actions, params), block.timestamp);

        ethOut = to.balance - eth0;
        tokensOut = LeverageToken(token).balanceOf(to) - tok0;
        emit LiquidityPulled(token, l.positionId, to, ethOut, tokensOut);
    }

    function _setStartTick(int24 t) internal {
        if (t % TICK_SPACING != 0 || t <= MIN_USABLE_TICK || t >= TickMath.MAX_TICK) revert BadTick();
        startTick = t;
        emit StartTickSet(t);
    }

    function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
        return this.onERC721Received.selector;
    }

    receive() external payable {}
}

interface IERC721Transfer {
    function transferFrom(address from, address to, uint256 id) external;
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/src/",
    "solady/=lib/solady/src/",
    "permit2/=lib/permit2/",
    "forge-std/=lib/forge-std/src/",
    "@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "ds-test/=lib/permit2/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
    "hardhat/=lib/v4-periphery/lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/permit2/lib/openzeppelin-contracts/",
    "solmate/=lib/permit2/lib/solmate/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.