Skip to content
Verified contractPartialMIT

ArtHouse

Address0x73b1e5825280df29ea7124e927f3ebd9710b5a99
Balance

0.233 ETH

 

Transactions

11

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,224,242
Creation transaction
0x3515987061…dad23e6478

src/ArtHouse.sol

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

import {TwoStepOwnable} from "./base/TwoStepOwnable.sol";
import {ReentrancyGuard} from "./base/ReentrancyGuard.sol";
import {Clones} from "./libs/Clones.sol";
import {ArtStorage} from "./ArtStorage.sol";
import {ArtCollection} from "./ArtCollection.sol";
import {IERC20, IArtCollection, IPieceRegistry, IPieceController, IBalanceOf} from "./interfaces/Interfaces.sol";

/// @notice Proof House ledger: artists, brokers, sale modules, per-collection splits, balances per currency,
/// plain SVG collections (curation, pricing, minting) and open submissions. Owner = curator.
contract ArtHouse is TwoStepOwnable, ReentrancyGuard {
    // ---------- constants ----------
    uint16 public constant BPS = 10_000;
    uint16 public constant ROYALTY_BPS = 750;
    // A sale's default split: 75% to the artist, 15% to the agent who brought the buyer, 5% to the house (team and
    // operations) and 5% to buy back and burn IMD. On any collection, an agent's share nobody earned is burned too.
    uint16 public constant DEFAULT_BROKER_BPS = 1500;
    uint16 public constant DEFAULT_HOUSE_BPS = 500;
    uint16 public constant DEFAULT_ARTIST_BPS = 7500;
    uint16 public constant DEFAULT_BURN_BPS = 500;
    /// @notice The balance key of ETH (or tokens) set aside to buy back and burn IMD. Only the buyback burner,
    /// set once, can receive it.
    address public constant BUYBACK = address(uint160(uint256(keccak256("proofhouse.buyback"))));
    /// @notice The gas an artist's payout address gets to receive its share at a sale (see _payArtist).
    uint256 public constant ARTIST_PAY_GAS = 50_000;
    /// @notice Bound the optional pass lookup so a broken pass cannot block sales.
    uint256 public constant BROKER_CALL_GAS = 100_000;
    uint256 public constant MAX_PIECE_BYTES = 100_000;
    address public constant ETH = address(0);

    // ---------- immutables ----------
    ArtStorage public immutable artStorage;
    address public immutable imd;
    address public immutable collectionImplementation;

    // ---------- types ----------
    struct Artist {
        string name;
        address payout;
        bool approved;
    }

    struct Collection {
        bool exists;
        bool isModule; // sold by an approved sale module (e.g. ArtifactsFactory) rather than by mint()
        bool open;
        bool isSealed;
        address artist;
        uint16 brokerBps;
        uint16 houseBps;
        uint16 artistBps;
        uint256 pieceCount;
        uint256 priceETH;
        uint256 priceIMD;
        uint16 burnBps; // last, so readers of the fields before it are unchanged
    }

    struct Piece {
        bytes32 contentHash;
        string title;
        string description;
        bool finalized;
        bool minted;
        uint256 size;
    }

    enum SubmissionStatus {
        Pending,
        Accepted,
        Rejected
    }

    struct Submission {
        address submitter;
        bytes32 contentHash;
        string previewURI;
        SubmissionStatus status;
    }

    // ---------- state ----------
    mapping(address => Artist) public artists;
    mapping(address => bool) public brokers;
    mapping(address => bool) public saleModules;
    mapping(address => Collection) public collections;
    mapping(address => mapping(uint256 => Piece)) public pieces;
    // party => currency => balance; the house's own balance is keyed by address(this)
    mapping(address => mapping(address => uint256)) public balances;
    Submission[] public submissions;
    address[] public collectionList;
    /// @notice Proof House Broker Pass: holding one makes a wallet a broker. Set once by the owner.
    address public brokerPass;
    /// @notice The contract that turns the buyback balance into IMD and burns it. Set once by the owner.
    address public buybackBurner;

    // ---------- events ----------
    event ArtistApproved(address indexed artist, string name, address payout);
    event ArtistRevoked(address indexed artist);
    event PayoutChanged(address indexed artist, address payout);
    event BrokerSet(address indexed broker, bool approved);
    event SaleModuleSet(address indexed module, bool approved);
    event BrokerPassSet(address indexed brokerPass);
    event Resale(
        address indexed collection, address indexed piece, address indexed broker, uint256 royalty, uint256 brokerShare
    );
    event CollectionCreated(address indexed collection, address indexed artist, string name, string symbol);
    event ModuleCollectionRegistered(address indexed collection, address indexed artist);
    event SplitSet(address indexed collection, uint16 brokerBps, uint16 houseBps, uint16 artistBps, uint16 burnBps);
    event BuybackBurnerSet(address indexed burner);
    event BuybackReleased(address indexed currency, address indexed burner, uint256 amount);
    event PricesSet(address indexed collection, uint256 priceETH, uint256 priceIMD);
    event SaleOpenSet(address indexed collection, bool open);
    event PieceRegistered(address indexed collection, uint256 indexed pieceId, bytes32 contentHash, string title);
    event PieceUpdated(address indexed collection, uint256 indexed pieceId, bytes32 contentHash, string title);
    event PieceCleared(address indexed collection, uint256 indexed pieceId);
    event PieceFinalized(address indexed collection, uint256 indexed pieceId);
    event CollectionSealed(address indexed collection);
    event Sale(
        address indexed collection,
        address indexed buyer,
        address indexed broker,
        address currency,
        uint256 amount,
        uint256 brokerShare,
        uint256 houseShare,
        uint256 artistShare,
        uint256 burnShare
    );
    event Withdrawn(address indexed party, address indexed currency, address to, uint256 amount);
    /// @notice An artist's ETH share, sent straight to their payout address at the sale.
    event ArtistPaid(address indexed artist, address indexed to, uint256 amount);
    /// @notice The artist's share waits in their balance (another currency, or the payout didn't take ETH).
    event ArtistCredited(address indexed artist, address indexed currency, uint256 amount);
    event Submitted(uint256 indexed id, address indexed submitter, bytes32 contentHash, string previewURI);
    event SubmissionDecided(uint256 indexed id, SubmissionStatus status);

    // ---------- errors ----------
    error NotApprovedArtist();
    error NotArtist();
    error NotSaleModule();
    error UnknownCollection();
    error BadSplit();
    error BadPieceId();
    error BadIndex();
    error Sealed();
    error NotSealed();
    error Finalized();
    error NotFinalized();
    error TooLarge();
    error HashMismatch();
    error SaleClosed();
    error WrongPrice();
    error AlreadyMinted();
    error NothingToWithdraw();
    error TransferFailed();
    error NotCurator();
    error BadSubmission();
    error NotPending();
    error NotModuleCollection();
    error BrokerPassAlreadySet();
    error NotPiece();
    error NotEligibleBroker();
    error BuybackBurnerAlreadySet();
    error NoBuybackBurner();

    constructor(address owner_, address storage_, address imd_) TwoStepOwnable(owner_) {
        if (storage_ == address(0) || imd_ == address(0)) revert ZeroAddress();
        artStorage = ArtStorage(storage_);
        imd = imd_;
        collectionImplementation = address(new ArtCollection());
    }

    // ---------- artists & brokers ----------

    function approveArtist(address artist, string calldata name_) external onlyOwner {
        if (artist == address(0)) revert ZeroAddress();
        Artist storage a = artists[artist];
        a.name = name_;
        a.approved = true;
        if (a.payout == address(0)) a.payout = artist; // kept across re-approval once the artist changed it
        emit ArtistApproved(artist, name_, a.payout);
    }

    function revokeArtist(address artist) external onlyOwner {
        artists[artist].approved = false;
        emit ArtistRevoked(artist);
    }

    /// @notice Only the artist can change where their earnings and royalties go.
    function setPayout(address payout) external {
        if (artists[msg.sender].payout == address(0)) revert NotArtist();
        if (payout == address(0)) revert ZeroAddress();
        artists[msg.sender].payout = payout;
        emit PayoutChanged(msg.sender, payout);
    }

    function setBroker(address broker, bool approved) external onlyOwner {
        brokers[broker] = approved;
        emit BrokerSet(broker, approved);
    }

    function setSaleModule(address module, bool approved) external onlyOwner {
        saleModules[module] = approved;
        emit SaleModuleSet(module, approved);
    }

    /// @notice Set once after deployment, like the VRF settings: the pass is deployed after the ledger.
    function setBrokerPass(address pass) external onlyOwner {
        if (brokerPass != address(0)) revert BrokerPassAlreadySet();
        if (pass == address(0)) revert ZeroAddress();
        brokerPass = pass;
        emit BrokerPassSet(pass);
    }

    /// @notice A broker earns when the curator approved it or it holds a Broker Pass at the time of the sale.
    function isEligibleBroker(address broker) public view returns (bool) {
        if (broker == address(0)) return false;
        if (brokers[broker]) return true;
        address pass = brokerPass;
        if (pass == address(0)) return false;
        bytes memory data = abi.encodeCall(IBalanceOf.balanceOf, (broker));
        uint256 g = BROKER_CALL_GAS;
        bool ok;
        uint256 held;
        assembly ("memory-safe") {
            mstore(0, 0)
            ok := staticcall(g, pass, add(data, 32), mload(data), 0, 32)
            if iszero(eq(returndatasize(), 32)) { ok := 0 }
            if ok { held := mload(0) }
        }
        return ok && held > 0;
    }

    // ---------- collections ----------

    function createCollection(string calldata name_, string calldata symbol_, address artist)
        external
        onlyOwner
        returns (address collection)
    {
        if (!artists[artist].approved) revert NotApprovedArtist();
        collection = Clones.copyCode(collectionImplementation);
        IArtCollection(collection).initialize(address(this), name_, symbol_);
        _newCollection(collection, artist, false);
        emit CollectionCreated(collection, artist, name_, symbol_);
    }

    /// @notice Registers a sale module (e.g. ArtifactsFactory) as a collection for splits and royalties.
    function registerModuleCollection(address module, address artist) external onlyOwner {
        if (!artists[artist].approved) revert NotApprovedArtist();
        if (collections[module].exists) revert UnknownCollection();
        _newCollection(module, artist, true);
        emit ModuleCollectionRegistered(module, artist);
    }

    function _newCollection(address collection, address artist, bool isModule) private {
        Collection storage c = collections[collection];
        c.exists = true;
        c.isModule = isModule;
        c.artist = artist;
        c.brokerBps = DEFAULT_BROKER_BPS;
        c.houseBps = DEFAULT_HOUSE_BPS;
        c.artistBps = DEFAULT_ARTIST_BPS;
        c.burnBps = DEFAULT_BURN_BPS;
        collectionList.push(collection);
    }

    function setSplit(address collection, uint16 brokerBps, uint16 houseBps, uint16 artistBps, uint16 burnBps)
        external
        onlyOwner
    {
        if (!collections[collection].exists) revert UnknownCollection();
        if (uint256(brokerBps) + houseBps + artistBps + burnBps != BPS) revert BadSplit();
        Collection storage c = collections[collection];
        c.brokerBps = brokerBps;
        c.houseBps = houseBps;
        c.artistBps = artistBps;
        c.burnBps = burnBps;
        emit SplitSet(collection, brokerBps, houseBps, artistBps, burnBps);
    }

    function setPrices(address collection, uint256 priceETH, uint256 priceIMD) external onlyOwner {
        Collection storage c = collections[collection];
        if (!c.exists || c.isModule) revert UnknownCollection();
        c.priceETH = priceETH;
        c.priceIMD = priceIMD;
        emit PricesSet(collection, priceETH, priceIMD);
    }

    function setSaleOpen(address collection, bool open) external onlyOwner {
        Collection storage c = collections[collection];
        if (!c.exists || c.isModule) revert UnknownCollection();
        if (open && !c.isSealed) revert NotSealed();
        c.open = open;
        emit SaleOpenSet(collection, open);
    }

    function collectionCount() external view returns (uint256) {
        return collectionList.length;
    }

    // ---------- piece curation (plain SVG) ----------

    /// @dev The curator, or the collection's artist while still approved: revocation ends curation rights too.
    function _curatorOrArtist(Collection storage c) private view {
        if (msg.sender == owner) return;
        if (msg.sender != c.artist || !artists[c.artist].approved) revert NotCurator();
    }

    function registerPiece(
        address collection,
        uint256 pieceId,
        bytes32 contentHash,
        string calldata title,
        string calldata description
    ) external {
        Collection storage c = collections[collection];
        if (!c.exists || c.isModule) revert UnknownCollection();
        _curatorOrArtist(c);
        if (c.isSealed) revert Sealed();
        if (pieceId != c.pieceCount) revert BadPieceId();
        c.pieceCount = pieceId + 1;
        Piece storage p = pieces[collection][pieceId];
        p.contentHash = contentHash;
        p.title = title;
        p.description = description;
        emit PieceRegistered(collection, pieceId, contentHash, title);
    }

    /// @notice Corrects an unfinalized piece's content hash, title and description (a mistyped hash would otherwise
    /// leave the collection unsealable forever). Uploaded chunks are kept; finalizePiece checks against the new hash.
    function updatePiece(
        address collection,
        uint256 pieceId,
        bytes32 contentHash,
        string calldata title,
        string calldata description
    ) external {
        Collection storage c = collections[collection];
        if (!c.exists || c.isModule) revert UnknownCollection();
        _curatorOrArtist(c);
        if (c.isSealed) revert Sealed();
        if (pieceId >= c.pieceCount) revert BadPieceId();
        Piece storage p = pieces[collection][pieceId];
        if (p.finalized) revert Finalized();
        p.contentHash = contentHash;
        p.title = title;
        p.description = description;
        emit PieceUpdated(collection, pieceId, contentHash, title);
    }

    function uploadChunk(address collection, uint256 pieceId, uint256 index, bytes calldata data) external {
        Collection storage c = collections[collection];
        if (!c.exists || c.isModule) revert UnknownCollection();
        _curatorOrArtist(c);
        if (pieceId >= c.pieceCount) revert BadPieceId();
        Piece storage p = pieces[collection][pieceId];
        if (p.finalized) revert Finalized();
        if (index != artStorage.chunkCount(collection, pieceId)) revert BadIndex();
        p.size += data.length;
        if (p.size > MAX_PIECE_BYTES) revert TooLarge();
        artStorage.write(collection, pieceId, index, data);
    }

    /// @notice The curator may wipe an unfinalized piece's chunks so they can be re-uploaded.
    function clearPiece(address collection, uint256 pieceId) external onlyOwner {
        Collection storage c = collections[collection];
        if (!c.exists || pieceId >= c.pieceCount) revert BadPieceId();
        Piece storage p = pieces[collection][pieceId];
        if (p.finalized) revert Finalized();
        p.size = 0;
        artStorage.clear(collection, pieceId);
        emit PieceCleared(collection, pieceId);
    }

    function finalizePiece(address collection, uint256 pieceId) external {
        Collection storage c = collections[collection];
        if (!c.exists || c.isModule) revert UnknownCollection();
        _curatorOrArtist(c);
        if (pieceId >= c.pieceCount) revert BadPieceId();
        Piece storage p = pieces[collection][pieceId];
        if (p.finalized) revert Finalized();
        if (p.size == 0 || keccak256(artStorage.read(collection, pieceId)) != p.contentHash) revert HashMismatch();
        p.finalized = true;
        emit PieceFinalized(collection, pieceId);
    }

    function sealCollection(address collection) external onlyOwner {
        Collection storage c = collections[collection];
        if (!c.exists || c.isModule) revert UnknownCollection();
        if (c.isSealed) revert Sealed();
        if (c.pieceCount == 0) revert NotFinalized();
        for (uint256 i; i < c.pieceCount; ++i) {
            if (!pieces[collection][i].finalized) revert NotFinalized();
        }
        c.isSealed = true;
        emit CollectionSealed(collection);
    }

    // ---------- buying ----------

    function mint(address collection, uint256 pieceId, address broker) external payable nonReentrant {
        Collection storage c = collections[collection];
        _checkMintable(c, collection, pieceId);
        if (c.priceETH == 0 || msg.value != c.priceETH) revert WrongPrice();
        pieces[collection][pieceId].minted = true;
        _credit(collection, msg.sender, broker, ETH, msg.value);
        IArtCollection(collection).mint(msg.sender, pieceId);
    }

    function mintWithIMD(address collection, uint256 pieceId, address broker, uint256 price) external nonReentrant {
        Collection storage c = collections[collection];
        _checkMintable(c, collection, pieceId);
        if (c.priceIMD == 0 || price != c.priceIMD) revert WrongPrice();
        pieces[collection][pieceId].minted = true;
        _credit(collection, msg.sender, broker, imd, price);
        _pullIMD(msg.sender, price);
        IArtCollection(collection).mint(msg.sender, pieceId);
    }

    function _checkMintable(Collection storage c, address collection, uint256 pieceId) private view {
        if (!c.exists || c.isModule) revert UnknownCollection();
        if (!c.open) revert SaleClosed();
        if (pieceId >= c.pieceCount) revert BadPieceId();
        Piece storage p = pieces[collection][pieceId];
        if (!p.finalized) revert NotFinalized();
        if (p.minted) revert AlreadyMinted();
    }

    function _pullIMD(address from, uint256 amount) private {
        IERC20 token = IERC20(imd);
        uint256 before = token.balanceOf(address(this));
        if (!token.transferFrom(from, address(this), amount)) revert TransferFailed();
        if (token.balanceOf(address(this)) - before != amount) revert TransferFailed();
    }

    /// @notice An ARTIFACTS piece contract credits a resale's royalty and broker share here, so the artist and
    /// brokers withdraw once from the ledger instead of from each piece. The caller must be a piece of an approved
    /// module collection, as that module confirms; the ETH comes with the call.
    function recordResale(address broker, uint256 royalty, uint256 brokerShare) external payable nonReentrant {
        address module = IPieceController(msg.sender).controller();
        Collection storage c = collections[module];
        if (!saleModules[module] || !c.exists || !c.isModule || !IPieceRegistry(module).isPiece(msg.sender)) {
            revert NotPiece();
        }
        if (msg.value != royalty + brokerShare) revert WrongPrice();
        if (brokerShare > 0 && !isEligibleBroker(broker)) revert NotEligibleBroker();
        if (brokerShare > 0) balances[broker][ETH] += brokerShare;
        emit Resale(module, msg.sender, brokerShare > 0 ? broker : address(0), royalty, brokerShare);
        _payArtist(c.artist, ETH, royalty);
    }

    /// @notice Whether `module` can record a sale of its own collection now: an approved sale module registered as a
    /// module collection. A module checks this before taking bids it will settle later.
    function canRecordSale(address module) external view returns (bool) {
        Collection storage c = collections[module];
        return saleModules[module] && c.exists && c.isModule;
    }

    /// @notice Approved sale modules record an ETH sale of a module collection; the ETH comes with the call.
    function recordSale(address collection, address buyer, address broker) external payable nonReentrant {
        if (!saleModules[msg.sender]) revert NotSaleModule();
        Collection storage c = collections[collection];
        if (!c.exists || !c.isModule) revert NotModuleCollection();
        if (msg.value == 0) revert WrongPrice();
        _credit(collection, buyer, broker, ETH, msg.value);
    }

    function _credit(address collection, address buyer, address broker, address currency, uint256 amount) private {
        Collection storage c = collections[collection];
        uint256 artistShare = (amount * c.artistBps) / BPS;
        uint256 burnShare = (amount * c.burnBps) / BPS;
        uint256 brokerShare = (amount * c.brokerBps) / BPS;
        if (isEligibleBroker(broker)) {
            balances[broker][currency] += brokerShare;
        } else {
            // No agent brought this sale: their share buys back and burns IMD, on every collection.
            burnShare += brokerShare;
            brokerShare = 0;
            broker = address(0);
        }
        uint256 houseShare = amount - artistShare - burnShare - brokerShare; // its share and the rounding
        if (c.houseBps == 0) {
            // a collection with no house share (THE SOURCE): what the house would have kept goes to the artist
            artistShare += houseShare;
            houseShare = 0;
        }
        balances[address(this)][currency] += houseShare;
        balances[BUYBACK][currency] += burnShare;
        emit Sale(collection, buyer, broker, currency, amount, brokerShare, houseShare, artistShare, burnShare);
        _payArtist(c.artist, currency, artistShare); // last: every other share is already recorded
    }

    /// @dev The artist's ETH share goes straight to their payout address, with enough gas for a wallet or a Safe to
    /// receive it and little more. If it can't take it, or the share is in another currency, it waits in their
    /// balance for withdraw, as every other share does, so a sale never fails because of the artist's address.
    function _payArtist(address artist, address currency, uint256 amount) private {
        if (amount == 0) return;
        if (currency == ETH) {
            address to = artists[artist].payout;
            if (to == address(0)) to = artist;
            uint256 g = ARTIST_PAY_GAS;
            bool ok;
            assembly ("memory-safe") {
                ok := call(g, to, amount, 0, 0, 0, 0) // nothing returned is copied: no return-data bomb
            }
            if (ok) {
                emit ArtistPaid(artist, to, amount);
                return;
            }
        }
        balances[artist][currency] += amount;
        emit ArtistCredited(artist, currency, amount);
    }

    // ---------- withdrawals ----------

    /// @notice Artists and brokers withdraw their own balance; an artist's goes to their payout address.
    function withdraw(address currency) external nonReentrant {
        uint256 amount = balances[msg.sender][currency];
        if (amount == 0) revert NothingToWithdraw();
        balances[msg.sender][currency] = 0;
        address to = artists[msg.sender].payout;
        if (to == address(0)) to = msg.sender;
        _pay(currency, to, amount);
        emit Withdrawn(msg.sender, currency, to, amount);
    }

    /// @notice The contract that buys back and burns IMD with the buyback balance. Set once, so what is set aside to
    /// burn can never go anywhere else.
    function setBuybackBurner(address burner) external onlyOwner {
        if (buybackBurner != address(0)) revert BuybackBurnerAlreadySet();
        if (burner == address(0)) revert ZeroAddress();
        buybackBurner = burner;
        emit BuybackBurnerSet(burner);
    }

    /// @notice Anyone may send the buyback balance (in one currency) to the buyback burner.
    function releaseBuyback(address currency) external nonReentrant {
        address burner = buybackBurner;
        if (burner == address(0)) revert NoBuybackBurner();
        uint256 amount = balances[BUYBACK][currency];
        if (amount == 0) revert NothingToWithdraw();
        balances[BUYBACK][currency] = 0;
        _pay(currency, burner, amount);
        emit BuybackReleased(currency, burner, amount);
    }

    /// @notice The house balance goes to the current owner.
    function withdrawHouse(address currency) external nonReentrant onlyOwner {
        uint256 amount = balances[address(this)][currency];
        if (amount == 0) revert NothingToWithdraw();
        balances[address(this)][currency] = 0;
        _pay(currency, owner, amount);
        emit Withdrawn(address(this), currency, owner, amount);
    }

    function _pay(address currency, address to, uint256 amount) private {
        if (currency == ETH) {
            (bool ok,) = to.call{value: amount}("");
            if (!ok) revert TransferFailed();
        } else {
            if (!IERC20(currency).transfer(to, amount)) revert TransferFailed();
        }
    }

    // ---------- views for collections ----------

    function royaltyFor(address collection, uint256 salePrice) external view returns (address, uint256) {
        Collection storage c = collections[collection];
        if (!c.exists) revert UnknownCollection();
        return (artists[c.artist].payout, (salePrice * ROYALTY_BPS) / BPS);
    }

    function pieceMetadata(address collection, uint256 pieceId)
        external
        view
        returns (string memory title, string memory description, bytes memory svg)
    {
        Piece storage p = pieces[collection][pieceId];
        return (p.title, p.description, artStorage.read(collection, pieceId));
    }

    function artistPayout(address artist) external view returns (address) {
        return artists[artist].payout;
    }

    // ---------- submissions ----------

    function submit(bytes32 contentHash, string calldata previewURI) external returns (uint256 id) {
        if (contentHash == bytes32(0)) revert BadSubmission();
        id = submissions.length;
        submissions.push(Submission(msg.sender, contentHash, previewURI, SubmissionStatus.Pending));
        emit Submitted(id, msg.sender, contentHash, previewURI);
    }

    function decideSubmission(uint256 id, bool accept) external onlyOwner {
        if (id >= submissions.length) revert BadSubmission();
        Submission storage s = submissions[id];
        if (s.status != SubmissionStatus.Pending) revert NotPending();
        s.status = accept ? SubmissionStatus.Accepted : SubmissionStatus.Rejected;
        emit SubmissionDecided(id, s.status);
    }

    function submissionCount() external view returns (uint256) {
        return submissions.length;
    }
}

