Skip to content
Verified contractExactGPL-3.0

FactoryV7

Address0x3f484d387a2f069fac44f48fe337aa64760e753f
Balance

0 ETH

 

Transactions

4

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 10,000 runs
EVM version
cancun
License
GPL-3.0
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,355,048
Creation transaction
0x6069707215…bdaa72a26e

2 files

src/FactoryV7.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.24;

import {File, PermanentFile} from "./PermanentFile.sol";

interface ISaleViewV7 {
    function artist() external view returns (address);
    function collection() external view returns (address);
    function inscriptions() external view returns (address);
    function inscriptionId() external view returns (uint256);
    function royaltyBps() external view returns (uint96);
    function mediaURI() external view returns (string memory);
    function name() external view returns (string memory);
    function description() external view returns (string memory);
}

interface ICollectionViewV7 {
    function artist() external view returns (address);
    function inscriptions() external view returns (address);
    function royaltyBps() external view returns (uint96);
    function factory() external view returns (address);
}

interface IInscriptionsViewV7 {
    function isSealed(uint256 id) external view returns (bool);
    function artistOf(uint256 id) external view returns (address);
}

interface ICollectionV3Bind {
    function authorizePermanentSale(address sale, File calldata file, string calldata title, string calldata description)
        external;
}

/// Generation 7 (PERMANENT): the press's deployer, a new printing beside
/// generation 6. Factory.sol (gen6) is frozen and untouched, and stays live
/// for the collections it deployed; this is a new file.
///
/// The ETCHED branch is generation 6's, rule for rule: the same five kinds,
/// four sale templates pinned by the hash and length of their creation code
/// (generation 8's twins of gen6's four, which pay the press's one percent to
/// the IncomeForwarder: FeeV2.sol), the wallet path and the carried path under the artist's
/// EIP-712 SaleAuthorization (the same typed data and the same domain name
/// and version as gen6, pinned to this address), R-04 "onchain or not at
/// all" (the canonical store, a sealed inscription, the artist's own), one
/// standalone sale per inscription, and no value taken. What changes is the
/// collection it deploys: CollectionV3, the superset that also carries
/// PERMANENT works and ETCH IT.
///
/// The PERMANENT branch is new, and separate: its own entry point, never a
/// flag on the ETCHED ones. A PERMANENT sale names no store (its file lives
/// on Arweave) and its inscriptionId is the File's id, keccak256(abi.encode
/// (File)). It is admitted only
///   - from the artist's own wallet: there is no carried PERMANENT deploy
///     (SPEC-v2 2.2 step 7), so the storage price is always the artist's
///     own money and any refund of it goes back to the artist;
///   - in collection mode, into a CollectionV3 this Factory deployed, for
///     the same artist at the same royalty;
///   - with an empty mediaURI (the sale's own getter, shown by explorers,
///     never points anywhere: the File is the work);
///   - under the press attestation: an EIP-712 PermanentAttestation over
///     the artist and every field of the File plus the storage price and a
///     deadline, signed by the immutable attester, for the sale's own
///     artist, unexpired, and never used before. Nothing the chain can
///     compute ties the Arweave id, the SHA-256 and the chunk root to one
///     file; the attester signs only after computing all three from the one
///     set of bytes it signed into the Arweave item;
///   - with msg.value exactly the attested storage price, forwarded in the
///     same call to the immutable storage wallet, the whole deploy reverting
///     if the wallet refuses it.
/// The collection then binds the File to the sale in the same transaction
/// (CollectionV3.authorizePermanentSale), so a PERMANENT sale is born bound
/// and paid for, or not at all.
///
/// No owner, no setters, no upgrade path. The attester and the storage
/// wallet are fixed at deploy: changing either means a new Factory.
contract FactoryV7 {
    enum Kind {
        None,
        Auction,
        Edition,
        Collection,
        EditionAllowlist,
        AuctionAllowlist
    }

    struct SaleRecord {
        Kind kind;
        address artist;
        address collection;
        address inscriptions;
        uint256 inscriptionId;
        uint64 deployBlock;
        /// keccak256 of the abi-encoded constructor args, the variable tail
        /// of the initcode: the deploy-time config, pinned for the indexer
        bytes32 configHash;
    }

    /// The press attestation as it rides in calldata: the typed fields, then
    /// the attester's signature over them.
    struct PermanentAttestation {
        address artist;
        File file;
        uint256 storageWei;
        uint256 deadline;
        bytes signature;
    }

    // keccak256 and byte length of each audited template's creation code,
    // asserted against type(T).creationCode by FactoryV7.t.sol and
    // regenerated by scripts/gen-factory-hashes.mjs. Generation 7: the four
    // sale pins are the generation 8 templates (Auction1of1V4, EditionSaleV3,
    // EditionSaleAllowlistV3, AuctionAllowlistV4: gen6's four with only the
    // fee library swapped for FeeV2, scripts/verify-template-twins.mjs), the
    // same four FactoryV8 pins; the collection pin moves to CollectionV3.
    bytes32 public constant AUCTION_CODE_HASH = 0xba7acf845cfb4a87df1945cae91b698eb2efa7cd43c9e74810f45c2460614496;
    uint256 public constant AUCTION_CODE_LEN = 17388;
    bytes32 public constant EDITION_CODE_HASH = 0xb738a01be38e047841c1b99dcd33086299f06ea82de63437dcac0110fe77663f;
    uint256 public constant EDITION_CODE_LEN = 15902;
    bytes32 public constant COLLECTION_CODE_HASH = 0xf14c65ce0f30844768ce971793c2f97ecd9f4beec85436f88d109dfed3a01135;
    uint256 public constant COLLECTION_CODE_LEN = 23679;
    bytes32 public constant EDITION_ALLOWLIST_CODE_HASH = 0xee3afb9cb3e90b899be0e6ff6868062257cf3e0167cb58e753b4776fdd2ee005;
    uint256 public constant EDITION_ALLOWLIST_CODE_LEN = 17381;
    bytes32 public constant AUCTION_ALLOWLIST_CODE_HASH = 0xa2cbf1435e98bfa978fd92e1fb857b04f92e8d825df6e6065091240656c49e7e;
    uint256 public constant AUCTION_ALLOWLIST_CODE_LEN = 18564;

    /// The one inscription store this chain's press writes into.
    address public immutable inscriptions;
    /// The press attestation key: the only signer whose PermanentAttestation
    /// admits a PERMANENT sale. A new trust root, fixed here for good.
    address public immutable attester;
    /// Where the artist's storage payment goes, in the deploy transaction.
    address public immutable storageWallet;

    mapping(address => SaleRecord) private records;
    mapping(address => bool) public isCanonicalCollection;
    /// CHAIN-02: store => inscription id => a standalone sale already exists
    mapping(address => mapping(uint256 => bool)) public inscriptionSold;
    /// attestation digest => spent. An attestation admits one sale, ever.
    mapping(bytes32 => bool) public attestationUsed;

    /// The artist's SaleAuthorization: generation 6's domain, "ETCH'D
    /// Factory" / "3", with this chain and this address pinned, so a
    /// signature is for this printing on this chain only.
    bytes32 private immutable _domainSeparator;
    bytes32 public constant SALE_AUTH_TYPEHASH =
        keccak256("SaleAuthorization(address artist,uint8 kind,bytes32 salt,bytes32 initCodeHash,uint256 deadline)");

    /// The press attestation's own domain: "ETCHD Factory" / "7", this chain,
    /// this address.
    bytes32 private immutable _attestationDomainSeparator;
    bytes32 public constant PERMANENT_ATTESTATION_TYPEHASH = keccak256(
        "PermanentAttestation(address artist,bytes32 arTx,bytes32 sha256,bytes32 chunkRoot,uint32 size,string mime,bytes32 posterTx,bytes32 posterSha256,uint256 storageWei,uint256 deadline)"
    );

    /// held for the length of a PERMANENT deploy: the storage wallet is paid
    /// last, and nothing it does on receipt can re-enter the branch
    bool private transient _entered;

    event SaleDeployed(
        address indexed sale,
        Kind indexed kind,
        address indexed artist,
        address collection,
        address inscriptions,
        uint256 inscriptionId,
        bytes32 configHash
    );
    event CollectionDeployed(address indexed collection, address indexed artist, bytes32 configHash);
    /// A PERMANENT sale was paid for: the storage price went to the storage
    /// wallet in this transaction (zero when the artist pays Arweave some
    /// other way). The press posts the signed Arweave item after seeing this
    /// beside the collection's PermanentSaleAuthorized. `payer` is the
    /// transaction's sender, which the only PERMANENT entry point requires
    /// to be the artist, so payer == artist on every StoragePaid.
    event StoragePaid(address indexed sale, address indexed artist, address indexed payer, uint256 fileId, uint256 amount);

    error NotATemplate();
    error UnknownKind();
    error DeployFailed();
    error NotACanonicalCollection();
    error CollectionArtistMismatch();
    error CollectionRoyaltyMismatch();
    error CollectionFactoryMismatch();
    error UnknownStore();
    error InscriptionNotSealed();
    error InscriptionArtistMismatch();
    error StoreHasNoCode();
    error NotAuthorized();
    error AuthorizationExpired();
    error SaleExists();
    // generation 7
    error ZeroAttester();
    error ZeroStorageWallet();
    error NotAPermanentSale();
    error PermanentNeedsACollection();
    error MediaURIMustBeEmpty();
    error FileIdMismatch();
    error AttestationArtistMismatch();
    error AttestationExpired();
    error AttestationUsed();
    error BadAttestation();
    error WrongStoragePayment();
    error StoragePaymentFailed();
    error Reentered();

    constructor(address inscriptions_, address attester_, address storageWallet_) {
        // fail fast, as gen6: a factory whose store is the zero address or an
        // EOA can never deploy a sale
        if (inscriptions_.code.length == 0) revert StoreHasNoCode();
        // and one with no attester or no storage wallet could never take a
        // PERMANENT work, or would burn the artist's payment
        if (attester_ == address(0)) revert ZeroAttester();
        if (storageWallet_ == address(0)) revert ZeroStorageWallet();
        inscriptions = inscriptions_;
        attester = attester_;
        storageWallet = storageWallet_;
        _domainSeparator = keccak256(abi.encode(
            keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
            keccak256("ETCH'D Factory"),
            keccak256("3"),
            block.chainid,
            address(this)
        ));
        _attestationDomainSeparator = keccak256(abi.encode(
            keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
            keccak256("ETCHD Factory"),
            keccak256("7"),
            block.chainid,
            address(this)
        ));
    }

    function domainSeparator() external view returns (bytes32) { return _domainSeparator; }
    function attestationDomainSeparator() external view returns (bytes32) { return _attestationDomainSeparator; }

    /// The digest the artist signs to let someone else (the press's relayer)
    /// send their ETCHED deploy: bound to the artist, the kind, the exact
    /// salt and initcode (so the address and every constructor arg are
    /// fixed), and a deadline. A PERMANENT deploy is never carried.
    function authorizationDigest(address artist, Kind kind, bytes32 salt, bytes32 initCodeHash, uint256 deadline)
        public
        view
        returns (bytes32)
    {
        return keccak256(abi.encodePacked(
            "\x19\x01",
            _domainSeparator,
            keccak256(abi.encode(SALE_AUTH_TYPEHASH, artist, uint8(kind), salt, initCodeHash, deadline))
        ));
    }

    /// The digest the press attester signs for a PERMANENT work.
    function attestationDigest(address artist, File calldata file, uint256 storageWei, uint256 deadline)
        public
        view
        returns (bytes32)
    {
        // two static halves, concatenated: byte for byte the one abi.encode
        // of all eleven words (the legacy pipeline's stack takes no more)
        bytes32 structHash = keccak256(bytes.concat(
            abi.encode(PERMANENT_ATTESTATION_TYPEHASH, artist, file.arTx, file.sha256, file.chunkRoot, file.size),
            abi.encode(keccak256(bytes(file.mime)), file.posterTx, file.posterSha256, storageWei, deadline)
        ));
        return keccak256(abi.encodePacked("\x19\x01", _attestationDomainSeparator, structHash));
    }

    /// A PERMANENT sale's inscriptionId: keccak256(abi.encode(File)).
    function fileIdOf(File calldata file) external pure returns (uint256) {
        return PermanentFile.idOf(file);
    }

    // =====================================================================
    // ETCHED: generation 6, rule for rule
    // =====================================================================

    /// Deploy an audited sale template. The initcode is the caller's, whole:
    /// creation code plus constructor args, its salt ground off-chain so the
    /// resulting address checksums to 0xC0DE over THIS deployer. Only the
    /// audited creation code passes the prefix hash; only a sane target
    /// passes the reads after.
    /// The wallet path: the artist's own transaction. msg.sender must be the
    /// artist the deployed sale names.
    function deploySale(Kind kind, bytes32 salt, bytes calldata initcode) external returns (address sale) {
        sale = _deploySale(kind, salt, initcode);
        if (msg.sender != records[sale].artist) revert NotAuthorized();
    }

    /// The carried path: anyone sends, the artist has signed. The signature
    /// is checked against the artist the deployed sale itself names.
    function deploySaleFor(Kind kind, bytes32 salt, bytes calldata initcode, uint256 deadline, bytes calldata sig)
        external
        returns (address sale)
    {
        if (block.timestamp > deadline) revert AuthorizationExpired();
        sale = _deploySale(kind, salt, initcode);
        if (!_isSigner(records[sale].artist, authorizationDigest(records[sale].artist, kind, salt, keccak256(initcode), deadline), sig)) {
            revert NotAuthorized();
        }
    }

    function _deploySale(Kind kind, bytes32 salt, bytes calldata initcode) private returns (address sale) {
        uint256 len;
        bytes32 want;
        if (kind == Kind.Auction) {
            len = AUCTION_CODE_LEN;
            want = AUCTION_CODE_HASH;
        } else if (kind == Kind.Edition) {
            len = EDITION_CODE_LEN;
            want = EDITION_CODE_HASH;
        } else if (kind == Kind.EditionAllowlist) {
            len = EDITION_ALLOWLIST_CODE_LEN;
            want = EDITION_ALLOWLIST_CODE_HASH;
        } else if (kind == Kind.AuctionAllowlist) {
            len = AUCTION_ALLOWLIST_CODE_LEN;
            want = AUCTION_ALLOWLIST_CODE_HASH;
        } else {
            revert UnknownKind();
        }
        _checkTemplate(initcode, want, len);
        sale = _create2(salt, initcode);

        address artist = ISaleViewV7(sale).artist();
        address col = ISaleViewV7(sale).collection();
        address store = ISaleViewV7(sale).inscriptions();
        uint256 inscriptionId = ISaleViewV7(sale).inscriptionId();

        if (col != address(0)) {
            // closes the fake-collection hole: a canonical sale only ever
            // mints into a collection this factory deployed, for this artist
            if (!isCanonicalCollection[col]) revert NotACanonicalCollection();
            if (ICollectionViewV7(col).artist() != artist) revert CollectionArtistMismatch();
            // the delivered token lives in the collection, so its ERC-2981
            // royalty is the COLLECTION's, not the sale's. Bind them equal at
            // deploy; since royalty is reduce-only on both, the token's royalty
            // can never later exceed the value the artist signs against the
            // sale. Without this a 1% sale could deliver into a 10% collection.
            if (ICollectionViewV7(col).royaltyBps() != ISaleViewV7(sale).royaltyBps()) revert CollectionRoyaltyMismatch();
        }
        // R-04, onchain or not at all: every sale this branch deploys serves a
        // sealed inscription in THIS chain's canonical store, never an
        // external URL. The store is immutable and nonzero, so a sale can
        // never ship mutable off-chain bytes; the inscription is sealed
        // forever and the artist's own. (A PERMANENT sale, store 0, is
        // refused here: it has its own branch below, under the attestation.)
        if (store != inscriptions) revert UnknownStore();
        if (!IInscriptionsViewV7(store).isSealed(inscriptionId)) revert InscriptionNotSealed();
        if (IInscriptionsViewV7(store).artistOf(inscriptionId) != artist) revert InscriptionArtistMismatch();
        // CHAIN-02: one standalone sale per inscription, ever. A collection
        // sale is bound by the collection's own authorizeSale instead.
        if (col == address(0)) {
            if (inscriptionSold[store][inscriptionId]) revert SaleExists();
            inscriptionSold[store][inscriptionId] = true;
        }

        bytes32 configHash = keccak256(initcode[len:]);
        records[sale] = SaleRecord({
            kind: kind,
            artist: artist,
            collection: col,
            inscriptions: store,
            inscriptionId: inscriptionId,
            deployBlock: uint64(block.number),
            configHash: configHash
        });
        emit SaleDeployed(sale, kind, artist, col, store, inscriptionId, configHash);
    }

    /// Deploy the audited collection template and register it, so sales can
    /// name it. Same discipline: audited bytes in, real immutables out.
    function deployCollection(bytes32 salt, bytes calldata initcode) external returns (address col) {
        col = _deployCollection(salt, initcode);
        if (msg.sender != records[col].artist) revert NotAuthorized();
    }

    function deployCollectionFor(bytes32 salt, bytes calldata initcode, uint256 deadline, bytes calldata sig)
        external
        returns (address col)
    {
        if (block.timestamp > deadline) revert AuthorizationExpired();
        col = _deployCollection(salt, initcode);
        if (!_isSigner(records[col].artist, authorizationDigest(records[col].artist, Kind.Collection, salt, keccak256(initcode), deadline), sig)) {
            revert NotAuthorized();
        }
    }

    function _deployCollection(bytes32 salt, bytes calldata initcode) private returns (address col) {
        _checkTemplate(initcode, COLLECTION_CODE_HASH, COLLECTION_CODE_LEN);
        col = _create2(salt, initcode);

        address artist = ICollectionViewV7(col).artist();
        address store = ICollectionViewV7(col).inscriptions();
        // the collection serves art from the canonical store, and it must point
        // back at THIS factory: otherwise its authorizeSale would trust a
        // look-alike factory the deployer controls (R-02 anchor).
        if (store != inscriptions) revert UnknownStore();
        if (ICollectionViewV7(col).factory() != address(this)) revert CollectionFactoryMismatch();

        bytes32 configHash = keccak256(initcode[COLLECTION_CODE_LEN:]);
        isCanonicalCollection[col] = true;
        records[col] = SaleRecord({
            kind: Kind.Collection,
            artist: artist,
            collection: address(0),
            inscriptions: store,
            inscriptionId: 0,
            deployBlock: uint64(block.number),
            configHash: configHash
        });
        emit CollectionDeployed(col, artist, configHash);
    }

    // =====================================================================
    // PERMANENT
    // =====================================================================

    modifier nonReentrant() {
        if (_entered) revert Reentered();
        _entered = true;
        _;
        _entered = false;
    }

    /// The only PERMANENT entry point: the artist's own transaction, carrying
    /// exactly the attested storage price. msg.sender must be the artist the
    /// sale names. There is no carried PERMANENT deploy (SPEC-v2 2.2 step 7):
    /// a relayer or anyone else paying the storage price would make the
    /// payer someone other than the artist, and the press refunds the artist.
    function deployPermanentSale(Kind kind, bytes32 salt, bytes calldata initcode, PermanentAttestation calldata att)
        external
        payable
        nonReentrant
        returns (address sale)
    {
        sale = _deployPermanentSale(kind, salt, initcode, att);
        if (msg.sender != records[sale].artist) revert NotAuthorized();
        _payStorage(sale);
    }

    function _deployPermanentSale(Kind kind, bytes32 salt, bytes calldata initcode, PermanentAttestation calldata att)
        private
        returns (address sale)
    {
        // exactly the attested price: not a wei more (it would be kept by
        // nobody's rule), not a wei less
        if (msg.value != att.storageWei) revert WrongStoragePayment();
        (uint256 len, bytes32 want) = _templateOf(kind);
        _checkTemplate(initcode, want, len);
        sale = _create2(salt, initcode);

        address artist = ISaleViewV7(sale).artist();
        address col = ISaleViewV7(sale).collection();
        // a PERMANENT sale names no store: its file is on Arweave, its record
        // in the collection. An inscribed sale takes the ETCHED branch.
        if (ISaleViewV7(sale).inscriptions() != address(0)) revert NotAPermanentSale();
        // collection mode only: standalone, a frozen template renders its own
        // mediaURI, with no fingerprint and no upgrade
        if (col == address(0)) revert PermanentNeedsACollection();
        if (!isCanonicalCollection[col]) revert NotACanonicalCollection();
        if (ICollectionViewV7(col).artist() != artist) revert CollectionArtistMismatch();
        if (ICollectionViewV7(col).royaltyBps() != ISaleViewV7(sale).royaltyBps()) revert CollectionRoyaltyMismatch();
        // the sale's own mediaURI getter is shown by explorers: it stays
        // empty, so it can never point at anything but the File
        if (bytes(ISaleViewV7(sale).mediaURI()).length != 0) revert MediaURIMustBeEmpty();
        uint256 fileId = PermanentFile.idOf(att.file);
        if (ISaleViewV7(sale).inscriptionId() != fileId) revert FileIdMismatch();
        _spendAttestation(artist, att);

        bytes32 configHash = keccak256(initcode[len:]);
        records[sale] = SaleRecord({
            kind: kind,
            artist: artist,
            collection: col,
            inscriptions: address(0),
            inscriptionId: fileId,
            deployBlock: uint64(block.number),
            configHash: configHash
        });
        emit SaleDeployed(sale, kind, artist, col, address(0), fileId, configHash);
        // born bound: the collection reads the record just written and binds
        // the File with the sale's own title and words
        ICollectionV3Bind(col).authorizePermanentSale(
            sale, att.file, ISaleViewV7(sale).name(), ISaleViewV7(sale).description()
        );
    }

    /// The press attestation: for this sale's artist, unexpired, never used,
    /// signed by the attester over every field. Spent here, for good.
    function _spendAttestation(address artist, PermanentAttestation calldata att) private {
        if (att.artist != artist) revert AttestationArtistMismatch();
        if (block.timestamp > att.deadline) revert AttestationExpired();
        bytes32 digest = attestationDigest(att.artist, att.file, att.storageWei, att.deadline);
        if (attestationUsed[digest]) revert AttestationUsed();
        if (!_isSigner(attester, digest, att.signature)) revert BadAttestation();
        attestationUsed[digest] = true;
    }

    /// Last, after every check and every write: the exact storage price to
    /// the storage wallet. A wallet that refuses it undoes the whole deploy.
    function _payStorage(address sale) private {
        SaleRecord storage r = records[sale];
        emit StoragePaid(sale, r.artist, msg.sender, r.inscriptionId, msg.value);
        if (msg.value != 0) {
            (bool ok,) = storageWallet.call{value: msg.value}("");
            if (!ok) revert StoragePaymentFailed();
        }
    }

    /// The four sale kinds and their pins (generation 6's selection).
    function _templateOf(Kind kind) private pure returns (uint256 len, bytes32 want) {
        if (kind == Kind.Auction) return (AUCTION_CODE_LEN, AUCTION_CODE_HASH);
        if (kind == Kind.Edition) return (EDITION_CODE_LEN, EDITION_CODE_HASH);
        if (kind == Kind.EditionAllowlist) return (EDITION_ALLOWLIST_CODE_LEN, EDITION_ALLOWLIST_CODE_HASH);
        if (kind == Kind.AuctionAllowlist) return (AUCTION_ALLOWLIST_CODE_LEN, AUCTION_ALLOWLIST_CODE_HASH);
        revert UnknownKind();
    }

    // =====================================================================
    // reads and shared machinery (generation 6's)
    // =====================================================================

    /// Did this factory deploy this sale? ETCHED or PERMANENT alike.
    function isCanonicalSale(address sale) external view returns (bool) {
        Kind k = records[sale].kind;
        return k == Kind.Auction || k == Kind.Edition || k == Kind.EditionAllowlist || k == Kind.AuctionAllowlist;
    }

    function saleRecord(address deployed) external view returns (SaleRecord memory) {
        return records[deployed];
    }

    /// A signature check that speaks both dialects (the same one the store
    /// uses): a plain wallet's ECDSA signature, low-s only, and a contract
    /// wallet's ERC-1271 isValidSignature.
    function _isSigner(address signer, bytes32 digest, bytes calldata sig) private view returns (bool) {
        if (sig.length == 65) {
            bytes32 r; bytes32 s; uint8 v;
            assembly {
                r := calldataload(sig.offset)
                s := calldataload(add(sig.offset, 32))
                v := byte(0, calldataload(add(sig.offset, 64)))
            }
            // reject the malleable upper half of s; an authorization has exactly one form
            if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) return false;
            address rec = ecrecover(digest, v, r, s);
            if (rec != address(0) && rec == signer) return true;
        }
        if (signer.code.length > 0) {
            (bool ok, bytes memory ret) = signer.staticcall(
                abi.encodeWithSelector(0x1626ba7e, digest, sig) // isValidSignature(bytes32,bytes)
            );
            return ok && ret.length >= 32 && bytes4(ret) == bytes4(0x1626ba7e);
        }
        return false;
    }

    /// The initcode's fixed prefix must hash to the audited template's
    /// creation code, byte for byte. Everything after it is constructor args.
    function _checkTemplate(bytes calldata initcode, bytes32 want, uint256 len) private pure {
        if (initcode.length < len || keccak256(initcode[:len]) != want) revert NotATemplate();
    }

    function _create2(bytes32 salt, bytes calldata initcode) private returns (address deployed) {
        bytes memory code = initcode;
        assembly {
            deployed := create2(0, add(code, 0x20), mload(code), salt)
        }
        if (deployed == address(0)) revert DeployFailed();
    }
}

