Skip to content
Verified contractPartialMIT

ZipRouter

Address0x696dce48babd22c15e5e11a91789ac5fd699d2b7
Balance

0 ETH

 

Transactions

15

 

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,305,621
Creation transaction
0x3d84d3565f…7fddab15ae

97 files

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

src/ZipRouter.sol

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

/*
 ███████╗██╗██████╗ ██████╗ ███████╗██████╗
 ╚══███╔╝██║██╔══██╗██╔══██╗██╔════╝██╔══██╗
   ███╔╝ ██║██████╔╝██████╔╝█████╗  ██║  ██║
  ███╔╝  ██║██╔═══╝ ██╔═══╝ ██╔══╝  ██║  ██║
 ███████╗██║██║     ██║     ███████╗██████╔╝
 ╚══════╝╚═╝╚═╝     ╚═╝     ╚══════╝╚═════╝  .fun

 launch on solana. get zipped everywhere.

 zipped.fun is pump.fun with one difference: coins launch and trade on a bonding curve on Solana, and when the curve
 fills the coin graduates into PumpSwap AND gets zipped out to Ethereum, Base, Robinhood Chain and BNB Chain at the
 same price. One coin across five chains (LayerZero OFT), one address on every EVM chain.

   Solana         pump.fun's curve and prices, PumpSwap at graduation
   EVM chains     opened by the relay at the graduation price, 18.75M each, on Uniswap v4
   Bridge         move the coin between any two of the five chains

 website   https://zipped.fun

 This file: ZipRouter
*/

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "v4-core/interfaces/callback/IUnlockCallback.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 {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

import {ZipFactory} from "./ZipFactory.sol";

/**
 * @title ZipRouter
 * @notice Buy and sell an omnichain coin on this chain with its pair, and collect its LP fees.
 *
 * Every coin's pool is a plain hookless Uniswap v4 pool, so any v4 router can trade it; this one just knows each
 * coin's pool from the factory and takes the pair as native value or as an ERC-20 (approve first). It also runs fee
 * collection: the factory hands it a launch's LP fees (both currencies, never liquidity), it sells the coin side into
 * the pool for the pair, and pays 80% to the launch's fee recipient and 20% to the treasury. A recipient that cannot
 * take a push (no receive function, blocklisted by the stablecoin) is owed it instead, so a collect never blocks.
 *
 * Constructor argument = the factory only, so the router sits at the same address on every chain.
 */
