Skip to content
Verified contractPartialMIT

OSKernel

Address0x3166ebf50f9ac119949c45cd1920e12067f406b2
Balance

0 ETH

 

Transactions

4

 

Compiler

solc 0.8.26

 

Same code

1 more 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: no, runtime code: yes
Verified on Sourcify
Created in block
26,307,870
Creation transaction
0xf66dd43581…54a637766a

src/os/OSKernel.sol

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

import {ERC721Lite} from "../base/ERC721Lite.sol";
import {ReentrancyGuard} from "../base/ReentrancyGuard.sol";
import {Encoding} from "../libs/Encoding.sol";
import {KeyProof} from "../KeyProof.sol";
import {IArtHouse} from "../interfaces/Interfaces.sol";
import {IEdition, IEditionRegistry, IOSFactory, IOSMetadata} from "./IOS.sol";

/// @notice One ARTIFACTS Operating System: a contract that holds editions as its windows and opens them for its
/// users. Its login is a version 2 viewing key, registered on every piece it holds; each piece's key is wrapped to
/// the login, and the login's secret is wrapped to each user's own viewing key, so a user opens every window with one
/// signature and nothing is sent anywhere. The OS is booted by OSFactory as an independent runtime copy of this
/// kernel (no proxy, no DELEGATECALL).
///
/// A living OS holds up to 7 windows. With 2 to 7, its installers may mint its one output (Tiled, Overprint or
/// Merged field), which dissolves the OS in place: this contract becomes the output, one token, and the editions stay
/// in it for good. The minter picks epoch 0's roll; from then on a new roll each week (OSFactory's draw). The output's
/// holder may reveal it forever, by posting the editions' keys, each checked against its commitment. It sells through
/// its own keyed escrow, as a piece does, with the artist's royalty.
contract OSKernel is ERC721Lite, ReentrancyGuard {
    uint256 public constant TOKEN_ID = 1;
    uint256 public constant MAX_WINDOWS = 7;
    uint256 public constant MIN_OUTPUT = 2; // an output uses 2 to 7 editions
    uint256 public constant MAX_USERS = 16;
    uint8 public constant TILED = 1;
    uint8 public constant OVERPRINT = 2;
    uint8 public constant MERGED = 3;
    uint256 public constant ESCROW_TIMEOUT = 72 hours; // the buyer's time to check the keys, from when they arrive
    uint16 public constant DEPOSIT_BPS = 1_000; // the seller's deposit sent with the keys: 10% of the price
    uint256 public constant SELLER_WINDOW = 24 hours; // from paying, only the seller may end a sale (keys or refund)
    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;

    IOSFactory public immutable factory;
    IEditionRegistry public immutable artifacts; // ArtifactsFactory: genuine editions, and the royalty's collection
    IArtHouse public immutable house;
    KeyProof public immutable keyProof;

    bool private _initialized;
    string public osName;
    address public admin;
    bytes32 public login; // the OS's viewing key (public half), registered on every piece it holds

    address[] private _windows;
    mapping(address => address) public installerOf; // piece => the user who installed it
    mapping(address => address) public ejectedBy; // piece => who may still forward its key after ejecting it
    address[] private _users;
    mapping(address => bytes) public wrappedLoginOf; // the login's secret, wrapped to each user's viewing key
    mapping(address => bool) public rewrapRequested; // a user whose wrap doesn't open asks the admin for a new one
    uint256 public layout; // counts installs and ejects: a mint approval names the layout it approved
    mapping(address => bytes32) public approvalOf; // installer => the mint they approved

    // ---------- the output, once minted ----------
    bool public minted;
    uint8 public composition;
    bytes32 public roll0; // epoch 0's roll, picked by the minter
    uint256 public mintWeek; // OSFactory's week of the mint: epoch e is week mintWeek + e
    uint256 public number; // 1 to 64, in the order outputs are minted
    bool public revealed;
    bool public frozen; // its holder froze it at a past epoch's design, for good
    uint256 public frozenEpoch;
    bytes32[] private _revealedKeys;

    // ---------- the holder's keys and the keyed resale escrow ----------
    bytes[] private _holderKeys; // each edition's key wrapped to the holder (empty: the minter opens with the login)
    address public previousOwner; // may post the keys once 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;
        address broker;
        uint64 keyPostedAt;
        bytes32 viewingKey;
        uint256 deposit;
    }

    Escrow public escrow;
    bytes[] private _escrowKeys;
    bool private _releasing;
    uint256 public listing; // counts listings: a purchase names the one it was priced on
    uint256 private _touched; // the epoch last signalled to marketplaces, plus one
    uint256 public royaltyOwed; // the artist's royalty from sales here, paid to their payout as it is when withdrawn
    bool public installsClosed; // the admin closes the windows while the installers collect their mint approvals

    event Booted(address indexed admin, string name, bytes32 login);
    event UserAdded(address indexed user);
    event RewrapRequested(address indexed user);
    event Installed(address indexed piece, address indexed installer);
    event Ejected(address indexed piece, address indexed installer, address indexed to);
    event KeyForwarded(address indexed piece);
    event Returned(address indexed piece, address indexed to);
    event MintApproved(address indexed installer, bytes32 proposal);
    event Minted(uint256 indexed number, uint8 composition, bytes32 roll, address indexed recipient);
    event Revealed();
    event Frozen(uint256 epoch, bytes32 roll);
    event ViewingKeyRegistered(address indexed account, bytes32 key);
    event KeysPosted(address indexed by, address indexed forOwner);
    event InstallsClosed(bool closed);
    event MetadataUpdate(uint256 _tokenId); // EIP-4906: the token image changed (a freeze, a reveal)
    event RoyaltyWithdrawn(address indexed to, uint256 amount);
    event Listed(address indexed seller, uint256 price, uint256 listing);
    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, uint256 window);
    event EscrowReleased(
        address indexed seller,
        address indexed buyer,
        uint256 price,
        uint256 royalty,
        address broker,
        uint256 brokerShare
    );
    event Withdrawn(address indexed to, uint256 amount);

    error AlreadyInitialized();
    error NotFactory();
    error NotAdmin();
    error NotUser();
    error BadUser();
    error TooManyUsers();
    error BadWrap();
    error NotEdition();
    error NotHeld();
    error AlreadyInstalled();
    error Full();
    error NotInstaller();
    error LayoutChanged();
    error NoSender();
    error Dissolved();
    error NotMinted();
    error TooFewWindows();
    error BadComposition();
    error BadRecipient();
    error KeyMissing();
    error FutureEpoch();
    error NotTokenOwner();
    error NotPreviousOwner();
    error AlreadyRevealed();
    error AlreadyFrozen();
    error NotAPastEpoch();
    error WrongKey();
    error WrongCount();
    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 BadWrappedKey();
    error KeyOpens();
    error TransferFailed();
    error NothingToWithdraw();
    error InstallsAreClosed();
    error NotRequested();
    error ListingChanged();

    constructor(address factory_, address artifacts_, address house_, address keyProof_) {
        factory = IOSFactory(factory_);
        artifacts = IEditionRegistry(artifacts_);
        house = IArtHouse(house_);
        keyProof = KeyProof(keyProof_);
        _initialized = true; // lock the kernel itself; only its runtime copies boot
    }

    /// @notice Boot: by OSFactory, in the transaction that copies this kernel. The creator is the admin and the first
    /// user, with the login's secret wrapped to their own viewing key by their browser.
    function initialize(address admin_, string calldata name_, bytes32 login_, bytes calldata wrappedLogin_)
        external
    {
        if (_initialized) revert AlreadyInitialized();
        if (msg.sender != address(factory)) revert NotFactory();
        _initialized = true;
        osName = name_;
        admin = admin_;
        login = login_;
        _symbol = "ARTIFACTS OS";
        _addUser(admin_, wrappedLogin_);
        emit Booted(admin_, name_, login_);
    }

    // ---------- users ----------

    /// @notice The admin adds a user, with the login's secret wrapped to the user's viewing key (the admin's browser
    /// opens the login and wraps it). Again for an existing user replaces their wrap, but only when that user asked
    /// (requestRewrap: theirs doesn't open), so an admin can't lock a user out. A view can't be taken back, so there
    /// is no removing a user.
    function addUser(address user, bytes calldata wrapped) external {
        if (msg.sender != admin) revert NotAdmin();
        if (minted) revert Dissolved();
        if (wrappedLoginOf[user].length != 0) {
            if (!rewrapRequested[user]) revert NotRequested();
            if (!_isWrap(wrapped)) revert BadWrap();
            delete rewrapRequested[user];
            wrappedLoginOf[user] = wrapped;
            emit UserAdded(user);
            return;
        }
        _addUser(user, wrapped);
    }

    /// @notice A user whose login wrap doesn't open asks the admin for a new one.
    function requestRewrap() external {
        if (!isUser(msg.sender)) revert NotUser();
        if (minted) revert Dissolved();
        rewrapRequested[msg.sender] = true;
        emit RewrapRequested(msg.sender);
    }

    /// @notice A user replaces their own login wrap (wrapped to a new viewing key of theirs, say).
    function setLoginWrap(bytes calldata wrapped) external {
        if (!isUser(msg.sender)) revert NotUser();
        if (minted) revert Dissolved();
        if (!_isWrap(wrapped)) revert BadWrap();
        delete rewrapRequested[msg.sender];
        wrappedLoginOf[msg.sender] = wrapped;
        emit UserAdded(msg.sender);
    }

    function _addUser(address user, bytes calldata wrapped) private {
        if (user == address(0)) revert BadUser();
        if (!_isWrap(wrapped)) revert BadWrap();
        if (_users.length >= MAX_USERS) revert TooManyUsers();
        _users.push(user);
        wrappedLoginOf[user] = wrapped;
        emit UserAdded(user);
    }

    /// @dev A version 2 wrapped key: 0x02, the wrapper's point, the masked secret.
    function _isWrap(bytes calldata wrapped) private pure returns (bool) {
        return wrapped.length == 65 && wrapped[0] == 0x02;
    }

    function isUser(address account) public view returns (bool) {
        return wrappedLoginOf[account].length != 0;
    }

    // ---------- install, eject ----------

    /// @notice Install: a user sends an edition here with safeTransferFrom. The OS records it and who installed it,
    /// and registers its login on the piece, in the same step; the installer then wraps the piece's key to the login
    /// and posts it on the piece (`rewrapFor`), as its previous owner.
    function onERC721Received(address, address from, uint256, bytes calldata) external returns (bytes4) {
        _install(msg.sender, from);
        return this.onERC721Received.selector;
    }

    function _install(address piece, address from) private {
        if (minted) revert Dissolved();
        if (installsClosed) revert InstallsAreClosed();
        if (!artifacts.isPiece(piece)) revert NotEdition();
        if (IEdition(piece).ownerOf(TOKEN_ID) != address(this)) revert NotHeld();
        if (installerOf[piece] != address(0)) revert AlreadyInstalled();
        if (!isUser(from)) revert NotUser();
        if (_windows.length >= MAX_WINDOWS) revert Full();
        installerOf[piece] = from;
        delete ejectedBy[piece];
        _windows.push(piece);
        ++layout;
        IEdition(piece).registerViewingKey(login);
        emit Installed(piece, from);
    }

    /// @notice An edition sent here with a plain transfer (no install step ran): anyone may settle it. From a user,
    /// with room, while the OS lives and its windows are open, it is installed as theirs; otherwise it goes back to
    /// whoever sent it, who may then post its key to themselves through the OS (forwardKey), as its previous owner.
    /// Settle it before anyone posts its key: posting ends the piece's record of who sent it (its previousOwner),
    /// and without that it can't be sent back.
    function adopt(address piece) external nonReentrant {
        if (!artifacts.isPiece(piece) || IEdition(piece).ownerOf(TOKEN_ID) != address(this)) revert NotHeld();
        if (installerOf[piece] != address(0)) revert AlreadyInstalled();
        address from = IEdition(piece).previousOwner();
        if (from == address(0)) revert NoSender();
        if (!minted && !installsClosed && isUser(from) && _windows.length < MAX_WINDOWS) {
            _install(piece, from);
        } else {
            ejectedBy[piece] = from;
            IEdition(piece).transferFrom(address(this), from, TOKEN_ID);
            emit Returned(piece, from);
        }
    }

    /// @notice Eject: the piece's installer sends it to a wallet. The OS becomes its previous owner, so it can post
    /// the piece's key for the receiver once: here at once when the receiver's viewing key is already registered on
    /// the piece (`wrapped`, made by the installer's browser with the login), or later with forwardKey.
    function eject(address piece, address to, bytes calldata wrapped) external nonReentrant {
        if (minted) revert Dissolved();
        if (installerOf[piece] != msg.sender) revert NotInstaller();
        if (to == address(0)) revert BadRecipient();
        delete installerOf[piece];
        _removeWindow(piece);
        ++layout;
        ejectedBy[piece] = msg.sender;
        emit Ejected(piece, msg.sender, to);
        IEdition(piece).safeTransferFrom(address(this), to, TOKEN_ID);
        if (wrapped.length != 0) _forward(piece, wrapped);
    }

    /// @notice The admin closes the windows (or opens them again) while the installers collect their mint approvals,
    /// so no one can change the layout under them by installing: users can't be removed, and an install voids every
    /// approval. Installers may still eject their own windows.
    function setInstallsClosed(bool closed) external {
        if (msg.sender != admin) revert NotAdmin();
        if (minted) revert Dissolved();
        installsClosed = closed;
        emit InstallsClosed(closed);
    }

    /// @notice The ejecting installer posts the piece's key, wrapped to its new owner's viewing key. Once.
    function forwardKey(address piece, bytes calldata wrapped) external nonReentrant {
        if (ejectedBy[piece] != msg.sender) revert NotInstaller();
        _forward(piece, wrapped);
    }

    function _forward(address piece, bytes calldata wrapped) private {
        if (!_isWrap(wrapped)) revert BadWrap(); // the piece takes one key, once: at least a version 2 wrap
        delete ejectedBy[piece];
        IEdition(piece).rewrapFor(wrapped);
        emit KeyForwarded(piece);
    }

    function _removeWindow(address piece) private {
        uint256 n = _windows.length;
        for (uint256 i; i < n; ++i) {
            if (_windows[i] == piece) {
                _windows[i] = _windows[n - 1];
                _windows.pop();
                return;
            }
        }
    }

    // ---------- mint: the OS dissolves into its output ----------

    /// @notice What a mint approval names: the composition, epoch 0's roll, the recipient and the current layout.
    function proposalOf(uint8 composition_, bytes32 roll_, address recipient) public view returns (bytes32) {
        return keccak256(abi.encode(composition_, roll_, recipient, layout));
    }

    /// @notice An installer approves the output: composition (TILED, OVERPRINT or MERGED), epoch 0's roll and the
    /// recipient, who must be one of the installers, for the windows they saw: `expectedLayout`, the `layout` their
    /// preview was drawn from (an install or eject landing first makes it revert, so no one approves, or mints,
    /// windows they never saw). When every installer has approved the same, for the same windows, the OS mints: one
    /// approval in an OS whose windows one wallet installed. Every window needs its key posted (the installers'
    /// browsers open each before approving). Minting takes the next number of 64 and closes the OS for good: no
    /// install, eject, user or mint after it.
    function mint(uint8 composition_, bytes32 roll_, address recipient, uint256 expectedLayout)
        external
        nonReentrant
        returns (bool done)
    {
        if (minted) revert Dissolved();
        if (expectedLayout != layout) revert LayoutChanged();
        uint256 n = _windows.length;
        if (n < MIN_OUTPUT) revert TooFewWindows();
        if (composition_ < TILED || composition_ > MERGED) revert BadComposition();
        bytes32 proposal = proposalOf(composition_, roll_, recipient);
        bool sender;
        bool receives;
        bool pending;
        for (uint256 i; i < n; ++i) {
            address piece = _windows[i];
            address inst = installerOf[piece];
            if (inst == msg.sender) sender = true;
            if (inst == recipient) receives = true;
            if (inst != msg.sender && approvalOf[inst] != proposal) pending = true;
            bytes memory windowKey = IEdition(piece).wrappedKey(); // to the login: a version 2 wrap, at least
            if (windowKey.length == 0) revert KeyMissing();
            if (windowKey.length != 65 || windowKey[0] != 0x02) revert BadWrap();
        }
        if (!sender) revert NotInstaller();
        if (!receives) revert BadRecipient();
        approvalOf[msg.sender] = proposal;
        emit MintApproved(msg.sender, proposal);
        if (pending) return false;

        number = factory.claimNumber(); // reverts once 64 outputs exist
        minted = true;
        composition = composition_;
        roll0 = roll_;
        mintWeek = factory.currentWeek();
        _mint(recipient, TOKEN_ID);
        emit Minted(number, composition_, roll_, recipient);
        return true;
    }

    // ---------- epochs ----------

    /// @notice The output's epoch now: 0 from the mint until the first Monday 00:00 UTC, then one more each week.
    function epoch() public view returns (uint256) {
        if (!minted) return 0;
        return factory.currentWeek() - mintWeek;
    }

    /// @notice An epoch's roll: the minter's for epoch 0; for each week after, from that week's random number,
    /// keccak256(week, random, this output, epoch 0's roll), so no two outputs move alike. A week whose number was
    /// never drawn takes keccak256(week, this output, epoch 0's roll). This week's roll is final once its number
    /// arrives, or once the week ends without one.
    function rollOf(uint256 e) public view returns (bytes32) {
        if (!minted) revert NotMinted();
        if (e == 0) return roll0;
        if (e > epoch()) revert FutureEpoch();
        uint256 week = mintWeek + e;
        uint256 random = factory.weekRandom(week);
        return random != 0
            ? keccak256(abi.encode(week, random, address(this), roll0))
            : keccak256(abi.encode(week, address(this), roll0));
    }

    /// @notice The epoch its design shows: this week's, or the past one its holder froze it at.
    function shownEpoch() public view returns (uint256) {
        return frozen ? frozenEpoch : epoch();
    }

    /// @notice The roll its design shows: this week's, or the frozen epoch's.
    function roll() external view returns (bytes32) {
        return rollOf(shownEpoch());
    }

    /// @notice The holder freezes it at a past epoch's design (`e` before this week's, epoch 0 included): from then on
    /// it shows that design for good and the weeks no longer turn it, for every later holder too. Once. Not while a
    /// buyer's payment sits in escrow (they paid for it as it stood); a listing with no buyer yet is taken down.
    function freeze(uint256 e) external {
        if (msg.sender != ownerOf(TOKEN_ID)) revert NotTokenOwner();
        if (frozen) revert AlreadyFrozen();
        if (e >= epoch()) revert NotAPastEpoch();
        if (escrow.buyer != address(0)) revert EscrowActive();
        frozen = true;
        frozenEpoch = e;
        if (escrow.seller != address(0)) {
            delete escrow;
            emit Delisted();
        }
        emit Frozen(e, rollOf(e));
        emit MetadataUpdate(TOKEN_ID);
    }

    /// @notice Anyone tells marketplaces this week's design is up (EIP-4906); the weekly keeper calls it after the draw.
    /// The image follows the week by itself: this only asks indexers to look again.
    function touch() external {
        if (!minted) revert NotMinted();
        uint256 e = epoch();
        // twice an epoch at most: as it begins (its fixed roll), and again once its number lands
        uint256 mark = (e + 1) * 2 + (e != 0 && factory.weekRandom(mintWeek + e) != 0 ? 1 : 0);
        if (frozen || _touched == mark) return;
        _touched = mark;
        emit MetadataUpdate(TOKEN_ID);
    }

    // ---------- reveal ----------

    /// @notice The holder reveals the output to everyone, once and forever, by posting the key of every edition in
    /// it, in window order; each must match its piece's commitment. This reveals the editions too: they stay in the
    /// output, so a revealed edition never trades on its own. Not while a buyer's payment sits in escrow (they paid
    /// for it sealed); a listing with no buyer yet is taken down.
    function reveal(bytes32[] calldata keys) external {
        if (msg.sender != ownerOf(TOKEN_ID)) revert NotTokenOwner();
        if (revealed) revert AlreadyRevealed();
        if (escrow.buyer != address(0)) revert EscrowActive();
        uint256 n = _windows.length;
        if (keys.length != n) revert WrongCount();
        for (uint256 i; i < n; ++i) {
            if (keccak256(abi.encodePacked(keys[i])) != IEdition(_windows[i]).commitment()) revert WrongKey();
        }
        _revealedKeys = keys;
        revealed = true;
        if (escrow.seller != address(0)) {
            delete escrow;
            emit Delisted();
        }
        emit Revealed();
        emit MetadataUpdate(TOKEN_ID);
    }

    // ---------- the holder's 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 holder wraps each edition's key to the new holder's viewing key and
    /// posts them here, in window order. Once: posting ends the previous holder's right, so each must at least be a
    /// version 2 wrap (0x02, a point, a masked key), as the editions themselves require.
    function rewrapFor(bytes[] calldata wrapped) external {
        if (msg.sender != previousOwner) revert NotPreviousOwner();
        if (_holderKeys.length != 0) revert KeyAlreadyPosted();
        if (wrapped.length != _windows.length) revert WrongCount();
        address current = ownerOf(TOKEN_ID);
        if (viewingKeyOf[current] == bytes32(0)) revert NoViewingKey();
        for (uint256 i; i < wrapped.length; ++i) {
            if (!_isWrap(wrapped[i])) revert BadWrap();
            _holderKeys.push(wrapped[i]);
        }
        delete previousOwner;
        emit KeysPosted(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, ++listing);
    }

    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 and registers their viewing key for this purchase (a version 2 key, so
    /// a fake key can be proven), naming the broker who brought them (or zero) and the listing they were shown
    /// (`listingId`, the listing's number): a reveal or freeze takes a listing down, so a relisting ahead of a pending
    /// purchase makes it revert instead of buying a changed output. A revealed output needs no keys: the sale settles
    /// at once.
    function buy(bytes32 viewingKey, address broker, uint256 listingId) external payable nonReentrant {
        Escrow storage e = escrow;
        if (e.seller == address(0)) revert NotListed();
        if (listingId != listing) revert ListingChanged();
        if (e.buyer != address(0)) revert EscrowActive();
        if (msg.value != e.price) revert WrongPrice();
        if (msg.sender == e.seller) revert NotEscrowBuyer();
        emit EscrowPaid(msg.sender, msg.value);
        if (revealed) {
            address seller = e.seller;
            delete escrow;
            _settle(seller, msg.sender, broker, msg.value, 0);
            return;
        }
        if (!keyProof.isViewingKey(viewingKey)) revert NoViewingKey();
        e.buyer = msg.sender;
        e.paidAt = uint64(block.timestamp);
        e.broker = broker;
        e.viewingKey = viewingKey;
        viewingKeyOf[msg.sender] = viewingKey;
        emit ViewingKeyRegistered(msg.sender, viewingKey);
    }

    function depositFor(uint256 price) public pure returns (uint256) {
        return (price * DEPOSIT_BPS) / BPS;
    }

    /// @notice The seller sends every edition's key, in window order, each wrapped to the buyer's viewing key for this
    /// purchase with its proof that the seller made it (KeyProof.knowsWrap), and a deposit of 10% of the price: back
    /// to the seller at release, the buyer's if any key is proven fake. Before paidAt + SELLER_WINDOW.
    function postEscrowKeys(bytes[] calldata wrapped, address[] calldata r, uint256[] calldata 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();
        uint256 n = _windows.length;
        if (wrapped.length != n || r.length != n || z.length != n) revert WrongCount();
        if (msg.value != depositFor(e.price)) revert WrongPrice();
        delete _escrowKeys;
        for (uint256 i; i < n; ++i) {
            if (!keyProof.knowsWrap(wrapped[i], e.viewingKey, e.buyer, r[i], z[i])) revert BadWrappedKey();
            _escrowKeys.push(wrapped[i]);
        }
        e.keyPosted = true;
        e.keyPostedAt = uint64(block.timestamp);
        e.deposit = msg.value;
        emit EscrowKeyPosted();
    }

    /// @notice The buyer proves one of the keys doesn't open its edition (KeyProof): they get their payment and the
    /// seller's deposit, and the seller keeps the output. Any time until release.
    function proveFakeKey(uint256 window, KeyProof.Proof calldata proof) external nonReentrant {
        Escrow storage e = escrow;
        if (msg.sender != e.buyer) revert NotEscrowBuyer();
        if (!e.keyPosted) revert KeyNotPosted();
        if (window >= _escrowKeys.length) revert WrongCount();
        IEdition piece = IEdition(_windows[window]);
        if (!keyProof.isFake(
                _escrowKeys[window], piece.pieceId(), e.viewingKey, piece.commitment(), msg.sender, proof
            )) revert KeyOpens();
        uint256 amount = e.price + e.deposit;
        delete escrow;
        delete _escrowKeys;
        pendingWithdrawals[msg.sender] += amount;
        emit EscrowProvenFake(msg.sender, amount, window);
    }

    /// @notice The seller may end a sale before sending the keys: the buyer gets it all back.
    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 if the keys haven't come SELLER_WINDOW after paying.
    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);
        e.viewingKey = bytes32(0);
        pendingWithdrawals[buyer] += refund;
        emit EscrowCancelled(buyer);
    }

    /// @notice Release: by the buyer once the keys are posted, or by anyone 72 hours after they arrived.
    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;
        delete escrow;
        _settle(seller, buyer, broker, price, deposit);
        delete _holderKeys;
        for (uint256 i; i < _escrowKeys.length; ++i) {
            _holderKeys.push(_escrowKeys[i]);
        }
        delete _escrowKeys;
    }

    /// @dev Pays the seller (less the artist's royalty and the broker's share), all as pull payments, and moves the
    /// token. The royalty is the editions' own (the house's royalty for ArtifactsFactory's collection), owed to the
    /// artist rather than to one address: withdrawRoyalty pays it to their payout as it is then.
    function _settle(address seller, address buyer, address broker, uint256 price, uint256 deposit) private {
        (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;
        if (royalty > 0) royaltyOwed += royalty;
        if (brokerShare > 0) pendingWithdrawals[broker] += brokerShare;
        _releasing = true;
        _transfer(seller, buyer, TOKEN_ID);
        _releasing = false;
        delete previousOwner; // a paid seller keeps no re-key right
        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 {
        withdrawFor(msg.sender);
    }

    /// @notice Sends `payee` what this contract owes them. Anyone may call it, so a payee that can't call (a payment
    /// splitter, say) is still paid; the money only ever goes to the payee.
    function withdrawFor(address payee) public nonReentrant {
        uint256 amount = pendingWithdrawals[payee];
        if (amount == 0) revert NothingToWithdraw();
        pendingWithdrawals[payee] = 0;
        (bool ok,) = payee.call{value: amount}("");
        if (!ok) revert TransferFailed();
        emit Withdrawn(payee, amount);
    }

    /// @notice Sends the artist's royalty from this output's sales to their payout as it is now (ArtHouse's royalty
    /// receiver for the collection), so a payout that refused it, or was changed, is put right with setPayout. Anyone
    /// may call it; the money only ever goes to the artist's payout.
    function withdrawRoyalty() external nonReentrant {
        uint256 amount = royaltyOwed;
        if (amount == 0) revert NothingToWithdraw();
        (address to,) = royaltyInfo(TOKEN_ID, 0);
        if (to == address(0)) revert TransferFailed();
        royaltyOwed = 0;
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert TransferFailed();
        emit RoyaltyWithdrawn(to, amount);
    }

    /// @dev Plain transfers stay allowed, except while a buyer's payment sits in escrow. A transfer clears the
    /// holder's keys and remembers who can post them again; 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 _holderKeys;
    }

    // ---------- views and metadata ----------

    function windows() external view returns (address[] memory) {
        return _windows;
    }

    function users() external view returns (address[] memory) {
        return _users;
    }

    function holderKeys() external view returns (bytes[] memory) {
        return _holderKeys;
    }

    function escrowKeys() external view returns (bytes[] memory) {
        return _escrowKeys;
    }

    function revealedKeys() external view returns (bytes32[] memory) {
        return _revealedKeys;
    }

    /// @notice "ARTIFACTS · OS 001" once minted; the OS's own name while it lives.
    function name() public view override returns (string memory) {
        return minted ? string.concat(unicode"ARTIFACTS · OS ", Encoding.pad3(number)) : osName;
    }

    function royaltyInfo(uint256, uint256 salePrice) public view returns (address, uint256) {
        try house.royaltyFor(address(artifacts), salePrice) returns (address to, uint256 amount) {
            return (to, amount);
        } catch {
            return (address(0), 0);
        }
    }

    function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
        // ERC-2981 royalties, ERC-721 receiving (installs) and EIP-4906 metadata updates
        return interfaceId == 0x2a55205a || interfaceId == 0x150b7a02 || interfaceId == 0x49064906
            || super.supportsInterface(interfaceId);
    }

    function tokenURI(uint256 tokenId) external view returns (string memory) {
        ownerOf(tokenId);
        return IOSMetadata(factory.metadata()).tokenURI(address(this));
    }
}

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/os/IOS.sol

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

