Skip to content
Verified contractExactMIT

Zamkuro

Address0xf1eccffb1340fe93e2efb42aaf099ef8b85f7fb6
Balance

0 ETH

 

Transactions

367

 

Compiler

solc 0.8.27

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 800 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,220,040
Creation transaction
0x55a6669f6c…49107a29ba

29 files

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

contracts/Zamkuro.sol

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

/*
 *  ███████╗ █████╗ ███╗   ███╗██╗  ██╗██╗   ██╗██████╗  ██████╗
 *  ╚══███╔╝██╔══██╗████╗ ████║██║ ██╔╝██║   ██║██╔══██╗██╔═══██╗
 *    ███╔╝ ███████║██╔████╔██║█████╔╝ ██║   ██║██████╔╝██║   ██║
 *   ███╔╝  ██╔══██║██║╚██╔╝██║██╔═██╗ ██║   ██║██╔══██╗██║   ██║
 *  ███████╗██║  ██║██║ ╚═╝ ██║██║  ██╗╚██████╔╝██║  ██║╚██████╔╝
 *  ╚══════╝╚═╝  ╚═╝╚═╝     ╚═╝╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═╝ ╚═════╝
 *
 *  2,222 faceless operatives. Each carries a Seal: a clan and a power
 *  encrypted on-chain with Zama FHE, readable only by its holder.
 *
 *  Seen by none. Verified by all.
 */

import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {ERC2981} from "@openzeppelin/contracts/token/common/ERC2981.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";

import {FHE, euint8, ebool} from "@fhevm/solidity/lib/FHE.sol";
import {ZamaEthereumConfig} from "@fhevm/solidity/config/ZamaConfig.sol";

/// @dev Limit Break ERC-721C (Creator Token Standard). Marketplaces like OpenSea read this to enforce creator fees.
interface ICreatorToken {
    event TransferValidatorUpdated(address oldValidator, address newValidator);
    function getTransferValidator() external view returns (address validator);
    function setTransferValidator(address validator) external;
    function getTransferValidationFunction() external view returns (bytes4 functionSignature, bool isViewFunction);
}
interface ICreatorTokenLegacy {
    event TransferValidatorUpdated(address oldValidator, address newValidator);
    function getTransferValidator() external view returns (address validator);
    function setTransferValidator(address validator) external;
}
interface ITransferValidator {
    function validateTransfer(address caller, address from, address to, uint256 tokenId) external view;
    function setTokenTypeOfCollection(address collection, uint16 tokenType) external;
}