src/ArtCollection.sol

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

import {ERC721Lite} from "./base/ERC721Lite.sol";
import {Encoding} from "./libs/Encoding.sol";
import {IArtHouse} from "./interfaces/Interfaces.sol";

/// @notice A plain SVG collection: ERC-721 + ERC-2981 runtime copy, minted only by ArtHouse, with on-chain base64 JSON metadata.
contract ArtCollection is ERC721Lite {
    IArtHouse public house;

    error AlreadyInitialized();
    error NotHouse();

    constructor() {
        // Lock the implementation itself: only independent runtime copies can be initialised.
        house = IArtHouse(address(this));
    }

    function initialize(address house_, string calldata name_, string calldata symbol_) external {
        if (address(house) != address(0)) revert AlreadyInitialized();
        if (msg.sender != house_ || house_.code.length == 0) revert NotHouse();
        house = IArtHouse(house_);
        _name = name_;
        _symbol = symbol_;
    }

    function mint(address to, uint256 tokenId) external {
        if (msg.sender != address(house)) revert NotHouse();
        _mint(to, tokenId);
    }

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

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

    function tokenURI(uint256 tokenId) external view returns (string memory) {
        ownerOf(tokenId);
        (string memory title, string memory description, bytes memory svg) = house.pieceMetadata(address(this), tokenId);
        bytes memory json = abi.encodePacked(
            '{"name":"',
            title,
            '","description":"',
            description,
            '","image":"data:image/svg+xml;base64,',
            Encoding.base64(svg),
            '"}'
        );
        return string.concat("data:application/json;base64,", Encoding.base64(json));
    }
}

