Skip to content
Verified contractExactMIT

NUTZ

Address0x2f620f2eb60fbe665edf91a7dccfab09edf7d500
Balance

0.001 ETH

 

Transactions

13

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,115,437
Creation transaction
0xb163f375ac…af376af2ab

contracts/NUTZ.sol

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

/**
 * NUTZ — ERC-404 with deterministic rarity tiers + per-NFT mining accrual.
 *
 * ⚠️  READ WARNINGS.md BEFORE INTERACTING. Unaudited mainnet code.
 *
 * Native supply: 10,000  (3,000 deployer / 7,000 public mint)
 * Mint:   0.001 ETH each, max 20/wallet, EOA-only, 100/block cap
 * Tiers (per NFT id, set at deploy):
 *   Common    8,500 NFTs → 0.01 NUTZ/day
 *   Mid       1,350 NFTs → 0.05 NUTZ/day
 *   Legendary   150 NFTs → 0.25 NUTZ/day
 * Mining source: deployer's 3,000-NUTZ allocation, held by contract reserve.
 * Pool runs out in ~152 days at 100% holding → mining halts cleanly.
 *
 * ── MINING INVARIANT ────────────────────────────────────────────────
 * Each NFT has a single state field: accrualStart[id].
 * For any held NFT, _accrued(id) = (now - accrualStart[id]) * rateOf(id).
 * On any change to NFT ownership we call _harvestOne(id, oldOwner), which:
 *   1. Adds _accrued(id) to pending[oldOwner]
 *   2. Resets accrualStart[id] = block.timestamp
 * claim() drains pending[wallet] + all NFT accruals into a single payout.
 */

interface IERC721Receiver {
    function onERC721Received(address, address, uint256, bytes calldata) external returns (bytes4);
}

library Strings {
    function toString(uint256 v) internal pure returns (string memory) {
        if (v == 0) return "0";
        uint256 t = v; uint256 d;
        while (t != 0) { d++; t /= 10; }
        bytes memory b = new bytes(d);
        while (v != 0) { d--; b[d] = bytes1(uint8(48 + (v % 10))); v /= 10; }
        return string(b);
    }
}

abstract contract Ownable {
    address public owner;
    event OwnershipTransferred(address indexed prev, address indexed next);
    error NotOwner();
    error ZeroAddress();

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

    constructor(address _owner) {
        if (_owner == address(0)) revert ZeroAddress();
        owner = _owner;
        emit OwnershipTransferred(address(0), _owner);
    }

    function transferOwnership(address next) external onlyOwner {
        if (next == address(0)) revert ZeroAddress();
        emit OwnershipTransferred(owner, next);
        owner = next;
    }

    function renounceOwnership() external onlyOwner {
        emit OwnershipTransferred(owner, address(0));
        owner = address(0);
    }
}

abstract contract ReentrancyGuard {
    uint256 private _g = 1;
    error Reentrant();
    modifier nonReentrant() {
        if (_g != 1) revert Reentrant();
        _g = 2; _; _g = 1;
    }
}

