Skip to content
Verified contractPartialMIT

ArtifactsPiece

Address0x8b003b73cb5adeff29d27819e9953cdc9dd5a261
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

4 more contracts

 

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,224,682
Creation transaction
0x18bf58b3ae…bc1733e769

src/ArtifactsPiece.sol

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

import {ERC721Lite} from "./base/ERC721Lite.sol";
import {ReentrancyGuard} from "./base/ReentrancyGuard.sol";
import {SSTORE2} from "./libs/SSTORE2.sol";
import {Encoding} from "./libs/Encoding.sol";
import {Seal} from "./libs/Seal.sol";
import {IArtHouse, ISourceStore, Traits} from "./interfaces/Interfaces.sol";
import {KeyProof} from "./KeyProof.sol";

/// @notice One ARTIFACTS piece: a one-token ERC-721 + ERC-2981, deployed as an independent runtime copy at claim.
/// Holds the ciphertext pointer, public traits, key commitment and the current owner's wrapped content key.
/// Runs its own keyed resale escrow, where a key that doesn't open can be proven fake (KeyProof) and costs the seller a
/// deposit, and re-keying after plain transfers. THE SOURCE (piece 256) adds a one-time
/// reveal: its owner publishes its content key, which opens its stored seed; from then on tokenURI serves the
/// on-chain renderer page drawing it from that seed.
contract ArtifactsPiece is ERC721Lite, ReentrancyGuard {
    uint256 public constant TOKEN_ID = 1;
    uint256 public constant ESCROW_TIMEOUT = 72 hours; // the buyer's time to check a key, from when it arrives
    uint16 public constant DEPOSIT_BPS = 1_000; // the seller's deposit sent with the key: 10% of the price
    uint256 public constant SELLER_WINDOW = 24 hours; // from paying, only the seller may end a sale (key or refund)
    uint16 public constant ROYALTY_BPS = 750;
    uint16 public constant RESALE_BROKER_BPS = 250; // 2.5% of a resale to the broker who brought the buyer
    uint16 public constant BPS = 10_000;
    /// @notice Closes THE SOURCE's renderer page after its seed (tools/source/renderer.js SUFFIX, byte for byte).
    string public constant RENDER_SUFFIX =
        '"),true);document.body.innerHTML=s;try{if(parent!==window)parent.postMessage({artifacts:s},"*")}catch(e){}</script></body></html>';

    /// @notice Checks fake-key proofs; shared by every piece (an immutable preserved in each runtime copy).
    KeyProof public immutable keyProof;

    address public controller; // ArtifactsFactory (editions) or ArtifactsSource (THE SOURCE)
    IArtHouse public house;
    uint256 public pieceId;
    bool public isSource;
    bool public revealed;
    bytes32 public revealKey; // THE SOURCE's content key K, published by its owner at reveal

    Traits private _traits;
    address public ciphertextPointer;
    bytes32 public commitment;
    bytes public wrappedKey; // wrapped to the current owner's viewing key; cleared on plain transfer
    address public previousOwner; // may post a re-wrapped key after a plain transfer

    mapping(address => bytes32) public viewingKeyOf;
    mapping(address => uint256) public pendingWithdrawals;

    struct Escrow {
        uint256 price;
        address seller;
        address buyer;
        uint64 paidAt;
        bool keyPosted;
        bytes key;
        address broker; // named by the buyer; paid at release if the ledger counts it as a broker
        uint64 keyPostedAt; // when the key arrived: the buyer's 72 hours to check it count from here
        bytes32 viewingKey; // the buyer's viewing key for this purchase: the key is wrapped to it, a proof uses it
        uint256 deposit; // the seller's, sent with the key: theirs again at release, the buyer's if the key is fake
    }

    Escrow public escrow;

    event ViewingKeyRegistered(address indexed account, bytes32 key);
    event WrappedKeyPosted(address indexed by, address indexed forOwner);
    event Listed(address indexed seller, uint256 price);
    event Delisted();
    event EscrowPaid(address indexed buyer, uint256 price);
    event EscrowKeyPosted();
    event EscrowCancelled(address indexed buyer);
    event EscrowRefunded(address indexed buyer, uint256 amount);
    event EscrowProvenFake(address indexed buyer, uint256 amount);
    event EscrowReleased(
        address indexed seller,
        address indexed buyer,
        uint256 price,
        uint256 royalty,
        address broker,
        uint256 brokerShare
    );
    event Revealed(bytes32 key);
    event Withdrawn(address indexed to, uint256 amount);

    error AlreadyInitialized();
    error NotController();
    error NotTokenOwner();
    error NotPreviousOwner();
    error NotSource();
    error AlreadyRevealed();
    error NotListed();
    error AlreadyListed();
    error EscrowActive();
    error NoEscrowBuyer();
    error NotEscrowBuyer();
    error NotSeller();
    error KeyAlreadyPosted();
    error KeyNotPosted();
    error TooEarly();
    error TooLate();
    error WrongPrice();
    error NoViewingKey();
    error TransferFailed();
    error NothingToWithdraw();
    error NotRevealable();
    error WrongKey();
    error KeyOpens();
    error NoKeyProof();
    error BadWrappedKey();

    constructor(address keyProof_) {
        if (keyProof_ == address(0)) revert NoKeyProof();
        keyProof = KeyProof(keyProof_);
        controller = address(this); // lock the implementation; only runtime copies can be initialised
    }

    // ---------- initialisation (by the controller, at claim / settlement) ----------

    function initialize(
        address controller_,
        address house_,
        uint256 pieceId_,
        address to,
        Traits calldata traits_,
        address ciphertext_,
        bytes32 commitment_,
        bytes calldata wrappedKey_,
        bool isSource_,
        bytes32 ownerViewingKey_
    ) external {
        if (controller != address(0)) revert AlreadyInitialized();
        if (msg.sender != controller_ || controller_.code.length == 0) revert NotController();
        controller = controller_;
        house = IArtHouse(house_);
        pieceId = pieceId_;
        isSource = isSource_;
        _traits = traits_;
        ciphertextPointer = ciphertext_;
        commitment = commitment_;
        wrappedKey = wrappedKey_;
        _name = isSource_ ? unicode"ARTIFACTS · THE SOURCE" : string.concat("ARTIFACTS #", Encoding.pad3(pieceId_));
        _symbol = "ARTIFACTS";
        // the viewing key the owner registered with the controller, so a key can be sent here later too
        if (ownerViewingKey_ != bytes32(0)) {
            viewingKeyOf[to] = ownerViewingKey_;
            emit ViewingKeyRegistered(to, ownerViewingKey_);
        }
        _mint(to, TOKEN_ID);
    }

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

    function traits() external view returns (Traits memory) {
        return _traits;
    }

    function ciphertext() external view returns (bytes memory) {
        return ciphertextPointer == address(0) ? bytes("") : SSTORE2.read(ciphertextPointer);
    }

    function royaltyInfo(uint256, uint256 salePrice) public view returns (address, uint256) {
        return house.royaltyFor(controller, salePrice);
    }

    function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
        return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId);
    }

    // ---------- keys ----------

    function registerViewingKey(bytes32 key) external {
        if (key == bytes32(0)) revert NoViewingKey();
        viewingKeyOf[msg.sender] = key;
        emit ViewingKeyRegistered(msg.sender, key);
    }

    /// @notice After a plain transfer the previous owner re-wraps K to the new owner's viewing key and posts it here.
    /// The controller may too (the curator, through it): THE SOURCE's delivery, an edition claimed before its key
    /// arrived, or a piece whose previous owner never re-keyed it. One shot: the key slot must be empty, and posting
    /// ends the previous owner's right, so a delivered key can never be overwritten.
    function rewrapFor(bytes calldata wrapped) external {
        if (msg.sender != previousOwner && msg.sender != controller) revert NotPreviousOwner();
        if (wrappedKey.length != 0) revert KeyAlreadyPosted();
        if (wrapped.length == 0) revert KeyNotPosted();
        address current = ownerOf(TOKEN_ID);
        if (viewingKeyOf[current] == bytes32(0)) revert NoViewingKey();
        wrappedKey = wrapped;
        delete previousOwner;
        emit WrappedKeyPosted(msg.sender, current);
    }

    // ---------- keyed resale escrow ----------

    function list(uint256 price) external {
        if (msg.sender != ownerOf(TOKEN_ID)) revert NotTokenOwner();
        if (escrow.seller != address(0)) revert AlreadyListed();
        if (price == 0) revert WrongPrice();
        escrow.price = price;
        escrow.seller = msg.sender;
        emit Listed(msg.sender, price);
    }

    function delist() external {
        if (msg.sender != escrow.seller) revert NotSeller();
        if (escrow.buyer != address(0)) revert EscrowActive();
        delete escrow;
        emit Delisted();
    }

    /// @notice The buyer pays the listed price into escrow and registers their viewing key for this purchase in the
    /// same step (a version 2 key, so a fake key can be proven), naming the broker who brought them (or zero).
    function buy(bytes32 viewingKey, address broker) external payable nonReentrant {
        Escrow storage e = escrow;
        if (e.seller == address(0)) revert NotListed();
        if (e.buyer != address(0)) revert EscrowActive();
        if (msg.value != e.price) revert WrongPrice();
        if (!keyProof.isViewingKey(viewingKey)) revert NoViewingKey();
        if (msg.sender == e.seller) revert NotEscrowBuyer();
        e.buyer = msg.sender;
        e.paidAt = uint64(block.timestamp);
        e.broker = broker;
        e.viewingKey = viewingKey;
        viewingKeyOf[msg.sender] = viewingKey;
        emit ViewingKeyRegistered(msg.sender, viewingKey);
        emit EscrowPaid(msg.sender, msg.value);
    }

    /// @notice The seller's deposit with the key: DEPOSIT_BPS of the price.
    function depositFor(uint256 price) public pure returns (uint256) {
        return (price * DEPOSIT_BPS) / BPS;
    }

    /// @notice The seller sends the piece's key, wrapped to the buyer's viewing key for this purchase, with a deposit
    /// of 10% of the price: back to the seller with the payment at release, the buyer's if the key is proven fake.
    /// (`r`, `z`) prove the seller made this wrapped key for this buyer and key (KeyProof.knowsWrap).
    /// Must arrive before paidAt + SELLER_WINDOW; after that, refund the buyer and start a new sale instead.
    function postEscrowKey(bytes calldata wrapped, address r, uint256 z) external payable {
        Escrow storage e = escrow;
        if (msg.sender != e.seller) revert NotSeller();
        if (e.buyer == address(0)) revert NoEscrowBuyer();
        if (e.keyPosted) revert KeyAlreadyPosted();
        if (block.timestamp >= e.paidAt + SELLER_WINDOW) revert TooLate();
        if (!keyProof.knowsWrap(wrapped, e.viewingKey, e.buyer, r, z)) revert BadWrappedKey();
        if (msg.value != depositFor(e.price)) revert WrongPrice();
        e.keyPosted = true;
        e.key = wrapped;
        e.keyPostedAt = uint64(block.timestamp);
        e.deposit = msg.value;
        emit EscrowKeyPosted();
    }

    /// @notice The buyer proves the key they were sent doesn't open the piece (see KeyProof): they get their payment
    /// and the seller's deposit, and the seller keeps the piece. Any time until the payment is released. A key that
    /// opens can never be proven fake, so an honest seller can't lose their deposit.
    function proveFakeKey(KeyProof.Proof calldata proof) external nonReentrant {
        Escrow storage e = escrow;
        if (msg.sender != e.buyer) revert NotEscrowBuyer();
        if (!e.keyPosted) revert KeyNotPosted();
        if (!keyProof.isFake(e.key, pieceId, e.viewingKey, commitment, msg.sender, proof)) revert KeyOpens();
        uint256 amount = e.price + e.deposit;
        delete escrow; // the listing ends with it; the seller may list again
        pendingWithdrawals[msg.sender] += amount;
        emit EscrowProvenFake(msg.sender, amount);
    }

    /// @notice The seller may end a sale before sending the key: the buyer gets it all back and the listing ends. Once
    /// the key is sent, only release or a proven fake key ends the sale, so a seller can't dodge a proof.
    function refundBuyer() external nonReentrant {
        Escrow storage e = escrow;
        if (msg.sender != e.seller) revert NotSeller();
        if (e.buyer == address(0)) revert NoEscrowBuyer();
        if (e.keyPosted) revert KeyAlreadyPosted();
        address buyer = e.buyer;
        uint256 amount = e.price;
        delete escrow;
        pendingWithdrawals[buyer] += amount;
        emit EscrowRefunded(buyer, amount);
    }

    /// @notice The buyer may cancel and take their payment back if the key hasn't come SELLER_WINDOW after paying. Not
    /// sooner: a key in a pending transaction is readable, and a buyer could take it and cancel ahead of it.
    function cancel() external nonReentrant {
        Escrow storage e = escrow;
        if (msg.sender != e.buyer) revert NotEscrowBuyer();
        if (e.keyPosted) revert KeyAlreadyPosted();
        if (block.timestamp < e.paidAt + SELLER_WINDOW) revert TooEarly();
        uint256 refund = e.price;
        address buyer = e.buyer;
        e.buyer = address(0);
        e.paidAt = 0;
        e.broker = address(0);
        pendingWithdrawals[buyer] += refund;
        emit EscrowCancelled(buyer);
    }

    /// @notice Release: by the buyer once the key is posted, or by anyone 72 hours after the key arrived. The seller
    /// gets the price (less royalty and broker share) and their deposit back.
    function release() external nonReentrant {
        Escrow storage e = escrow;
        if (e.buyer == address(0)) revert NoEscrowBuyer();
        if (!e.keyPosted) revert KeyNotPosted();
        if (msg.sender != e.buyer && block.timestamp < e.keyPostedAt + ESCROW_TIMEOUT) revert TooEarly();
        address seller = e.seller;
        address buyer = e.buyer;
        address broker = e.broker;
        uint256 price = e.price;
        uint256 deposit = e.deposit;
        bytes memory key = e.key;
        delete escrow;
        (address royaltyTo, uint256 royalty) = royaltyInfo(TOKEN_ID, price);
        if (royaltyTo == address(0)) royalty = 0;
        uint256 brokerShare;
        if (broker != seller && _isBroker(broker)) brokerShare = (price * RESALE_BROKER_BPS) / BPS;
        else broker = address(0);
        pendingWithdrawals[seller] += price - royalty - brokerShare + deposit;
        // The piece and its key are the buyer's before any outside call (the ledger pays the artist directly), so
        // nothing called from there can list, move or reveal it as the seller's.
        _releasing = true;
        _transfer(seller, buyer, TOKEN_ID);
        _releasing = false;
        wrappedKey = key;
        delete previousOwner; // the escrowed key is delivered; the paid seller keeps no re-key right
        // The royalty and broker share go to the ledger, so each party withdraws once from one place. If the
        // ledger refuses (e.g. this piece's module was revoked), they stay here as pull payments instead.
        uint256 toLedger = royalty + brokerShare;
        if (toLedger > 0) {
            try house.recordResale{value: toLedger}(broker, royalty, brokerShare) {}
            catch {
                if (royalty > 0) pendingWithdrawals[royaltyTo] += royalty;
                if (brokerShare > 0) pendingWithdrawals[broker] += brokerShare;
            }
        }
        emit EscrowReleased(seller, buyer, price, royalty, broker, brokerShare);
    }

    function _isBroker(address broker) private view returns (bool) {
        if (broker == address(0)) return false;
        try house.isEligibleBroker(broker) returns (bool ok) {
            return ok;
        } catch {
            return false;
        }
    }

    function withdraw() external nonReentrant {
        uint256 amount = pendingWithdrawals[msg.sender];
        if (amount == 0) revert NothingToWithdraw();
        pendingWithdrawals[msg.sender] = 0;
        (bool ok,) = msg.sender.call{value: amount}("");
        if (!ok) revert TransferFailed();
        emit Withdrawn(msg.sender, amount);
    }

    /// @dev Plain transfers stay allowed, except while a buyer's payment sits in escrow (only release() moves a
    /// token then). A transfer clears the wrapped key and remembers who can re-wrap it; a listing without a
    /// buyer is dropped.
    function _beforeTransfer(address from, address, uint256) internal override {
        if (from == address(0)) return;
        if (!_releasing) {
            if (escrow.buyer != address(0)) revert EscrowActive();
            delete escrow;
        }
        previousOwner = from;
        delete wrappedKey;
    }

    bool private _releasing;

    // ---------- THE SOURCE ----------

    /// @notice THE SOURCE's owner reveals it to everyone, once and forever, by publishing its content key K, which
    /// opens its stored seed. The key must match the commitment locked before the auction. Not while a buyer's payment
    /// sits in escrow: they paid for it sealed. A listing with no buyer yet is taken down, since it was listed sealed.
    function reveal(bytes32 key) external {
        if (!isSource) revert NotSource();
        if (msg.sender != ownerOf(TOKEN_ID)) revert NotTokenOwner();
        if (revealed) revert AlreadyRevealed();
        if (!ISourceStore(controller).locked()) revert NotRevealable();
        if (escrow.buyer != address(0)) revert EscrowActive();
        if (keccak256(abi.encodePacked(key)) != commitment) revert WrongKey();
        revealKey = key;
        revealed = true;
        if (escrow.seller != address(0)) {
            delete escrow;
            emit Delisted();
        }
        emit Revealed(key);
    }

    // ---------- metadata ----------

    function tokenURI(uint256 tokenId) external view returns (string memory) {
        ownerOf(tokenId);
        if (isSource && revealed) return _revealedURI();
        string memory svg = isSource
            ? Seal.source()
            : Seal.edition(_traits.title, _traits.palette, _traits.colourCount, _traits.direction, pieceId);
        bytes memory json = abi.encodePacked(
            '{"name":"',
            _name,
            '","description":"',
            isSource
                ? "THE SOURCE. The full prism the 255 editions are fragments of. Sealed until its owner reveals it."
                : "An ARTIFACTS edition. Encrypted generative art; only the owner can render it. The seal shows its public traits.",
            '","attributes":[',
            _attributes(),
            '],"image":"data:image/svg+xml;base64,',
            Encoding.base64(bytes(svg)),
            '"}'
        );
        return string.concat("data:application/json;base64,", Encoding.base64(json));
    }

    function _attributes() private view returns (string memory) {
        if (isSource) return '{"trait_type":"Piece","value":"THE SOURCE"}';
        return string.concat(
            '{"trait_type":"Title","value":"',
            _traits.title,
            '"},{"trait_type":"Palette","value":"',
            _traits.palette,
            '"},{"trait_type":"Colours","value":',
            Encoding.toString(_traits.colourCount),
            '},{"trait_type":"Direction","value":"',
            _traits.direction,
            '"},{"trait_type":"Edition","value":"',
            Encoding.pad3(pieceId),
            '"}'
        );
    }

    /// @notice THE SOURCE's seed, once revealed (zero before): the stored sealed seed XOR keccak256(K ‖ uint256(0)).
    function revealedSeed() public view returns (bytes32) {
        if (!revealed) return bytes32(0);
        return ISourceStore(controller).sealedSeed() ^ keccak256(abi.encodePacked(revealKey, uint256(0)));
    }

    /// @dev After the reveal the seal stays the still image (marketplace thumbnails), and animation_url is the
    /// on-chain renderer page drawing THE SOURCE from its seed: the rules, stored once, plus the seed.
    function _revealedURI() private view returns (string memory) {
        string memory seedHex = Encoding.toHexString(revealedSeed());
        address[] memory chunks = ISourceStore(controller).rendererChunks();
        bytes memory page;
        for (uint256 i; i < chunks.length; ++i) {
            page = bytes.concat(page, SSTORE2.read(chunks[i]));
        }
        page = bytes.concat(page, bytes(seedHex), bytes(RENDER_SUFFIX));
        bytes memory json = abi.encodePacked(
            '{"name":"',
            _name,
            '","description":"THE SOURCE, revealed by its owner. Drawn from its seed by the ARTIFACTS rules stored on-chain.",',
            '"attributes":[{"trait_type":"Piece","value":"THE SOURCE"},{"trait_type":"Seed","value":"',
            seedHex,
            '"}],"image":"data:image/svg+xml;base64,',
            Encoding.base64(bytes(Seal.sourceRevealed())),
            '","animation_url":"data:text/html;base64,',
            Encoding.base64(page),
            '"}'
        );
        return string.concat("data:application/json;base64,", Encoding.base64(json));
    }
}