src/ArtStorage.sol

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

import {TwoStepOwnable} from "./base/TwoStepOwnable.sol";
import {SSTORE2} from "./libs/SSTORE2.sol";

/// @notice SSTORE2 chunk store for plain SVG collections. Only ArtHouse may write, after the owner's one-time setHouse.
contract ArtStorage is TwoStepOwnable {
    address public house;

    // collection => pieceId => chunk pointers
    mapping(address => mapping(uint256 => address[])) private _chunks;

    event HouseSet(address indexed house);
    event ChunkWritten(
        address indexed collection, uint256 indexed pieceId, uint256 index, address pointer, uint256 size
    );
    event PieceCleared(address indexed collection, uint256 indexed pieceId);

    error HouseAlreadySet();
    error NotHouse();
    error BadIndex();

    constructor(address owner_) TwoStepOwnable(owner_) {}

    function setHouse(address house_) external onlyOwner {
        if (house != address(0)) revert HouseAlreadySet();
        if (house_ == address(0)) revert ZeroAddress();
        house = house_;
        emit HouseSet(house_);
    }

    modifier onlyHouse() {
        if (msg.sender != house) revert NotHouse();
        _;
    }

    function write(address collection, uint256 pieceId, uint256 index, bytes calldata data)
        external
        onlyHouse
        returns (address pointer)
    {
        address[] storage list = _chunks[collection][pieceId];
        if (index != list.length) revert BadIndex();
        pointer = SSTORE2.write(data);
        list.push(pointer);
        emit ChunkWritten(collection, pieceId, index, pointer, data.length);
    }

    function clear(address collection, uint256 pieceId) external onlyHouse {
        delete _chunks[collection][pieceId];
        emit PieceCleared(collection, pieceId);
    }

    function chunkCount(address collection, uint256 pieceId) external view returns (uint256) {
        return _chunks[collection][pieceId].length;
    }

    function chunk(address collection, uint256 pieceId, uint256 index) external view returns (address) {
        return _chunks[collection][pieceId][index];
    }

    function size(address collection, uint256 pieceId) public view returns (uint256 total) {
        address[] storage list = _chunks[collection][pieceId];
        for (uint256 i; i < list.length; ++i) {
            total += SSTORE2.size(list[i]);
        }
    }

    function read(address collection, uint256 pieceId) external view returns (bytes memory data) {
        address[] storage list = _chunks[collection][pieceId];
        data = new bytes(size(collection, pieceId));
        uint256 offset;
        for (uint256 i; i < list.length; ++i) {
            uint256 dest;
            assembly ("memory-safe") {
                dest := add(add(data, 32), offset)
            }
            offset += SSTORE2.copyTo(list[i], dest);
        }
    }
}

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/base/TwoStepOwnable.sol

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