src/PermanentFile.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.24;

/// Generation 7 (PERMANENT): the record of a work whose file lives on
/// Arweave, written once when its sale is bound and never again. The token
/// carries the Arweave id AND the file's own fingerprints, so any copy of the
/// file, from any gateway or any disk, can prove itself against the chain.
///
///   arTx          the Arweave id: the 43-character base64url id decoded to
///                 its 32 raw bytes (tokenURI re-encodes it)
///   sha256        SHA-256 of the exact file, what shasum and a gateway's
///                 content-digest header give
///   chunkRoot     the fold over the file cut into 24,575-byte pieces, the
///                 store's chunk size: acc0 = 0, then for each piece
///                 acc = keccak256(acc ++ keccak256(0x00 ++ piece)). A chunk
///                 contract's code is a STOP byte and its piece, so its
///                 extcodehash is keccak256(0x00 ++ piece): the chain checks
///                 this against a sealed inscription one opcode per chunk
///   size          bytes, above zero: a non-zero size is what marks a work
///                 PERMANENT
///   mime          one of the six PERMANENT types, inside MetaEscape's collar
///   posterTx      video only: the poster still's Arweave id, else zero
///   posterSha256  video only: the poster still's SHA-256, else zero
///
/// Nothing the chain can compute ties arTx, sha256 and chunkRoot to one set
/// of bytes. The press attestation does: the gen7 Factory binds a File only
/// under the press attester's EIP-712 signature over every field.
struct File {
    bytes32 arTx;
    bytes32 sha256;
    bytes32 chunkRoot;
    uint32 size;
    string mime;
    bytes32 posterTx;
    bytes32 posterSha256;
}