src/KeyProof.sol

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

/// @notice Checks that a wrapped key doesn't open its piece, so a seller who sends a fake key can be caught and
/// penalised with no one to trust. The format is version 2 of site/sealcrypto.js, on secp256k1:
///   viewing key  B.x (B lifted with an even y);  wrapped key  0x02 ‖ E.x ‖ K XOR keccak256(DOMAIN ‖ id ‖ B.x ‖ E.x ‖ S.x)
/// where S = e·B = b·E. The buyer reveals S for this one wrapped key and proves S = b·E for the b behind B
/// (Chaum-Pedersen: A1 = w·G, A2 = w·E, c = keccak256(... ‖ A1 ‖ A2) mod n, z = w + c·b; X = c·S as a hint).
/// Scalar multiplications are checked with the ecrecover precompile (it returns the address of u1·G + u2·R for a
/// point R of our choosing), square roots and the one inverse with modexp. Stateless; the pieces call it. A key that
/// opens can never be proven fake: with S proven, the decryption is exact, and it matches the piece's commitment.
/// A seller also proves they made the wrapped key (they know e with E = e·G, see knowsWrap), so nobody can post a key
/// built from someone else's E: a proof of a fake then reveals S = e·B, which only its maker already knew.
contract KeyProof {
    uint256 internal constant P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
    uint256 internal constant N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;

    struct Proof {
        uint256 sx; // S, the shared point for this wrapped key
        uint256 sy;
        uint256 a1x; // A1 = w·G
        uint256 a1y;
        uint256 a2x; // A2 = w·E
        uint256 a2y;
        uint256 xx; // X = c·S
        uint256 xy;
        uint256 z; // w + c·b mod n
    }

    error BadViewingKey();
    error BadProof();

    /// @notice Whether a registered viewing key can receive version 2 keys (and so be used to prove a fake): the x of
    /// a curve point, below n.
    function isViewingKey(bytes32 viewingKey) public view returns (bool) {
        uint256 x = uint256(viewingKey);
        if (x == 0 || x >= N) return false;
        (bool ok,) = _lift(x);
        return ok;
    }

    /// @notice True when `wrapped` is proven not to open the piece (`pieceId`, key commitment `commitment`) for the
    /// holder of `viewingKey`: malformed (no honest wrapper makes it), or opened with the proven shared point to a key
    /// that doesn't match. False when it opens. Reverts on a proof that doesn't hold. The challenge binds the caller
    /// (the piece), the chain and `buyer`, so a proof can't be replayed elsewhere.
    function isFake(
        bytes calldata wrapped,
        uint256 pieceId,
        bytes32 viewingKey,
        bytes32 commitment,
        address buyer,
        Proof calldata p
    ) external view returns (bool) {
        if (wrapped.length != 65 || wrapped[0] != 0x02) return true;
        uint256 ex = uint256(bytes32(wrapped[1:33]));
        if (ex == 0 || ex >= N) return true;
        (bool okE, uint256 ey) = _lift(ex);
        if (!okE) return true;
        uint256 bx = uint256(viewingKey);
        if (!isViewingKey(viewingKey)) revert BadViewingKey();
        (, uint256 by) = _lift(bx);
        if (!_onCurve(p.sx, p.sy) || !_onCurve(p.a1x, p.a1y) || !_onCurve(p.a2x, p.a2y) || !_onCurve(p.xx, p.xy)) {
            revert BadProof();
        }
        if (p.sx == 0 || p.sx >= N || p.z == 0 || p.z >= N) revert BadProof();
        uint256 c = _challenge(bx, ex, buyer, p);
        if (c == 0) revert BadProof();
        // z·G − c·B = A1, and c·S = X, and z·E = A2 + X: so S = b·E for the b with b·G = B
        if (_lin(p.z, N - c, bx, by) != _addr(p.a1x, p.a1y)) revert BadProof();
        if (_lin(0, c, p.sx, p.sy) != _addr(p.xx, p.xy)) revert BadProof();
        (uint256 yx, uint256 yy) = _add(p.a2x, p.a2y, p.xx, p.xy);
        if (_lin(0, p.z, ex, ey) != _addr(yx, yy)) revert BadProof();
        bytes32 key =
            bytes32(wrapped[33:65]) ^ keccak256(abi.encodePacked("Proof House key wrap v2", pieceId, bx, ex, p.sx));
        return keccak256(abi.encodePacked(key)) != commitment;
    }

    /// @notice Whether the sender of `wrapped` knows the e behind its E (Schnorr: R = r·G, given as its address `r`;
    /// z = r + c·e mod n, c binding the chain, the caller (the piece), the buyer, their viewing key and the whole wrapped
    /// key). False for anything an honest wrapper doesn't make: not 65 bytes, not version 2, E off the curve or ≥ n.
    function knowsWrap(bytes calldata wrapped, bytes32 viewingKey, address buyer, address r, uint256 z)
        external
        view
        returns (bool)
    {
        if (wrapped.length != 65 || wrapped[0] != 0x02 || r == address(0) || z == 0 || z >= N) return false;
        uint256 ex = uint256(bytes32(wrapped[1:33]));
        if (ex == 0 || ex >= N) return false;
        (bool ok, uint256 ey) = _lift(ex);
        if (!ok) return false;
        uint256 c = uint256(
            keccak256(
                abi.encodePacked(
                    "Proof House key wrap v2 proof", block.chainid, msg.sender, buyer, viewingKey, keccak256(wrapped), r
                )
            )
        ) % N;
        // z·G − c·E = R
        return c != 0 && _lin(z, N - c, ex, ey) == r;
    }

    function _challenge(uint256 bx, uint256 ex, address buyer, Proof calldata p) private view returns (uint256) {
        return uint256(
            keccak256(
            abi.encodePacked(
            "Proof House fake key v2", block.chainid, msg.sender, buyer, bx, ex, p.sx, p.sy, p.a1x, p.a1y, p.a2x, p.a2y
        )
        )
        ) % N;
    }

    /// @dev The address of u1·G + u2·R, R = (rx, ry) with 0 < rx < n, u2 ≠ 0: ecrecover returns the address of
    /// r⁻¹(s·R − h·G), so s = u2·r and h = −u1·r give exactly that point. Zero if the precompile refuses.
    function _lin(uint256 u1, uint256 u2, uint256 rx, uint256 ry) private view returns (address) {
        uint256 s = mulmod(u2, rx, N);
        uint256 h = (N - mulmod(u1, rx, N)) % N;
        (bool ok, bytes memory ret) = address(1).staticcall(abi.encode(h, ry & 1 == 0 ? 27 : 28, rx, s));
        if (!ok || ret.length != 32) return address(0);
        address q = abi.decode(ret, (address));
        if (q == address(0)) revert BadProof();
        return q;
    }

    function _addr(uint256 x, uint256 y) private pure returns (address) {
        return address(uint160(uint256(keccak256(abi.encodePacked(x, y)))));
    }

    function _onCurve(uint256 x, uint256 y) private pure returns (bool) {
        return x < P && y < P && mulmod(y, y, P) == addmod(mulmod(mulmod(x, x, P), x, P), 7, P);
    }

    /// @dev The point with this x and an even y, if x is on the curve.
    function _lift(uint256 x) private view returns (bool ok, uint256 y) {
        if (x == 0 || x >= P) return (false, 0);
        uint256 c = addmod(mulmod(mulmod(x, x, P), x, P), 7, P);
        y = _modexp(c, (P + 1) / 4);
        ok = mulmod(y, y, P) == c;
        if (y & 1 == 1) y = P - y;
    }

    /// @dev Affine addition of two different points (equal x is refused: a doubling or the point at infinity).
    function _add(uint256 x1, uint256 y1, uint256 x2, uint256 y2) private view returns (uint256 x3, uint256 y3) {
        if (x1 == x2) revert BadProof();
        uint256 lam = mulmod(addmod(y2, P - y1, P), _modexp(addmod(x2, P - x1, P), P - 2), P);
        x3 = addmod(mulmod(lam, lam, P), P - addmod(x1, x2, P), P);
        y3 = addmod(mulmod(lam, addmod(x1, P - x3, P), P), P - y1, P);
    }

    function _modexp(uint256 b, uint256 e) private view returns (uint256 r) {
        (bool ok, bytes memory ret) = address(5).staticcall(abi.encode(uint256(32), uint256(32), uint256(32), b, e, P));
        if (!ok || ret.length != 32) revert BadProof();
        r = abi.decode(ret, (uint256));
    }
}

