Skip to content
Verified contractExactMIT

UniFunToken

Address0xf82d3883ee8ad2f81e8d3df58f685180cd889b3c
Balance

0 ETH

 

Transactions

490

 

Compiler

solc 0.8.26

 

Same code

5 more contracts

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 50 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,401,873
Creation transaction
0x93b3d91437…d28fc37227

contracts/UniFunToken.sol

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

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

interface IUniFunMirror {
    function emitTransfer(address from, address to, uint256 tokenId) external;
    function emitApproval(address owner, address approved, uint256 tokenId) external;
}

/// @dev Hook dividend settlement interface (Token → Hook callback only).
interface IUniFunHookDividend {
    /// @notice Batch-settle two users; pass (addr, 0, 0) for skipNFT addresses so Hook skips them.
    function settleRewardsBatch(
        address token,
        address from, uint256 fromOld, uint256 fromNew,
        address to,   uint256 toOld,   uint256 toNew
    ) external;
}

/// @title  UniFunToken
/// @notice ERC-20 token where each full unit (1e18) is 1:1 bound to a unique NFT.
///
///         Transfer rules:
///         - Token transfer: top-of-stack (most recently minted) NFT moves with the tokens.
///         - NFT transfer (via Mirror): moves exactly 1e18 ERC-20 tokens together.
///         - Addresses in `skipNFT` (e.g. Uniswap pool) never hold NFTs; tokens entering the pool burn NFTs,
///           tokens leaving the pool mint new NFTs.
///
///         tokenURI is fully on-chain (base64 HTML + SVG), rendered by the TokenURIRenderer contract.
///
///         Optional features (configured at launch):
///         - holdTime: minimum hold duration (seconds) after NFT mint before sell/burn; 0 = disabled.
///         - dividendEnabled: participate in Hook 2% trading dividends; when enabled, each NFT balance change
///           calls Hook.settleRewards() to update the reward ledger.
contract UniFunToken {
    // ─── ERC-20 metadata ─────────────────────────────────────────────────────

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

    // ─── ERC-20 state ────────────────────────────────────────────────────────

    uint256 public totalSupply;
    uint256 public immutable maxSupply;

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

    // ─── NFT state ───────────────────────────────────────────────────────────

    uint256 private _nextId = 1;

    /// @notice Total NFTs minted so far (monotonically increasing, not reduced on burn).
    uint256 public nftMinted;

    /// @notice Permanent seed per tokenId; renderer uses seed to generate unique artwork.
    mapping(uint256 => uint256) public seeds;

    mapping(uint256 => address)   private _ownerOf;
    mapping(address => uint256[]) private _ownedIds;
    mapping(address => mapping(uint256 => uint256)) private _ownedIndex;
    mapping(uint256 => address)   private _tokenApprovals;
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    // ─── Generative art script (Art Blocks compatible, on-chain storage) ─────

    string public script;
    string public scriptType;
    string public scriptCdnUrl;

    /// @notice Project social links (written at launch for OpenSea metadata).
    string public website;
    string public twitter;

    event ScriptUpdated(string scriptType, address updatedBy);

    // ─── Optional: minimum hold duration ─────────────────────────────────────

    /// @notice NFT must be held for holdTime seconds after mint before sell/burn; 0 = disabled.
    uint256 public holdTime;

    /// @notice Mint timestamp per tokenId; not written when holdTime=0 to save gas.
    mapping(uint256 => uint256) public mintTime;

    // ─── Optional: NFT-holder dividends ──────────────────────────────────────

    /// @notice Whether Hook dividend callbacks are enabled.
    bool    public dividendEnabled;

    /// @notice Hook contract address for settleRewards callbacks.
    address public hookAddr;

    // ─── Configuration ───────────────────────────────────────────────────────

    address public immutable factory;
    address public renderer;
    address public owner;
    address public mirror;

    mapping(address => bool) public skipNFT;

    // ─── ERC-20 events ───────────────────────────────────────────────────────

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);

    // ─── Errors ──────────────────────────────────────────────────────────────

    error Unauthorized();
    error AlreadyInitialized();
    error InsufficientBalance();
    error InsufficientAllowance();
    error ExceedsMaxSupply();
    error NonexistentToken();
    error UnsafeReceiver();
    error HoldPeriodNotEnded();

    // ─── Modifiers ───────────────────────────────────────────────────────────

    modifier onlyFactory() {
        if (msg.sender != factory) revert Unauthorized();
        _;
    }

    modifier onlyMirror() {
        if (msg.sender != mirror) revert Unauthorized();
        _;
    }

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

    // ─── Constructor ─────────────────────────────────────────────────────────

    constructor(
        string memory _name,
        string memory _symbol,
        uint256 _maxSupply,
        address _factory,
        address _owner,
        address _renderer
    ) {
        name      = _name;
        symbol    = _symbol;
        maxSupply = _maxSupply;
        factory   = _factory;
        owner     = _owner;
        renderer  = _renderer;
        skipNFT[address(0)] = true;
    }

    // ─── Factory initialization ──────────────────────────────────────────────

    function initMirror(address _mirror) external onlyFactory {
        if (mirror != address(0)) revert AlreadyInitialized();
        mirror = _mirror;
    }

    /// @notice Factory calls once at launch to set optional feature parameters.
    /// @param _holdTime        Minimum hold duration (seconds); 0 = disabled.
    /// @param _dividendEnabled Whether to enable dividend callbacks.
    /// @param _hookAddr        Hook contract address (address(0) when enableDividend=false).
    function initFeatures(uint256 _holdTime, bool _dividendEnabled, address _hookAddr) external onlyFactory {
        holdTime        = _holdTime;
        dividendEnabled = _dividendEnabled;
        hookAddr        = _hookAddr;
    }

    /// @notice Factory calls once at launch to set optional social links.
    function initSocial(string calldata _website, string calldata _twitter) external onlyFactory {
        website = _website;
        twitter = _twitter;
    }

    function setSkipNFT(address addr, bool skip) external onlyOwnerOrFactory {
        skipNFT[addr] = skip;
    }

    function setScript(
        string calldata _script,
        string calldata _scriptType,
        string calldata _cdnUrl
    ) external onlyOwnerOrFactory {
        script       = _script;
        scriptType   = _scriptType;
        scriptCdnUrl = _cdnUrl;
        emit ScriptUpdated(_scriptType, msg.sender);
    }

    function setRenderer(address _renderer) external onlyFactory {
        renderer = _renderer;
    }

    function ownedIds(address addr) external view returns (uint256[] memory) {
        return _ownedIds[addr];
    }

    function bringToTop(address user, uint256 tokenId) external onlyFactory {
        if (_ownerOf[tokenId] != user) revert NonexistentToken();
        uint256[] storage stack = _ownedIds[user];
        uint256 len = stack.length;
        uint256 pos = _ownedIndex[user][tokenId];
        uint256 lastPos = len - 1;
        if (pos == lastPos) return;
        uint256 lastTokenId = stack[lastPos];
        stack[lastPos] = tokenId;
        stack[pos] = lastTokenId;
        _ownedIndex[user][tokenId] = lastPos;
        _ownedIndex[user][lastTokenId] = pos;
    }

    function mintInitial(address to, uint256 amount) external onlyFactory {
        if (totalSupply != 0) revert AlreadyInitialized();
        if (amount > maxSupply) revert ExceedsMaxSupply();
        _mintERC20(to, amount);
    }

    // ─── ERC-20 ──────────────────────────────────────────────────────────────

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

    function transferFrom(address from, address to, uint256 amount) external returns (bool) {
        _spendAllowance(from, msg.sender, amount);
        _transfer(from, to, amount);
        return true;
    }

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

    // ─── ERC-721 queries ─────────────────────────────────────────────────────

    function ownerOf(uint256 tokenId) public view returns (address o) {
        o = _ownerOf[tokenId];
        if (o == address(0)) revert NonexistentToken();
    }

    function nftBalanceOf(address addr) public view returns (uint256) {
        return _ownedIds[addr].length;
    }

    function getApproved(uint256 tokenId) public view returns (address) {
        if (_ownerOf[tokenId] == address(0)) revert NonexistentToken();
        return _tokenApprovals[tokenId];
    }

    function isApprovedForAll(address addr, address operator) public view returns (bool) {
        return _operatorApprovals[addr][operator];
    }

    function tokenURI(uint256 tokenId) public view returns (string memory) {
        // tokenId=0 is collection preview; fixed non-zero seed from contract address hash, no real NFT required
        if (tokenId != 0 && _ownerOf[tokenId] == address(0)) revert NonexistentToken();
        uint256 previewSeed = tokenId == 0
            ? uint256(keccak256(abi.encodePacked(address(this))))
            : seeds[tokenId];
        return ITokenURIRenderer(renderer).render(ITokenURIRenderer.RenderParams({
            name:          name,
            symbol:        symbol,
            tokenAddr:     address(this),
            mirrorAddr:    mirror,
            tokenId:       tokenId,
            seed:          previewSeed,
            script:        script,
            scriptType:    scriptType,
            scriptCdnUrl:  scriptCdnUrl,
            website:       website,
            twitter:       twitter
        }));
    }

    // ─── ERC-721 mutations (called by Mirror) ────────────────────────────────

    function approveNFT(address caller, address spender, uint256 tokenId) external onlyMirror {
        address nftOwner = _ownerOf[tokenId];
        if (nftOwner == address(0)) revert NonexistentToken();
        if (caller != nftOwner && !_operatorApprovals[nftOwner][caller]) revert Unauthorized();
        _tokenApprovals[tokenId] = spender;
        IUniFunMirror(mirror).emitApproval(nftOwner, spender, tokenId);
    }

    function setApprovalForAll(address caller, address operator, bool approved) external onlyMirror {
        _operatorApprovals[caller][operator] = approved;
    }

    function transferNFT(address caller, address from, address to, uint256 tokenId) external onlyMirror {
        address nftOwner = _ownerOf[tokenId];
        if (nftOwner == address(0)) revert NonexistentToken();
        if (nftOwner != from) revert Unauthorized();
        if (
            caller != nftOwner &&
            _tokenApprovals[tokenId] != caller &&
            !_operatorApprovals[nftOwner][caller]
        ) revert Unauthorized();

        if (balanceOf[from] < 1 ether) revert InsufficientBalance();

        unchecked {
            balanceOf[from] -= 1 ether;
            balanceOf[to]   += 1 ether;
        }
        emit Transfer(from, to, 1 ether);

        // Dividend settlement (single call: saves CALL overhead + skips wasteful totalDividendNFTs write)
        if (dividendEnabled && hookAddr != address(0)) {
            uint256 fromOld = _ownedIds[from].length;
            uint256 toOld   = _ownedIds[to].length;
            IUniFunHookDividend(hookAddr).settleRewardsBatch(
                address(this),
                from, fromOld, fromOld - 1,
                to,   toOld,   toOld   + 1
            );
        }

        delete _tokenApprovals[tokenId];
        _stackRemove(from, tokenId);
        _ownerOf[tokenId] = to;
        _stackPush(to, tokenId);
        IUniFunMirror(mirror).emitTransfer(from, to, tokenId);
    }

    // ─── Internal: ERC-20 + NFT sync ─────────────────────────────────────────

    function _transfer(address from, address to, uint256 amount) internal {
        uint256 fromBefore = balanceOf[from];
        if (fromBefore < amount) revert InsufficientBalance();
        uint256 toBefore = balanceOf[to];

        uint256 fromAfter;
        uint256 toAfter;
        unchecked {
            fromAfter = fromBefore - amount;
            toAfter   = toBefore   + amount;
            balanceOf[from] = fromAfter;
            balanceOf[to]   = toAfter;
        }
        emit Transfer(from, to, amount);

        address _mirror = mirror;
        if (_mirror != address(0)) {
            if (fromBefore / 1 ether != fromAfter / 1 ether || toBefore / 1 ether != toAfter / 1 ether) {
                _syncNFTs(from, to, fromBefore, fromAfter, toBefore, toAfter, _mirror);
            }
        }
    }

    function _syncNFTs(
        address from,
        address to,
        uint256 fromBefore,
        uint256 fromAfter,
        uint256 toBefore,
        uint256 toAfter,
        address _mirror
    ) internal {
        bool fromSkip = skipNFT[from];
        bool toSkip   = skipNFT[to];
        if (fromSkip && toSkip) return;

        uint256 fromLoss;
        uint256 toGain;
        unchecked {
            fromLoss = fromSkip ? 0 : (fromBefore / 1 ether - fromAfter / 1 ether);
            toGain   = toSkip   ? 0 : (toAfter   / 1 ether  - toBefore  / 1 ether);
        }

        // Dividend settlement: single settleRewardsBatch covers both sides
        //   - skipNFT addresses pass (addr, 0, 0); Hook skips when oldNFT==newNFT
        //   - pure NFT transfer (both non-skip, net change 0): Hook skips totalDividendNFTs SSTORE
        if (dividendEnabled && hookAddr != address(0)) {
            IUniFunHookDividend(hookAddr).settleRewardsBatch(
                address(this),
                from, fromSkip ? 0 : fromBefore / 1 ether, fromSkip ? 0 : fromAfter  / 1 ether,
                to,   toSkip   ? 0 : toBefore   / 1 ether, toSkip   ? 0 : toAfter    / 1 ether
            );
        }

        if (!fromSkip && fromLoss > 0) {
            uint256 toTransfer = (!toSkip && toGain >= fromLoss) ? fromLoss
                               : (!toSkip && toGain <  fromLoss) ? toGain
                               : 0;
            if (toTransfer > 0) _transferTopBatch(from, to, toTransfer, _mirror);
            uint256 toBurn = fromLoss - toTransfer;
            if (toBurn > 0)     _burnTopBatch(from, toBurn, _mirror);
        }

        if (!toSkip && toGain > 0) {
            uint256 alreadyReceived = fromSkip ? 0 : (fromLoss < toGain ? fromLoss : toGain);
            uint256 toMint = toGain - alreadyReceived;
            if (toMint > 0) _mintNFTBatch(to, toMint, _mirror);
        }
    }

    // ─── Internal: NFT primitives ────────────────────────────────────────────

    function _stackPush(address addr, uint256 tokenId) internal {
        _ownedIndex[addr][tokenId] = _ownedIds[addr].length;
        _ownedIds[addr].push(tokenId);
    }

    function _stackPopTop(address addr) internal returns (uint256 tokenId) {
        uint256[] storage stack = _ownedIds[addr];
        tokenId = stack[stack.length - 1];
        stack.pop();
        delete _ownedIndex[addr][tokenId];
    }

    function _stackRemove(address addr, uint256 tokenId) internal {
        mapping(uint256 => uint256) storage idx = _ownedIndex[addr];
        uint256[] storage stack = _ownedIds[addr];
        uint256 pos = idx[tokenId];
        uint256 lastTokenId = stack[stack.length - 1];
        stack[pos] = lastTokenId;
        idx[lastTokenId] = pos;
        stack.pop();
        delete idx[tokenId];
    }

    function _transferTopBatch(address from, address to, uint256 count, address _mirror) internal {
        uint256[] storage fromStack = _ownedIds[from];
        mapping(uint256 => uint256) storage fromIdx = _ownedIndex[from];
        uint256 fromLen = fromStack.length;
        for (uint256 i; i < count; ++i) {
            uint256 tokenId = fromStack[fromLen - 1 - i];
            delete fromIdx[tokenId];
            delete _tokenApprovals[tokenId];
            _ownerOf[tokenId] = to;
            _stackPush(to, tokenId);
            IUniFunMirror(_mirror).emitTransfer(from, to, tokenId);
        }
        assembly { sstore(fromStack.slot, sub(fromLen, count)) }
    }

    /// @dev Batch-burn count NFTs from the end of from's stack.
    ///      holdTime branch hoisted outside loop to avoid useless comparisons when holdTime=0.
    function _burnTopBatch(address from, uint256 count, address _mirror) internal {
        uint256[] storage stack = _ownedIds[from];
        mapping(uint256 => uint256) storage idx = _ownedIndex[from];
        uint256 len = stack.length;
        uint256 _holdTime = holdTime; // single SLOAD

        if (_holdTime > 0) {
            // Hold period check required
            uint256 ts = block.timestamp;
            for (uint256 i; i < count; ++i) {
                uint256 tokenId = stack[len - 1 - i];
                if (ts < mintTime[tokenId] + _holdTime) revert HoldPeriodNotEnded();
                delete idx[tokenId];
                delete _tokenApprovals[tokenId];
                _ownerOf[tokenId] = address(0);
                IUniFunMirror(_mirror).emitTransfer(from, address(0), tokenId);
            }
        } else {
            // holdTime=0: no hold check, leaner hot path
            for (uint256 i; i < count; ++i) {
                uint256 tokenId = stack[len - 1 - i];
                delete idx[tokenId];
                delete _tokenApprovals[tokenId];
                _ownerOf[tokenId] = address(0);
                IUniFunMirror(_mirror).emitTransfer(from, address(0), tokenId);
            }
        }
        assembly { sstore(stack.slot, sub(len, count)) }
    }

    /// @dev Batch-mint count NFTs; records mintTime when holdTime > 0.
    function _mintNFTBatch(address to, uint256 count, address _mirror) internal {
        uint256 minted = nftMinted;
        if (minted + count > maxSupply * 4 / 5 / 1 ether) revert ExceedsMaxSupply();
        uint256 nextId = _nextId;
        uint256 randao = block.prevrandao;
        address self   = address(this);
        uint256 _holdTime = holdTime;
        uint256 ts = _holdTime > 0 ? block.timestamp : 0;
        for (uint256 i; i < count; ++i) {
            uint256 tokenId = nextId + i;
            seeds[tokenId] = uint256(keccak256(abi.encodePacked(randao, tokenId, self)));
            _ownerOf[tokenId] = to;
            _stackPush(to, tokenId);
            if (ts > 0) mintTime[tokenId] = ts;
            IUniFunMirror(_mirror).emitTransfer(address(0), to, tokenId);
        }
        nftMinted = minted + count;
        _nextId   = nextId  + count;
    }

    function _mintERC20(address to, uint256 amount) internal {
        totalSupply        += amount;
        balanceOf[to]      += amount;
        emit Transfer(address(0), to, amount);

        address _mirror = mirror;
        if (_mirror != address(0) && !skipNFT[to]) {
            uint256 count = amount / 1 ether;
            if (count > 0) _mintNFTBatch(to, count, _mirror);
        }
    }

    function _spendAllowance(address addr, address spender, uint256 amount) internal {
        uint256 allowed = allowance[addr][spender];
        if (allowed != type(uint256).max) {
            if (allowed < amount) revert InsufficientAllowance();
            unchecked { allowance[addr][spender] = allowed - amount; }
        }
    }
}

contracts/ITokenURIRenderer.sol

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

/// @notice Interface between UniFunToken and TokenURIRenderer.
interface ITokenURIRenderer {
    struct RenderParams {
        string  name;
        string  symbol;
        address tokenAddr;
        address mirrorAddr;
        uint256 tokenId;
        uint256 seed;
        string  script;
        string  scriptType;   // "p5js" | "pixijs" | "threejs" | "js"
        string  scriptCdnUrl;
        string  website;
        string  twitter;
    }

    function render(RenderParams calldata p) external pure returns (string memory);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 50,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
    "v4-periphery/=lib/v4-periphery/",
    "forge-std/=lib/forge-std/src/",
    "solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "@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/",
    "v4-core/=lib/v4-core/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.