/// @notice Two-step ownership with no renounce path. The curator (owner) nominates a successor who must accept.
abstract contract TwoStepOwnable {
    address public owner;
    address public pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    error NotOwner();
    error NotPendingOwner();
    error ZeroAddress();

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

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

    function transferOwnership(address newOwner) external onlyOwner {
        if (newOwner == address(0)) revert ZeroAddress();
        pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner, newOwner);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert NotPendingOwner();
        address previous = owner;
        owner = msg.sender;
        pendingOwner = address(0);
        emit OwnershipTransferred(previous, msg.sender);
    }
}

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/Clones.sol

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

/// @notice Independent runtime-copy deployment, without proxies or DELEGATECALL.
library Clones {
    error CloneFailed();

    /// @notice Deploys a full, independent copy of `implementation`'s runtime code (no proxy, no DELEGATECALL).
    /// The init code is: PUSH20 impl, EXTCODESIZE, DUP1, PUSH0, PUSH0, PUSH20 impl, EXTCODECOPY, PUSH0, RETURN.
    /// Used for plain collections, ARTIFACTS editions and THE SOURCE. Storage is initialized by the caller
    /// immediately after creation; immutables embedded in the implementation's runtime are preserved.
    function copyCode(address implementation) internal returns (address instance) {
        bytes memory initCode = abi.encodePacked(hex"73", implementation, hex"3b805f5f73", implementation, hex"3c5ff3");
        assembly ("memory-safe") {
            instance := create(0, add(initCode, 32), mload(initCode))
        }
        if (instance == address(0) || instance.code.length == 0) revert CloneFailed();
    }
}

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)
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none"
  },
  "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.