src/base/ERC721Lite.sol

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

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

/// @notice Minimal ERC-721 whose name and symbol live in storage, so EIP-1167 clones can set them at initialisation.
abstract contract ERC721Lite {
    string internal _name;
    string internal _symbol;

    mapping(uint256 => address) internal _owners;
    mapping(address => uint256) internal _balances;
    mapping(uint256 => address) internal _tokenApprovals;
    mapping(address => mapping(address => bool)) internal _operatorApprovals;

    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    error NonexistentToken();
    error NotAuthorized();
    error InvalidReceiver();
    error AlreadyMinted();

    function name() public view virtual returns (string memory) {
        return _name;
    }

    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    function balanceOf(address account) public view returns (uint256) {
        if (account == address(0)) revert InvalidReceiver();
        return _balances[account];
    }

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

    function approve(address to, uint256 tokenId) external {
        address o = ownerOf(tokenId);
        if (msg.sender != o && !_operatorApprovals[o][msg.sender]) revert NotAuthorized();
        _tokenApprovals[tokenId] = to;
        emit Approval(o, to, tokenId);
    }

    function getApproved(uint256 tokenId) public view returns (address) {
        ownerOf(tokenId);
        return _tokenApprovals[tokenId];
    }

    function setApprovalForAll(address operator, bool approved) external {
        _operatorApprovals[msg.sender][operator] = approved;
        emit ApprovalForAll(msg.sender, operator, approved);
    }

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

    function transferFrom(address from, address to, uint256 tokenId) public virtual {
        address o = ownerOf(tokenId);
        if (msg.sender != o && msg.sender != _tokenApprovals[tokenId] && !_operatorApprovals[o][msg.sender]) {
            revert NotAuthorized();
        }
        if (o != from) revert NotAuthorized();
        _transfer(from, to, tokenId);
    }

    function safeTransferFrom(address from, address to, uint256 tokenId) external {
        safeTransferFrom(from, to, tokenId, "");
    }

    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public {
        transferFrom(from, to, tokenId);
        _checkReceiver(from, to, tokenId, data);
    }

    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == 0x01ffc9a7 || interfaceId == 0x80ac58cd || interfaceId == 0x5b5e139f;
    }

    function _mint(address to, uint256 tokenId) internal {
        if (to == address(0)) revert InvalidReceiver();
        if (_owners[tokenId] != address(0)) revert AlreadyMinted();
        _beforeTransfer(address(0), to, tokenId);
        _balances[to] += 1;
        _owners[tokenId] = to;
        emit Transfer(address(0), to, tokenId);
    }

    function _transfer(address from, address to, uint256 tokenId) internal {
        if (to == address(0)) revert InvalidReceiver();
        _beforeTransfer(from, to, tokenId);
        delete _tokenApprovals[tokenId];
        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;
        emit Transfer(from, to, tokenId);
    }

    function _checkReceiver(address from, address to, uint256 tokenId, bytes memory data) internal {
        if (to.code.length > 0) {
            if (
                IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data)
                    != IERC721Receiver.onERC721Received.selector
            ) {
                revert InvalidReceiver();
            }
        }
    }

    function _beforeTransfer(address from, address to, uint256 tokenId) internal virtual {}
}