contract ZipRouter is ReentrancyGuard, IUnlockCallback {
    using SafeERC20 for IERC20;

    address public constant NATIVE = address(0);
    uint16 public constant PLATFORM_CUT_BPS = 2_000; // 20% of trading fees

    ZipFactory public immutable factory;

    /// @dev fees owed to a recipient whose push failed, per asset (address(0) = native)
    mapping(address asset => mapping(address to => uint256)) public owed;

    event Bought(address indexed token, address indexed to, uint256 pairIn, uint256 tokensOut);
    event Sold(address indexed token, address indexed to, uint256 tokensIn, uint256 pairOut);
    event FeesCollected(address indexed token, uint256 pairFees, uint256 tokenFees, uint256 tokenFeesSoldFor, uint256 toCreator, uint256 toPlatform);
    event Owed(address indexed asset, address indexed to, uint256 amount);

    error UnknownToken();
    error NotPoolManager();
    error SlippageExceeded();
    error WrongValue();
    error NativeTransferFailed();

    constructor(address factory_) {
        factory = ZipFactory(payable(factory_));
    }

    // ----------------------------- trading -----------------------------

    /// @notice Buy `token` with its pair: native as `msg.value`, or an ERC-20 pair's `amountIn` pulled from you.
    function buy(address token, uint256 amountIn, uint256 minOut, address to) external payable nonReentrant returns (uint256 out) {
        ZipFactory.Launch memory l = _launch(token);
        address quote = _quote(l);
        if (quote == NATIVE) {
            amountIn = msg.value;
        } else {
            if (msg.value != 0) revert WrongValue();
            amountIn = _pull(quote, amountIn);
        }
        out = _swap(l, true, amountIn, minOut, to);
        emit Bought(token, to, amountIn, out);
    }

    /// @notice Sell `amountIn` of `token` for its pair (approve this router first).
    function sell(address token, uint256 amountIn, uint256 minOut, address to) external nonReentrant returns (uint256 out) {
        ZipFactory.Launch memory l = _launch(token);
        IERC20(token).safeTransferFrom(msg.sender, address(this), amountIn);
        out = _swap(l, false, amountIn, minOut, to);
        emit Sold(token, to, amountIn, out);
    }

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

    /// @notice Collect a launch's LP fees on this chain. Anyone may call. Coin-side fees are sold for the pair;
    /// 20% of the pair goes to the treasury and 80% to the fee recipient.
    function collectFees(address token) external nonReentrant returns (uint256 toCreator, uint256 toPlatform) {
        ZipFactory.Launch memory l = _launch(token);
        address quote = _quote(l);

        uint256 pairBefore = _balance(quote);
        uint256 tokenBefore = IERC20(token).balanceOf(address(this));
        factory.takeFees(token);
        uint256 pairFees = _balance(quote) - pairBefore;
        uint256 tokenFees = IERC20(token).balanceOf(address(this)) - tokenBefore;

        uint256 soldFor;
        if (tokenFees != 0) soldFor = _swap(l, false, tokenFees, 0, address(this));
        uint256 total = pairFees + soldFor;
        toPlatform = total * PLATFORM_CUT_BPS / 10_000;
        toCreator = total - toPlatform;
        if (toPlatform != 0) _payOrOwe(quote, factory.treasury(), toPlatform);
        if (toCreator != 0) _payOrOwe(quote, l.feeRecipient, toCreator);
        emit FeesCollected(token, pairFees, tokenFees, soldFor, toCreator, toPlatform);
    }

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

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

    /// @dev buy = pair in, coin out; else coin in, pair out. The input is already held by this router.
    function _swap(ZipFactory.Launch memory l, bool isBuy, uint256 amountIn, uint256 minOut, address to)
        internal
        returns (uint256)
    {
        bool zeroForOne = isBuy != l.tokenIsCurrency0;
        return abi.decode(factory.poolManager().unlock(abi.encode(zeroForOne, l.key, amountIn, minOut, to)), (uint256));
    }

    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        IPoolManager pm = factory.poolManager();
        if (msg.sender != address(pm)) revert NotPoolManager();
        (bool zeroForOne, PoolKey memory key, uint256 amountIn, uint256 minOut, address recipient) =
            abi.decode(data, (bool, PoolKey, uint256, uint256, address));

        BalanceDelta d = pm.swap(
            key,
            SwapParams({
                zeroForOne: zeroForOne,
                amountSpecified: -int256(amountIn),
                sqrtPriceLimitX96: zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1
            }),
            ""
        );
        uint256 paid = uint256(uint128(-(zeroForOne ? d.amount0() : d.amount1())));
        uint256 out = uint256(uint128(zeroForOne ? d.amount1() : d.amount0()));
        if (out < minOut) revert SlippageExceeded();

        (Currency cin, Currency cout) = zeroForOne ? (key.currency0, key.currency1) : (key.currency1, key.currency0);
        address tin = Currency.unwrap(cin);
        if (tin == NATIVE) {
            pm.settle{value: paid}();
        } else {
            pm.sync(cin);
            IERC20(tin).safeTransfer(address(pm), paid);
            pm.settle();
        }
        pm.take(cout, recipient, out);
        // the price limit stopped the swap short: hand back the unspent input
        if (paid < amountIn && recipient != address(this)) _send(tin, recipient, amountIn - paid);
        return abi.encode(out);
    }

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

    function _launch(address token) internal view returns (ZipFactory.Launch memory l) {
        l = factory.getLaunch(token);
        if (l.token == address(0)) revert UnknownToken();
    }

    /// @dev the launch's pair token on this chain (address(0) = native)
    function _quote(ZipFactory.Launch memory l) internal pure returns (address) {
        return Currency.unwrap(l.tokenIsCurrency0 ? l.key.currency1 : l.key.currency0);
    }

    function _pull(address asset, uint256 amount) internal returns (uint256) {
        uint256 before = IERC20(asset).balanceOf(address(this));
        IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);
        return IERC20(asset).balanceOf(address(this)) - before;
    }

    function _balance(address asset) internal view returns (uint256) {
        return asset == NATIVE ? address(this).balance : IERC20(asset).balanceOf(address(this));
    }

    function _send(address asset, address to, uint256 amount) internal {
        if (amount == 0) return;
        if (asset == NATIVE) {
            (bool ok,) = to.call{value: amount}("");
            if (!ok) revert NativeTransferFailed();
        } else {
            IERC20(asset).safeTransfer(to, amount);
        }
    }

    /// @dev fee pushes never block a collect: a recipient that cannot take them is owed them
    function _payOrOwe(address asset, address to, uint256 amount) internal {
        bool ok;
        if (asset == NATIVE) {
            (ok,) = to.call{value: amount, gas: 50_000}("");
        } else {
            (bool called, bytes memory ret) = asset.call(abi.encodeCall(IERC20.transfer, (to, amount)));
            ok = called && (ret.length == 0 || (ret.length == 32 && abi.decode(ret, (bool))));
        }
        if (!ok) {
            owed[asset][to] += amount;
            emit Owed(asset, to, amount);
        }
    }

    /// @dev native from swaps, fee collection and PoolManager refunds
    receive() external payable {}
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
    "v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/src/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "forge-std/=lib/forge-std/src/",
    "@layerzerolabs/=node_modules/@layerzerolabs/",
    "solidity-bytes-utils/=node_modules/solidity-bytes-utils/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.