library PermanentFile {
    /// The store's chunk size (InscriptionsV3.CHUNK_MAX): the fixed cut the
    /// chunkRoot is folded over, the same on every chain.
    uint256 internal constant CHUNK = 24_575;

    /// The sale's inscriptionId for a PERMANENT sale, and the File's key in
    /// its collection: keccak256 of the File, abi-encoded as one argument
    /// (the tuple behind its 0x20 offset word, as ethers encodes a single
    /// tuple(bytes32,bytes32,bytes32,uint32,string,bytes32,bytes32) value).
    function idOf(File memory f) internal pure returns (uint256) {
        return uint256(keccak256(abi.encode(f)));
    }

    /// The six PERMANENT types (Kenny, 2026-09-25): PNG, JPEG, GIF, WEBP,
    /// MP4, WEBM, spelled exactly so. Nothing else binds: no HTML, no SVG,
    /// nothing a gateway would run.
    function allowedMime(string memory m) internal pure returns (bool) {
        bytes32 h = keccak256(bytes(m));
        return h == keccak256("image/png") || h == keccak256("image/jpeg") || h == keccak256("image/gif")
            || h == keccak256("image/webp") || isVideoHash(h);
    }

    /// A moving image: its token shows a poster still in `image` and the file
    /// in `animation_url`, because marketplaces expect a still in `image`.
    function isVideo(string memory m) internal pure returns (bool) {
        return isVideoHash(keccak256(bytes(m)));
    }

    function isVideoHash(bytes32 h) internal pure returns (bool) {
        return h == keccak256("video/mp4") || h == keccak256("video/webm");
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 10000,
    "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.