src/base/ReentrancyGuard.sol

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

abstract contract ReentrancyGuard {
    uint256 private _status;

    error Reentrancy();

    modifier nonReentrant() {
        if (_status == 1) revert Reentrancy();
        _status = 1;
        _;
        _status = 0;
    }
}

src/interfaces/Interfaces.sol

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

interface IERC20 {
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function transfer(address to, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

interface IERC2981 {
    function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address, uint256);
}

interface IArtHouse {
    function recordSale(address collection, address buyer, address broker) external payable;
    function canRecordSale(address module) external view returns (bool);
    function recordResale(address broker, uint256 royalty, uint256 brokerShare) external payable;
    function isEligibleBroker(address broker) external view returns (bool);
    function royaltyFor(address collection, uint256 salePrice) external view returns (address, uint256);
    function pieceMetadata(address collection, uint256 pieceId)
        external
        view
        returns (string memory title, string memory description, bytes memory svg);
    function owner() external view returns (address);
}

interface IArtCollection {
    function initialize(address house, string calldata name_, string calldata symbol_) external;
    function mint(address to, uint256 tokenId) external;
}

/// @notice Chainlink VRF v2.5 coordinator surface used by ArtifactsFactory.
interface IVRFCoordinatorV2Plus {
    struct RandomWordsRequest {
        bytes32 keyHash;
        uint256 subId;
        uint16 requestConfirmations;
        uint32 callbackGasLimit;
        uint32 numWords;
        bytes extraArgs;
    }