contract NUTZ is Ownable, ReentrancyGuard {
    using Strings for uint256;

    // ── Metadata ────────────────────────────────────────────────
    string public name = "NUTZ FARMER";
    string public symbol = "NUTZ";
    uint8 public constant decimals = 18;
    uint256 public constant TOTAL_NATIVE_SUPPLY = 10_000;
    uint256 public constant DEPLOYER_ALLOCATION = 3_000;
    uint256 public constant MINT_ALLOCATION = 7_000;
    uint256 public immutable totalSupply;
    string public baseURI;

    // ── Mint config ─────────────────────────────────────────────
    uint256 public mintPrice = 0.001 ether;
    uint256 public constant MAX_PER_WALLET = 20;
    uint256 public constant MAX_MINTS_PER_BLOCK = 100;
    bool public mintEnabled = false;
    uint256 public publicMinted;
    mapping(address => uint256) public mintedBy;
    mapping(uint256 => uint256) public mintsInBlock;

    // ── ERC-20 ──────────────────────────────────────────────────
    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;

    // ── ERC-721 ─────────────────────────────────────────────────
    uint256 public minted; // monotonic NFT id counter
    mapping(uint256 => address) internal _ownerOf;
    mapping(uint256 => address) public getApproved;
    mapping(address => mapping(address => bool)) public isApprovedForAll;
    mapping(address => uint256[]) internal _owned;
    mapping(uint256 => uint256) internal _ownedIndex;

    // ── Whitelist (skip NFT mint/burn on transfer for these) ────
    mapping(address => bool) public whitelist;

    // ── Rarity (deterministic, deploy-time seed) ────────────────
    uint256 public immutable raritySeed;
    uint8 public constant TIER_COMMON = 0;
    uint8 public constant TIER_MID = 1;
    uint8 public constant TIER_LEGENDARY = 2;
    uint256 private constant LEGENDARY_CUTOFF = 150;
    uint256 private constant MID_CUTOFF = 1500;

    // ── Mining rates (wei per second per NFT) ───────────────────
    uint256 public constant RATE_COMMON    = 115_740_740_740_740;
    uint256 public constant RATE_MID       = 578_703_703_703_703;
    uint256 public constant RATE_LEGENDARY = 2_893_518_518_518_518;

    mapping(uint256 => uint64) public accrualStart; // 0 = unset
    mapping(address => uint256) public pending;
    uint256 public miningPoolPaid;

    // ── Events ──────────────────────────────────────────────────
    event Transfer(address indexed from, address indexed to, uint256 indexed id);
    event TransferERC20(address indexed from, address indexed to, uint256 value);
    event ApprovalERC20(address indexed owner, address indexed spender, uint256 value);
    event ApprovalERC721(address indexed owner, address indexed approved, uint256 indexed id);
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
    event MintNutz(address indexed to, uint256 count, uint256 paid);
    event ClaimMining(address indexed wallet, uint256 amount);
    event WhitelistUpdated(address indexed target, bool state);
    event MintPriceChanged(uint256 newPrice);
    event MintToggled(bool enabled);
    event BaseURIChanged(string uri);

    // ── Errors ──────────────────────────────────────────────────
    error MintDisabled();
    error InsufficientPayment();
    error MintLimitReached();
    error BlockMintCap();
    error EOAOnly();
    error SoldOut();
    error InvalidCount();
    error NotFound();
    error InvalidRecipient();
    error InvalidSender();
    error NotAuthorized();
    error TransferFailed();
    error UnsafeRecipient();
    error PoolEmpty();
    error NothingToClaim();

    // ── Constructor ─────────────────────────────────────────────
    constructor() Ownable(msg.sender) {
        totalSupply = TOTAL_NATIVE_SUPPLY * 10 ** decimals;
        raritySeed = uint256(
            keccak256(abi.encodePacked(block.timestamp, block.prevrandao, msg.sender, address(this)))
        );

        whitelist[msg.sender] = true;
        whitelist[address(this)] = true;

        balanceOf[msg.sender] = DEPLOYER_ALLOCATION * 10 ** decimals;
        balanceOf[address(this)] = MINT_ALLOCATION * 10 ** decimals;

        emit TransferERC20(address(0), msg.sender, DEPLOYER_ALLOCATION * 10 ** decimals);
        emit TransferERC20(address(0), address(this), MINT_ALLOCATION * 10 ** decimals);
        emit WhitelistUpdated(msg.sender, true);
        emit WhitelistUpdated(address(this), true);
    }

    receive() external payable {}

    // ── Rarity ──────────────────────────────────────────────────
    function tierOf(uint256 id) public view returns (uint8) {
        uint256 h = uint256(keccak256(abi.encodePacked(raritySeed, id))) % 10_000;
        if (h < LEGENDARY_CUTOFF) return TIER_LEGENDARY;
        if (h < MID_CUTOFF) return TIER_MID;
        return TIER_COMMON;
    }

    function rateOf(uint256 id) public view returns (uint256) {
        uint8 t = tierOf(id);
        if (t == TIER_LEGENDARY) return RATE_LEGENDARY;
        if (t == TIER_MID) return RATE_MID;
        return RATE_COMMON;
    }

    /// 25 design indices (0..24). Legendaries 0..4, mids 5..19, commons 20..24.
    function designOf(uint256 id) public view returns (uint8) {
        uint8 t = tierOf(id);
        uint256 dh = uint256(keccak256(abi.encodePacked(raritySeed, id, uint256(0xDE516))));
        if (t == TIER_LEGENDARY) return uint8(dh % 5);
        if (t == TIER_MID) return uint8(5 + (dh % 15));
        return uint8(20 + (dh % 5));
    }

    // ── Mining: views ───────────────────────────────────────────
    function _accrued(uint256 id) internal view returns (uint256) {
        uint64 start = accrualStart[id];
        if (start == 0) return 0;
        uint256 elapsed = block.timestamp - start;
        if (elapsed == 0) return 0;
        return elapsed * rateOf(id);
    }

    function _accruedAll(address wallet) internal view returns (uint256 total) {
        uint256[] storage ids = _owned[wallet];
        for (uint256 i = 0; i < ids.length; i++) {
            total += _accrued(ids[i]);
        }
    }

    function pendingOf(address wallet) external view returns (uint256) {
        if (whitelist[wallet]) return pending[wallet];
        return pending[wallet] + _accruedAll(wallet);
    }

    function poolRemaining() external view returns (uint256) {
        return balanceOf[address(this)];
    }

    // ── Mining: state changes ───────────────────────────────────
    /**
     * Harvest one NFT's accrual into pending[holder], then reset its timestamp.
     * Call BEFORE changing the NFT's owner.
     */
    function _harvestOne(uint256 id, address holder) internal {
        if (holder != address(0) && !whitelist[holder]) {
            uint256 a = _accrued(id);
            if (a > 0) pending[holder] += a;
        }
        accrualStart[id] = uint64(block.timestamp);
    }

    /**
     * Drain wallet's full claimable amount (pending + accrued on all owned NFTs).
     * Resets accrualStart on each NFT to now. Sets pending[wallet] = 0.
     * Returns total drained.
     */
    function _drainAll(address wallet) internal returns (uint256 total) {
        if (whitelist[wallet]) {
            total = pending[wallet];
            pending[wallet] = 0;
            return total;
        }
        uint256[] storage ids = _owned[wallet];
        uint256 sumAccrued = 0;
        uint64 now64 = uint64(block.timestamp);
        for (uint256 i = 0; i < ids.length; i++) {
            uint256 id = ids[i];
            uint64 start = accrualStart[id];
            if (start > 0) {
                uint256 elapsed = block.timestamp - start;
                if (elapsed > 0) sumAccrued += elapsed * rateOf(id);
            }
            accrualStart[id] = now64;
        }
        total = pending[wallet] + sumAccrued;
        pending[wallet] = 0;
    }

    /**
     * Claim all pending + accrued mining.
     * Pays from contract reserve. If pool < drained, pays what's available
     * and stores the residual in pending[msg.sender] for future claim.
     */
    function claim() external nonReentrant {
        uint256 drained = _drainAll(msg.sender);
        if (drained == 0) revert NothingToClaim();

        uint256 pool = balanceOf[address(this)];
        if (pool == 0) {
            // Restore pending so user can retry later if pool refills
            pending[msg.sender] = drained;
            revert PoolEmpty();
        }

        uint256 payout = drained;
        if (payout > pool) {
            payout = pool;
            pending[msg.sender] = drained - payout; // residual stays as claimable
        }

        // Pay out via ERC-20 path. Contract is whitelisted so no NFT burns from
        // the contract side. Recipient may or may not be whitelisted.
        balanceOf[address(this)] -= payout;
        unchecked { balanceOf[msg.sender] += payout; }
        miningPoolPaid += payout;

        // If recipient is not whitelisted, mint NFTs as their balance crosses unit boundaries.
        // Snapshot BEFORE-balance is (balanceOf[msg.sender] - payout). Compute units crossed.
        if (!whitelist[msg.sender]) {
            uint256 unit = 10 ** decimals;
            uint256 balBefore = balanceOf[msg.sender] - payout;
            uint256 nftsExpected = balanceOf[msg.sender] / unit;
            uint256 nftsActual = _owned[msg.sender].length;
            // expected may exceed actual if balance crossed unit thresholds.
            // Edge case: balBefore/unit may equal nftsActual already (typical) — diff is 0..N.
            // We mint up to (expected - actual), capped at supply.
            // Note: nftsActual should == balBefore/unit if invariants held.
            // But we don't rely on that — we compute by expected vs actual.
            uint256 toMint = nftsExpected > nftsActual ? (nftsExpected - nftsActual) : 0;
            for (uint256 i = 0; i < toMint; i++) {
                if (minted >= TOTAL_NATIVE_SUPPLY) break;
                _mintOne(msg.sender);
            }
            // Silence unused-variable warning
            balBefore;
        }

        emit TransferERC20(address(this), msg.sender, payout);
        emit ClaimMining(msg.sender, payout);
    }

    // ── Mint (spawn) ────────────────────────────────────────────
    function spawn(uint256 count) external payable nonReentrant {
        if (!mintEnabled) revert MintDisabled();
        if (tx.origin != msg.sender) revert EOAOnly();
        if (count == 0 || count > MAX_PER_WALLET) revert InvalidCount();
        if (mintedBy[msg.sender] + count > MAX_PER_WALLET) revert MintLimitReached();
        if (mintsInBlock[block.number] + count > MAX_MINTS_PER_BLOCK) revert BlockMintCap();
        if (publicMinted + count > MINT_ALLOCATION) revert SoldOut();

        uint256 cost = mintPrice * count;
        if (msg.value < cost) revert InsufficientPayment();

        mintedBy[msg.sender] += count;
        mintsInBlock[block.number] += count;
        publicMinted += count;

        uint256 amount = count * 10 ** decimals;
        _transferERC20Inner(address(this), msg.sender, amount);

        if (msg.value > cost) {
            (bool ok,) = msg.sender.call{value: msg.value - cost}("");
            if (!ok) revert TransferFailed();
        }

        emit MintNutz(msg.sender, count, cost);
    }

    // ── ERC-20 surface ──────────────────────────────────────────
    function transfer(address to, uint256 amount) external returns (bool) {
        _transferERC20Inner(msg.sender, to, amount);
        return true;
    }

    function transferFrom(address from, address to, uint256 amountOrId) external returns (bool) {
        if (amountOrId > 0 && amountOrId <= minted && _ownerOf[amountOrId] != address(0)) {
            _transferNFT(from, to, amountOrId);
            return true;
        }
        uint256 a = allowance[from][msg.sender];
        if (a != type(uint256).max) allowance[from][msg.sender] = a - amountOrId;
        _transferERC20Inner(from, to, amountOrId);
        return true;
    }

    function approve(address spender, uint256 amountOrId) external returns (bool) {
        if (amountOrId > 0 && amountOrId <= minted && _ownerOf[amountOrId] != address(0)) {
            address o = _ownerOf[amountOrId];
            if (msg.sender != o && !isApprovedForAll[o][msg.sender]) revert NotAuthorized();
            getApproved[amountOrId] = spender;
            emit ApprovalERC721(o, spender, amountOrId);
        } else {
            allowance[msg.sender][spender] = amountOrId;
            emit ApprovalERC20(msg.sender, spender, amountOrId);
        }
        return true;
    }

    function setApprovalForAll(address op, bool ok) external {
        isApprovedForAll[msg.sender][op] = ok;
        emit ApprovalForAll(msg.sender, op, ok);
    }

    // ── ERC-721 surface ─────────────────────────────────────────
    function ownerOf(uint256 id) external view returns (address) {
        address o = _ownerOf[id];
        if (o == address(0)) revert NotFound();
        return o;
    }

    function safeTransferFrom(address from, address to, uint256 id) external {
        _transferNFT(from, to, id);
        _checkERC721Receiver(from, to, id, "");
    }

    function safeTransferFrom(address from, address to, uint256 id, bytes calldata data) external {
        _transferNFT(from, to, id);
        _checkERC721Receiver(from, to, id, data);
    }

    function _checkERC721Receiver(address from, address to, uint256 id, bytes memory data) internal {
        if (to.code.length == 0) return;
        try IERC721Receiver(to).onERC721Received(msg.sender, from, id, data) returns (bytes4 r) {
            if (r != IERC721Receiver.onERC721Received.selector) revert UnsafeRecipient();
        } catch {
            revert UnsafeRecipient();
        }
    }

    function _transferNFT(address from, address to, uint256 id) internal {
        if (from != _ownerOf[id]) revert InvalidSender();
        if (to == address(0)) revert InvalidRecipient();
        if (msg.sender != from && !isApprovedForAll[from][msg.sender] && msg.sender != getApproved[id]) {
            revert NotAuthorized();
        }

        // Harvest old owner's accrual on this NFT (resets accrualStart to now)
        _harvestOne(id, from);

        uint256 unit = 10 ** decimals;
        balanceOf[from] -= unit;
        unchecked { balanceOf[to] += unit; }
        _ownerOf[id] = to;
        delete getApproved[id];

        // Pop id out of from._owned (swap-with-last)
        uint256 fromLen = _owned[from].length;
        uint256 lastId = _owned[from][fromLen - 1];
        uint256 idIndex = _ownedIndex[id];
        if (idIndex != fromLen - 1) {
            _owned[from][idIndex] = lastId;
            _ownedIndex[lastId] = idIndex;
        }
        _owned[from].pop();

        // Push into to._owned
        _owned[to].push(id);
        _ownedIndex[id] = _owned[to].length - 1;

        emit Transfer(from, to, id);
        emit TransferERC20(from, to, unit);
    }

    // ── ERC-20 inner _transfer (handles NFT shuffle) ────────────
    function _transferERC20Inner(address from, address to, uint256 amount) internal {
        if (to == address(0)) revert InvalidRecipient();
        if (from == address(0)) revert InvalidSender();

        uint256 unit = 10 ** decimals;
        uint256 fromBefore = balanceOf[from];
        uint256 toBefore = balanceOf[to];

        if (fromBefore < amount) revert InvalidSender();

        balanceOf[from] = fromBefore - amount;
        unchecked { balanceOf[to] = toBefore + amount; }

        if (!whitelist[from]) {
            uint256 burnCount = (fromBefore / unit) - (balanceOf[from] / unit);
            for (uint256 i = 0; i < burnCount; i++) _burnOne(from);
        }
        if (!whitelist[to]) {
            uint256 mintCount = (balanceOf[to] / unit) - (toBefore / unit);
            for (uint256 i = 0; i < mintCount; i++) {
                if (minted >= TOTAL_NATIVE_SUPPLY) break;
                _mintOne(to);
            }
        }

        emit TransferERC20(from, to, amount);
    }

    function _mintOne(address to) internal {
        unchecked { minted++; }
        uint256 id = minted;
        _ownerOf[id] = to;
        _owned[to].push(id);
        _ownedIndex[id] = _owned[to].length - 1;
        accrualStart[id] = uint64(block.timestamp);
        emit Transfer(address(0), to, id);
    }

    function _burnOne(address from) internal {
        uint256 len = _owned[from].length;
        if (len == 0) revert InvalidSender();
        uint256 id = _owned[from][len - 1];

        // Harvest accrual on this NFT to the old owner before destroying it
        _harvestOne(id, from);

        _owned[from].pop();
        delete _ownedIndex[id];
        delete _ownerOf[id];
        delete getApproved[id];
        delete accrualStart[id];
        emit Transfer(from, address(0), id);
    }

    // ── tokenURI ────────────────────────────────────────────────
    function tokenURI(uint256 id) external view returns (string memory) {
        if (_ownerOf[id] == address(0)) revert NotFound();
        return string.concat(baseURI, id.toString(), ".json");
    }

    // ── Owner controls ──────────────────────────────────────────
    function setBaseURI(string calldata u) external onlyOwner {
        baseURI = u;
        emit BaseURIChanged(u);
    }

    function setMintPrice(uint256 p) external onlyOwner {
        mintPrice = p;
        emit MintPriceChanged(p);
    }

    function toggleMint() external onlyOwner {
        mintEnabled = !mintEnabled;
        emit MintToggled(mintEnabled);
    }

    function setWhitelist(address target, bool state) external onlyOwner {
        // CRITICAL: whitelisting a wallet AFTER it has accrued mining will
        // freeze its mining (no longer pays). Future mining will not accrue.
        // Their existing pending balance remains claimable.
        whitelist[target] = state;
        emit WhitelistUpdated(target, state);
    }

    function withdrawAll() external onlyOwner nonReentrant {
        uint256 b = address(this).balance;
        if (b == 0) revert TransferFailed();
        (bool ok,) = payable(owner).call{value: b}("");
        if (!ok) revert TransferFailed();
    }

    function setNameSymbol(string calldata _n, string calldata _s) external onlyOwner {
        name = _n;
        symbol = _s;
    }

    // ── View helpers ────────────────────────────────────────────
    function tokenOfOwnerByIndex(address o, uint256 i) external view returns (uint256) {
        return _owned[o][i];
    }

    function balanceNftOf(address o) external view returns (uint256) {
        return _owned[o].length;
    }

    function ownedTokens(address o) external view returns (uint256[] memory) {
        return _owned[o];
    }

    function totalNftMinted() external view returns (uint256) {
        return minted;
    }

    // ── ERC-165 (basic interface support) ───────────────────────
    function supportsInterface(bytes4 iid) external pure returns (bool) {
        return iid == 0x01ffc9a7  // ERC-165
            || iid == 0x80ac58cd  // ERC-721
            || iid == 0x36372b07  // ERC-20-ish (transfer/balance/approve)
            || iid == 0x5b5e139f; // ERC-721 metadata
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.