import {Traits} from "../interfaces/Interfaces.sol";

/// @notice What an Operating System uses of a deployed ARTIFACTS edition (ArtifactsPiece), unchanged.
interface IEdition {
    function ownerOf(uint256 tokenId) external view returns (address);
    function transferFrom(address from, address to, uint256 tokenId) external;
    function safeTransferFrom(address from, address to, uint256 tokenId) external;
    function registerViewingKey(bytes32 key) external;
    function rewrapFor(bytes calldata wrapped) external;
    function previousOwner() external view returns (address);
    function wrappedKey() external view returns (bytes memory);
    function commitment() external view returns (bytes32);
    function pieceId() external view returns (uint256);
    function traits() external view returns (Traits memory);
}

/// @notice ArtifactsFactory's answer to "is this contract a genuine edition?" (THE SOURCE is not one of its pieces).
interface IEditionRegistry {
    function isPiece(address piece) external view returns (bool);
}

/// @notice What an OS asks of the OS factory: its output number, the week, each week's random number, the metadata.
interface IOSFactory {
    function claimNumber() external returns (uint256);
    function currentWeek() external view returns (uint256);
    function weekRandom(uint256 week) external view returns (uint256);
    function metadata() external view returns (address);
}

/// @notice Draws an output's token metadata from the OS's public state.
interface IOSMetadata {
    function tokenURI(address os) external view returns (string memory);
}

/// @notice The public state of an OS that OSMetadata reads.
interface IOSView {
    function osName() external view returns (string memory);
    function number() external view returns (uint256);
    function composition() external view returns (uint8);
    function revealed() external view returns (bool);
    function epoch() external view returns (uint256);
    function shownEpoch() external view returns (uint256);
    function frozen() external view returns (bool);
    function windows() external view returns (address[] memory);
}

/// @notice Where THE SOURCE's piece lives: ArtifactsSource's answer, zero until its auction settles.
interface ISourcePiece {
    function pieceContract() external view returns (address);
    function keyCommitment() external view returns (bytes32);
}

/// @notice What THE SOURCE's mirror and outputs read of THE SOURCE's piece (the ArtifactsPiece runtime), unchanged.
interface ISourceToken {
    function ownerOf(uint256 tokenId) external view returns (address);
    function escrow()
        external
        view
        returns (
            uint256 price,
            address seller,
            address buyer,
            uint64 paidAt,
            bool keyPosted,
            bytes memory key,
            address broker,
            uint64 keyPostedAt,
            bytes32 viewingKey,
            uint256 deposit
        );
}
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.