    function requestRandomWords(RandomWordsRequest calldata req) external returns (uint256 requestId);
}

struct Traits {
    string title;
    string palette;
    uint8 colourCount;
    string direction;
}

interface IArtifactsPiece {
    function initialize(
        address controller,
        address house,
        uint256 pieceId,
        address to,
        Traits calldata traits,
        address ciphertext,
        bytes32 commitment,
        bytes calldata wrappedKey,
        bool isSource,
        bytes32 ownerViewingKey
    ) external;
    function rewrapFor(bytes calldata wrapped) external;
    function ownerOf(uint256 tokenId) external view returns (address);
}

/// @notice A sale module that deploys piece contracts answers whether a contract is one of its pieces.
interface IPieceRegistry {
    function isPiece(address piece) external view returns (bool);
}

interface IPieceController {
    function controller() external view returns (address);
}

interface IBalanceOf {
    function balanceOf(address account) external view returns (uint256);
}

interface IOwnerOf {
    function ownerOf(uint256 tokenId) external view returns (address);
}

/// @notice What an ArtifactsPiece needs from THE SOURCE's controller to serve the revealed tokenURI.
/// @notice What THE SOURCE's piece reads from ArtifactsSource: its renderer page and its encrypted seed.
interface ISourceStore {
    function rendererChunks() external view returns (address[] memory);
    function locked() external view returns (bool);
    function sealedSeed() external view returns (bytes32);
}

src/libs/Encoding.sol

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

/// @notice Base64 encoding and decimal string helpers (all internal, inlined by the compiler).
library Encoding {
    string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    function base64(bytes memory data) internal pure returns (string memory) {
        if (data.length == 0) return "";
        string memory table = TABLE;
        string memory result = new string(4 * ((data.length + 2) / 3));
        assembly ("memory-safe") {
            let tablePtr := add(table, 1)
            let resultPtr := add(result, 32)
            let dataPtr := data
            let endPtr := add(data, mload(data))
            for {} lt(dataPtr, endPtr) {} {
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)
                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
                resultPtr := add(resultPtr, 1)
            }
            switch mod(mload(data), 3)
            case 1 {
                mstore8(sub(resultPtr, 1), 0x3d)
                mstore8(sub(resultPtr, 2), 0x3d)
            }
            case 2 { mstore8(sub(resultPtr, 1), 0x3d) }
        }
        return result;
    }