contract Zamkuro is ERC721, ERC2981, Ownable, ReentrancyGuard, ZamaEthereumConfig, ICreatorToken {
    using Strings for uint256;

    // ───────────────────────────── Supply & mint ─────────────────────────────

    uint256 public immutable maxSupply;
    uint256 public totalMinted; // ever minted (ids are 1..totalMinted)
    uint256 public totalBurned; // destroyed through Ascension

    /// @notice Mint phases: Vault, Zamkurolist and Public. Closed is the off state before and after mint.
    ///         Vault and Zamkurolist are private: eligibility is a signature from `signer`, issued off-chain
    ///         by the Zamkuro server. No wallet list, Merkle root or count is ever stored on-chain.
    enum Phase {
        Closed,
        Vault,
        Zamkurolist,
        Public
    }

    struct PhaseConfig {
        uint128 price; // wei per token
        uint32 maxPerWallet;
    }

    /// @notice Phases run on a schedule: Vault opens at `mintStart`, then Zamkurolist, then Public.
    ///         A duration of 0 for Public means it stays open until sold out.
    uint64 public mintStart; // 0 = not scheduled (Closed)
    uint32 public vaultDuration; // seconds
    uint32 public zamkurolistDuration; // seconds
    uint32 public publicDuration; // seconds, 0 = no end
    bool public paused; // emergency stop, overrides the schedule
    mapping(Phase => PhaseConfig) public phaseConfig;
    /// @dev mintedIn[phase][wallet]
    mapping(Phase => mapping(address => uint256)) public mintedIn;
    /// @notice Address whose signatures grant Vault / Zamkurolist access. Only the address is public.
    address public signer;

    address payable public treasury;

    // ───────────────────────────── Reveal ─────────────────────────────

    string private _unrevealedURI;
    string private _baseTokenURI;
    bool public revealed;
    /// @notice Random shift applied to the art set at reveal: art index = (tokenId - 1 + offset) % maxSupply.
    uint256 public artOffset;
    bool public offsetRolled;
    bool public metadataFrozen;

    // ───────────────────────────── The Seal (FHE) ─────────────────────────────

    /// @dev Raw clan roll, uniform in [0,128). Clan is derived off-chain from the roll (see CLAN_TABLE in README).
    mapping(uint256 => euint8) private _clanRoll;
    /// @dev Seal power. Starts in [1,16], grows through Ascension, capped at MAX_POWER.
    mapping(uint256 => euint8) private _power;

    uint8 public constant MAX_POWER = 100;
    uint8 public constant ASCENSION_BONUS = 8;

    // ───────────────────────────── Ascension (burn-to-upgrade) ─────────────────────────────

    uint8 public constant MAX_TIER = 3;
    /// @notice Public tier of each token (0 = Initiate .. 3 = Keeper-touched). Drives art frame in metadata.
    mapping(uint256 => uint8) public tierOf;
    bool public ascensionOpen;

    // ───────────────────────────── Events & errors ─────────────────────────────

    event ScheduleSet(uint64 start, uint32 vault, uint32 zamkurolist, uint32 publicDuration);
    event PausedSet(bool paused);
    event Sealed(uint256 indexed tokenId, address indexed to);
    event Ascended(uint256 indexed tokenId, uint256 indexed burnedTokenId, uint8 newTier, address indexed holder);
    event Revealed(string baseURI, uint256 artOffset);
    event OffsetRolled(uint256 artOffset);
    event MetadataUpdate(uint256 _tokenId); // EIP-4906
    event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId); // EIP-4906

    error MintClosed();
    error WrongPhase();
    error NotAllowlisted();
    error ExceedsSupply();
    error ExceedsWalletLimit();
    error WrongPayment();
    error ZeroQuantity();
    error NotOwner();
    error SameToken();
    error AscensionClosed();
    error MaxTier();
    error AlreadyRevealed();
    error OffsetNotRolled();
    error Frozen();
    error NoTreasury();
    error TransferFailed();

    constructor(
        uint256 maxSupply_,
        string memory unrevealedURI_,
        address payable treasury_,
        uint96 royaltyBps_
    ) ERC721("Zamkuro", "ZMK") Ownable(msg.sender) {
        require(maxSupply_ > 0, "supply");
        maxSupply = maxSupply_;
        _unrevealedURI = unrevealedURI_;
        if (treasury_ == address(0)) revert NoTreasury();
        treasury = treasury_;
        require(royaltyBps_ <= 1000, "max 10%");
        _setDefaultRoyalty(treasury_, royaltyBps_);
        emit TransferValidatorUpdated(address(0), DEFAULT_TRANSFER_VALIDATOR);
        _registerTokenType(DEFAULT_TRANSFER_VALIDATOR);
    }

    // ═════════════════════════════ Creator fees (ERC-721C) ═════════════════════════════
    // Every transfer between wallets is checked by Limit Break's transfer validator, which only lets
    // marketplaces that pay creator fees move tokens (per the policy set for this collection).
    // Mints and Ascension burns are never checked.

    address public constant DEFAULT_TRANSFER_VALIDATOR = 0x721C008fdff27BF06E7E123956E2Fe03B63342e3;
    bool private _validatorSet;
    address private _transferValidator;
    bool public autoApproveTransfersFromValidator;

    function getTransferValidator() public view override returns (address v) {
        v = _transferValidator;
        if (v == address(0) && !_validatorSet) v = DEFAULT_TRANSFER_VALIDATOR;
    }

    function setTransferValidator(address v) external override onlyOwner {
        if (v != address(0) && v.code.length == 0) revert TransferFailed();
        emit TransferValidatorUpdated(getTransferValidator(), v);
        _validatorSet = true;
        _transferValidator = v;
        _registerTokenType(v);
    }

    function getTransferValidationFunction() external pure override returns (bytes4, bool) {
        return (bytes4(keccak256("validateTransfer(address,address,address,uint256)")), true);
    }

    function setAutomaticApprovalOfTransfersFromValidator(bool on) external onlyOwner {
        autoApproveTransfersFromValidator = on;
    }

    function isApprovedForAll(address owner_, address operator) public view override returns (bool) {
        return super.isApprovedForAll(owner_, operator)
            || (autoApproveTransfersFromValidator && operator == getTransferValidator());
    }

    function _registerTokenType(address v) private {
        if (v.code.length > 0) { try ITransferValidator(v).setTokenTypeOfCollection(address(this), 721) {} catch {} }
    }

    // ═════════════════════════════ Minting ═════════════════════════════

    /// @notice One mint function for every phase. `signature` is required in Vault and Zamkurolist,
    ///         and ignored in Public (pass empty bytes).
    function mint(uint256 quantity, bytes calldata signature) external payable nonReentrant {
        Phase p = phase();
        if (p == Phase.Closed) revert WrongPhase();
        if (p != Phase.Public) {
            bytes32 digest = MessageHashUtils.toEthSignedMessageHash(
                keccak256(abi.encode(address(this), block.chainid, msg.sender, uint8(p)))
            );
            (address who, ECDSA.RecoverError err, ) = ECDSA.tryRecover(digest, signature);
            if (err != ECDSA.RecoverError.NoError || who != signer || who == address(0)) revert NotAllowlisted();
        }
        PhaseConfig memory c = phaseConfig[p];
        if (mintedIn[p][msg.sender] + quantity > c.maxPerWallet) revert ExceedsWalletLimit();
        if (msg.value != uint256(c.price) * quantity) revert WrongPayment();
        mintedIn[p][msg.sender] += quantity;
        _mintSealed(msg.sender, quantity);
        // Mint funds go straight to the treasury wallet; nothing is held in the contract.
        if (msg.value > 0) {
            (bool ok, ) = treasury.call{value: msg.value}("");
            if (!ok) revert TransferFailed();
        }
    }

    /// @notice Team / Keeper reserve and giveaways. Works in any phase.
    function ownerMint(address to, uint256 quantity) external onlyOwner nonReentrant {
        _mintSealed(to, quantity);
    }

    function _mintSealed(address to, uint256 quantity) internal {
        if (quantity == 0) revert ZeroQuantity();
        if (totalMinted + quantity > maxSupply) revert ExceedsSupply();
        for (uint256 i = 0; i < quantity; i++) {
            uint256 id = ++totalMinted;

            // Encrypted randomness: nobody can see or steer these, not the team and not a validator.
            euint8 roll = FHE.randEuint8(128); // [0,128)
            euint8 pow = FHE.add(FHE.randEuint8(16), 1); // [1,16]

            FHE.allowThis(roll);
            FHE.allowThis(pow);
            _clanRoll[id] = roll;
            _power[id] = pow;

            _safeMint(to, id); // _update grants `to` read access
            emit Sealed(id, to);
        }
    }

    // ═════════════════════════════ Ascension ═════════════════════════════

    /**
     * @notice Burn `sacrificeId` to ascend `targetId`.
     *  - target tier +1 (public, changes the art frame)
     *  - target power = min(max(powerA, powerB) + ASCENSION_BONUS, MAX_POWER), computed on ciphertext
     *  - target keeps its clan; the sacrifice is destroyed forever (supply shrinks)
     */
    function ascend(uint256 targetId, uint256 sacrificeId) external nonReentrant {
        if (!ascensionOpen) revert AscensionClosed();
        if (targetId == sacrificeId) revert SameToken();
        if (ownerOf(targetId) != msg.sender || ownerOf(sacrificeId) != msg.sender) revert NotOwner();
        uint8 tier = tierOf[targetId];
        if (tier >= MAX_TIER) revert MaxTier();

        euint8 boosted = FHE.add(FHE.max(_power[targetId], _power[sacrificeId]), ASCENSION_BONUS);
        ebool over = FHE.gt(boosted, MAX_POWER);
        euint8 newPower = FHE.select(over, FHE.asEuint8(MAX_POWER), boosted);
        FHE.allowThis(newPower);
        FHE.allow(newPower, msg.sender);
        _power[targetId] = newPower;

        tierOf[targetId] = tier + 1;

        _burn(sacrificeId);
        _clanRoll[sacrificeId] = euint8.wrap(bytes32(0));
        _power[sacrificeId] = euint8.wrap(bytes32(0));
        delete tierOf[sacrificeId];
        totalBurned++;

        emit Ascended(targetId, sacrificeId, tier + 1, msg.sender);
        emit MetadataUpdate(targetId);
    }

    // ═════════════════════════════ Seal access ═════════════════════════════

    /// @notice Encrypted handles for a token's Seal. Only the current holder can decrypt them (via the Zama relayer).
    function sealOf(uint256 tokenId) external view returns (euint8 clanRoll, euint8 power) {
        _requireOwned(tokenId);
        return (_clanRoll[tokenId], _power[tokenId]);
    }

    /// @notice Holder can re-grant themselves access (e.g. after a contract-wallet migration).
    function refreshSealAccess(uint256 tokenId) external {
        if (ownerOf(tokenId) != msg.sender) revert NotOwner();
        FHE.allow(_clanRoll[tokenId], msg.sender);
        FHE.allow(_power[tokenId], msg.sender);
    }

    /// @dev Every mint and transfer hands the new holder permission to read the Seal.
    ///      Previous holders keep any decryption they already did, but this is inherent to any secret: once seen, seen.
    function _update(address to, uint256 tokenId, address auth) internal override returns (address from) {
        address prev = _ownerOf(tokenId);
        if (prev != address(0) && to != address(0)) {
            address v = getTransferValidator();
            if (v != address(0) && msg.sender != v && v.code.length > 0) ITransferValidator(v).validateTransfer(msg.sender, prev, to, tokenId);
        }
        from = super._update(to, tokenId, auth);
        if (to != address(0) && FHE.isInitialized(_clanRoll[tokenId])) {
            FHE.allow(_clanRoll[tokenId], to);
            FHE.allow(_power[tokenId], to);
        }
    }

    // ═════════════════════════════ Metadata ═════════════════════════════

    function totalSupply() external view returns (uint256) {
        return totalMinted - totalBurned;
    }

    /// @notice Revealed URI: {base}{tokenId}_{tier}.json, so token #5 is always "Zamkuro #5".
    /// Each token's file shows artwork artOf(tokenId), fixed by the random offset rolled on-chain.
    function tokenURI(uint256 tokenId) public view override returns (string memory) {
        _requireOwned(tokenId);
        if (!revealed) {
            // Folder of per-token sealed files ("ipfs://CID/") so marketplaces show "Zamkuro #5" before reveal too.
            bytes memory u = bytes(_unrevealedURI);
            if (u.length > 0 && u[u.length - 1] == "/") return string.concat(_unrevealedURI, tokenId.toString(), ".json");
            return _unrevealedURI;
        }
        return string.concat(_baseTokenURI, tokenId.toString(), "_", uint256(tierOf[tokenId]).toString(), ".json");
    }

    /// @notice Which artwork a token shows. Valid once the offset is rolled.
    function artOf(uint256 tokenId) public view returns (uint256) {
        if (!offsetRolled) revert OffsetNotRolled();
        return ((tokenId - 1 + artOffset) % maxSupply) + 1;
    }

    /// @notice Step 1 of reveal: roll the random art offset on-chain, once. Nobody (including the owner)
    /// can choose it.
    function rollOffset() external onlyOwner {
        if (offsetRolled) revert AlreadyRevealed();
        offsetRolled = true;
        artOffset = uint256(keccak256(abi.encode(block.prevrandao, blockhash(block.number - 1), totalMinted))) % maxSupply;
        emit OffsetRolled(artOffset);
    }

    /// @notice Step 2 of reveal: point at the metadata built for that offset. One-way.
    function reveal(string calldata baseURI_) external onlyOwner {
        if (revealed) revert AlreadyRevealed();
        if (!offsetRolled) revert OffsetNotRolled();
        revealed = true;
        _baseTokenURI = baseURI_;
        emit Revealed(baseURI_, artOffset);
        emit BatchMetadataUpdate(1, maxSupply);
    }

    function setBaseURI(string calldata baseURI_) external onlyOwner {
        if (metadataFrozen) revert Frozen();
        _baseTokenURI = baseURI_;
        emit BatchMetadataUpdate(1, maxSupply);
    }

    function setUnrevealedURI(string calldata uri) external onlyOwner {
        if (revealed) revert AlreadyRevealed();
        _unrevealedURI = uri;
        emit BatchMetadataUpdate(1, maxSupply); // tells OpenSea to reload every item
    }

    // ═════════════════════════════ Collection info (ERC-7572) ═════════════════════════════
    /// @notice JSON with the collection name, description, logo and banner. Marketplaces read it automatically.
    string private _contractURI;
    event ContractURIUpdated();

    function contractURI() external view returns (string memory) {
        return _contractURI;
    }

    function setContractURI(string calldata uri) external onlyOwner {
        _contractURI = uri;
        emit ContractURIUpdated();
    }

    function freezeMetadata() external onlyOwner {
        metadataFrozen = true;
    }

    // ═════════════════════════════ Admin ═════════════════════════════

    /// @notice The live phase, worked out from the schedule and the current block time.
    function phase() public view returns (Phase) {
        if (paused || mintStart == 0 || block.timestamp < mintStart) return Phase.Closed;
        uint256 t = block.timestamp - mintStart;
        if (t < vaultDuration) return Phase.Vault;
        t -= vaultDuration;
        if (t < zamkurolistDuration) return Phase.Zamkurolist;
        t -= zamkurolistDuration;
        if (publicDuration == 0 || t < publicDuration) return Phase.Public;
        return Phase.Closed;
    }

    /// @notice Start time (unix seconds) of each phase and the end of Public (0 = no end). For countdowns.
    function schedule() external view returns (uint64 vaultStart, uint64 zamkurolistStart, uint64 publicStart, uint64 publicEnd) {
        vaultStart = mintStart;
        zamkurolistStart = mintStart + vaultDuration;
        publicStart = zamkurolistStart + zamkurolistDuration;
        publicEnd = publicDuration == 0 ? 0 : publicStart + publicDuration;
    }

    function setSchedule(uint64 start, uint32 vaultSecs, uint32 zamkurolistSecs, uint32 publicSecs) external onlyOwner {
        mintStart = start;
        vaultDuration = vaultSecs;
        zamkurolistDuration = zamkurolistSecs;
        publicDuration = publicSecs;
        emit ScheduleSet(start, vaultSecs, zamkurolistSecs, publicSecs);
    }

    function setPaused(bool p) external onlyOwner {
        paused = p;
        emit PausedSet(p);
    }

    function configurePhase(Phase p, uint128 price, uint32 maxPerWallet) external onlyOwner {
        require(p != Phase.Closed, "closed");
        phaseConfig[p] = PhaseConfig(price, maxPerWallet);
    }

    function setSigner(address s) external onlyOwner {
        signer = s;
    }

    function setAscensionOpen(bool open) external onlyOwner {
        ascensionOpen = open;
    }

    function setTreasury(address payable t) external onlyOwner {
        if (t == address(0)) revert NoTreasury();
        treasury = t;
    }

    /// @notice Creator fee, capped at 10% so it can never be raised beyond that.
    function setRoyalty(address receiver, uint96 bps) external onlyOwner {
        require(bps <= 1000, "max 10%");
        _setDefaultRoyalty(receiver, bps);
    }

    /// @notice Only for ETH sent to the contract by mistake: mint funds already go straight to the treasury.
    function withdraw() external nonReentrant {
        (bool ok, ) = treasury.call{value: address(this).balance}("");
        if (!ok) revert TransferFailed();
    }

    function supportsInterface(bytes4 id) public view override(ERC721, ERC2981) returns (bool) {
        return id == bytes4(0x49064906) || id == type(ICreatorToken).interfaceId
            || id == type(ICreatorTokenLegacy).interfaceId || super.supportsInterface(id);
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 800,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.