    /// @notice "0x" followed by the 64 lowercase hex digits of `value`.
    function toHexString(bytes32 value) internal pure returns (string memory) {
        bytes memory out = new bytes(66);
        out[0] = "0";
        out[1] = "x";
        for (uint256 i; i < 32; ++i) {
            uint8 b = uint8(value[i]);
            out[2 + 2 * i] = _HEX[b >> 4];
            out[3 + 2 * i] = _HEX[b & 0x0f];
        }
        return string(out);
    }

    bytes16 private constant _HEX = "0123456789abcdef";

    function toString(uint256 value) internal pure returns (string memory) {
        if (value == 0) return "0";
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + (value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /// @dev Three-digit zero-padded number, as in "No. 003" and "ARTIFACTS #003".
    function pad3(uint256 value) internal pure returns (string memory) {
        bytes memory b = new bytes(3);
        b[0] = bytes1(uint8(48 + (value / 100) % 10));
        b[1] = bytes1(uint8(48 + (value / 10) % 10));
        b[2] = bytes1(uint8(48 + value % 10));
        return string(b);
    }
}

src/libs/SSTORE2.sol

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

/// @notice Stores bytes as the runtime code of a tiny contract (prefixed with STOP so it can never run).
library SSTORE2 {
    error WriteFailed();
    error TooLarge();

    uint256 internal constant MAX = 24_575;

    function write(bytes memory data) internal returns (address pointer) {
        if (data.length > MAX) revert TooLarge();
        // creation code: PUSH2 len+1, DUP1, PUSH1 0x0a, RETURNDATASIZE, CODECOPY, RETURNDATASIZE, RETURN, then 0x00 + data
        bytes memory code = abi.encodePacked(hex"61", uint16(data.length + 1), hex"80600a3d393df300", data);
        assembly ("memory-safe") {
            pointer := create(0, add(code, 32), mload(code))
        }
        if (pointer == address(0)) revert WriteFailed();
    }

    function size(address pointer) internal view returns (uint256) {
        uint256 s = pointer.code.length;
        return s == 0 ? 0 : s - 1;
    }

    function read(address pointer) internal view returns (bytes memory data) {
        uint256 len = size(pointer);
        data = new bytes(len);
        assembly ("memory-safe") {
            extcodecopy(pointer, add(data, 32), 1, len)
        }
    }

    /// @dev Copies the stored bytes to memory at `dest` (raw pointer). Returns the number of bytes copied.
    function copyTo(address pointer, uint256 dest) internal view returns (uint256 len) {
        len = size(pointer);
        assembly ("memory-safe") {
            extcodecopy(pointer, dest, 1, len)
        }
    }
}

src/libs/Seal.sol

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

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

/// @notice The ARTIFACTS seal: the RULES.md R8 frame (sheet, double border, menu bar, status bar) with no dots, and a
/// mark in its empty middle that says what it is: a closed lock and SEALED while the art is encrypted, an open lock and
/// REVEALED for THE SOURCE once its owner reveals it. The frame is byte-identical to the frame group of the reference
/// `framed-*.svg` files; the mark follows it.
library Seal {
    string internal constant HEAD =
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1080 1080" width="1080" height="1080"><rect width="1080" height="1080" fill="#ffffff"/>';
    string internal constant FRAME_OPEN =
        '<g fill="#1a1a1a" font-family="Menlo, ui-monospace, monospace" dominant-baseline="middle" letter-spacing="0.5"><rect x="200" y="220" width="680" height="640" fill="none" stroke="#1a1a1a" stroke-width="1.3"/><rect x="203.2" y="223.2" width="673.6" height="633.6" fill="none" stroke="#1a1a1a" stroke-width="1.3"/>';

    /// @dev A closed lock and SEALED, in grey: the art is there, encrypted, for its owner alone.
    string internal constant SEALED_MARK =
        '<g fill="none" stroke="#a8a8a2" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><rect x="510" y="508" width="60" height="40" rx="8.8"/><path d="M524 508v-12a16 16 0 0 1 32 0v12"/></g><circle cx="540" cy="527.2" r="5.5" fill="#a8a8a2"/><text x="540" y="590" fill="#8f8f89" font-family="Menlo, ui-monospace, monospace" font-size="13" letter-spacing="6" text-anchor="middle" dominant-baseline="middle">SEALED</text>';
    /// @dev An open lock and REVEALED, in ink: THE SOURCE is public; its animation draws it.
    string internal constant REVEALED_MARK =
        '<g fill="none" stroke="#1a1a1a" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><rect x="510" y="508" width="60" height="40" rx="8.8"/><path d="M524 508v-20a16 16 0 0 1 32 0v4"/></g><circle cx="540" cy="527.2" r="5.5" fill="#1a1a1a"/><text x="540" y="590" fill="#1a1a1a" font-family="Menlo, ui-monospace, monospace" font-size="13" letter-spacing="6" text-anchor="middle" dominant-baseline="middle">REVEALED</text><text x="540" y="616" fill="#6b6b66" font-family="Menlo, ui-monospace, monospace" font-size="11" letter-spacing="3" text-anchor="middle" dominant-baseline="middle">OPEN TO VIEW</text>';

    function text(string memory x, string memory y, string memory anchor, string memory str)
        internal
        pure
        returns (string memory)
    {
        return string.concat(
            '<text x="',
            x,
            '" y="',
            y,
            '" font-size="12.5" text-anchor="',
            anchor,
            '" xml:space="preserve">',
            str,
            "</text>"
        );
    }

    function line(string memory y) internal pure returns (string memory) {
        return
            string.concat('<line x1="203.2" y1="', y, '" x2="876.8" y2="', y, '" stroke="#1a1a1a" stroke-width="1.2"/>');
    }

    /// @param title menu-bar title (right)
    /// @param statusLeft status-bar left text
    /// @param statusRight status-bar right text
    /// @param master THE SOURCE variant (Reveal menu, doubled dividers)
    /// @param mark what goes in the frame's middle: SEALED_MARK or REVEALED_MARK
    function render(
        string memory title,
        string memory statusLeft,
        string memory statusRight,
        bool master,
        string memory mark
    ) internal pure returns (string memory) {
        string memory menu = master ? "File   View   Reveal" : "File   View   Run";
        string memory top = string.concat(
            HEAD, FRAME_OPEN, text("218.0", "250.0", "start", menu), text("862.0", "250.0", "end", title)
        );
        string memory lines = master
            ? string.concat(line("263.0"), line("266.0"), line("814.0"), line("817.0"))
            : string.concat(line("266.0"), line("814.0"));
        return string.concat(
            top,
            lines,
            text("218.0", "833.0", "start", statusLeft),
            text("862.0", "833.0", "end", statusRight),
            "</g>",
            mark,
            "</svg>"
        );
    }

    /// @dev Edition seal: title / "PALETTE  ·  kC  ·  DIRECTION" / "No. nnn", the edition's number (R8; its real seed is
    /// 256 bits and never printed).
    function edition(
        string memory title,
        string memory palette,
        uint8 colourCount,
        string memory direction,
        uint256 pieceId
    ) internal pure returns (string memory) {
        string memory statusLeft = string.concat(
            palette, unicode"  ·  ", Encoding.toString(colourCount), unicode"C  ·  ", direction
        );
        return render(title, statusLeft, string.concat("No. ", Encoding.pad3(pieceId)), false, SEALED_MARK);
    }

    /// @dev THE SOURCE seal (R9 frame), sealed.
    function source() internal pure returns (string memory) {
        return render(unicode"ARTIFACTS  ◆  MASTER", "THE SOURCE", unicode"FIDELITY · MAX · 1/1", true, SEALED_MARK);
    }

    /// @dev THE SOURCE once revealed: the same frame, marked REVEALED. The art itself is the animation, drawn live by
    /// the renderer stored on-chain; a still image can't run it.
    function sourceRevealed() internal pure returns (string memory) {
        return
            render(unicode"ARTIFACTS  ◆  MASTER", "THE SOURCE", unicode"FIDELITY · MAX · 1/1", true, REVEALED_MARK);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.