Skip to content
Verified contractPartialMIT

Foundry

Address0x6c1da890f9e013bcdf35931941ca1817e5c25f37
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,226,607
Creation transaction
0x430182b0a6…b27fac5acf

3 files

src/Foundry.sol

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

// RETICLE · DATASHEET · FOUNDRY (part RT-F1)
// https://reticlefab.xyz   https://x.com/reticlefab
//
// FUNCTION
//   The record book of combinational logic. A task is a function, given as a reference netlist, and an objective
//   (0 gates, 1 gates x depth, 2 gates x depth^2). Its crown is the cheapest circuit proven equal to the reference.
//   The first record must be strictly cheaper than the reference itself: a copy of the specification mines nothing.
//   After that only a strictly cheaper proven circuit takes a crown (an equal one only if committed earlier).
//
// OPERATING SEQUENCE
//   1 commit(hash)                      hash = keccak256(abi.encode(designer, task, keccak256(source), salt))
//   2 reveal(task, source, salt)        a later block. The source is flattened (IP dies inlined), measured, costed
//                                       and stored; it must already beat the crown. Wide tasks post a 0.05 ETH bond.
//   3 prove(attempt, passes)            any number of calls, anyone may pay for them. 256 inputs per pass. Tasks of
//                                       up to 16 inputs: every combination. Wider: 32 passes of inputs drawn from the
//                                       hash of the block after the reveal, unknown when the design was fixed.
//   4 on the last pass                  a Die is minted to the designer; if it still beats the crown, it is crowned
//                                       and half of the task's pot is set aside for it (only for a strictly cheaper
//                                       record), held in escrow for a day (three for a wide task): an equal design
//                                       committed earlier that is proven in that time takes the escrow with the crown,
//                                       and a die broken by fraud proof returns it to the pot.
//   Wide-task dies stand 3 days open to fraud proof: anyone who names one input on which the die and the reference
//   differ breaks it, takes the bond, and the crown falls back to the last unbroken record.
//
// EMISSION (Proof of Fee)
//   800,000,000 RETICLE over halvings: 273,972.6 per day, halving every 1,460 days. Each UTC-aligned day after launch,
//   traders direct the foundry's 1% of their trades to tasks (hookData). That day's output is scaled by the fees so
//   directed: full output at 1 ETH directed or more, proportionally less below (never issued later). A task receives
//   its share of the directed fees, at most 20%, and the dies that held its crown that day share it by the seconds
//   they held it. Unheld time and unclaimed share are never minted. Measured in econ/econ_reticle.js: with this
//   scaling, wash trading to steer emission cannot pay below ~7,300 ETH FDV at day-0 output.
//
// ROYALTIES
//   A die that inlines other dies pays them 25% of its emission x (inlined gates / its gates), split by gates. A
//   broken parent's part is never minted.
//
// LIMITS, STATED
//   Wide-task proofs are probabilistic: 8,192 random vectors, then three days of open fraud proofs: a wide task is
//   only as safe as whoever checks its new dies in that time. Exhaustive tasks are exact. Accrual walks at most 120
//   days per call: a crown change waits (NotSettled) until poke() has caught the crown up, so no held day is lost.
//   The seed for a wide proof must be read within 256 blocks of the reveal, or the attempt fails and the bond goes
//   back. When a broken crown falls, it falls back to the last unbroken crowned die, not to a cheaper die that was
//   proven but never crowned; that die can take the crown again by a new reveal.

import {Verifier} from "./Verifier.sol";
import {Die} from "./Die.sol";

interface IReticleMint {
    function mint(address to, uint256 amount) external;
}

interface IStepperFlush {
    function flush() external;
}

contract Foundry {
    uint256 public constant DAY = 1 days;
    uint256 public constant HALVING_DAYS = 1460;
    uint256 public constant MINED_SUPPLY = 800_000_000e18;
    uint256 public constant DAY0_OUTPUT = MINED_SUPPLY / (2 * HALVING_DAYS);
    uint256 public constant W_TARGET = 1 ether; // directed fees per day for full output
    uint256 public constant TASK_CAP_BPS = 2000; // the most of a day's output one taskId takes
    uint256 public constant ROYALTY_BPS = 2500;
    uint256 public constant POT_TAKE_BPS = 5000;
    uint256 public constant POST_FEE = 0.01 ether;
    uint256 public constant WIDE_BOND = 0.05 ether;
    uint256 public constant CHALLENGE_WINDOW = 3 days;
    uint256 public constant MAX_ACCRUE_DAYS = 120;
    uint256 public constant MAX_CODE = 24_575; // a stored netlist must fit one contract's code
    uint256 public constant ESCROW = 1 days; // a record's pot share waits this long (wide tasks: the challenge window)

    uint8 internal constant PROVING = 1;
    uint8 internal constant PROVEN = 2;
    uint8 internal constant FAILED = 3;

    address public immutable LAUNCHER;
    IReticleMint public immutable RETICLE;
    Die public immutable DIE;
    Verifier public immutable VERIFIER;
    address public immutable FURNACE;
    address public stepper;
    uint256 public start; // launch time: day 0 begins

    struct Task {
        address ref;
        uint8 nIn;
        uint8 nOut;
        uint8 objective;
        bool wide;
        uint32 crown;
        uint64 crownCost; // the record's cost; while there is none, the reference's (the bar to beat)
        uint64 crownCommit;
        uint40 crownSince; // accrual cursor
        uint32 records;
        bytes32 label;
        address poster;
    }

    struct Attempt {
        address designer;
        uint32 task;
        address flat;
        uint64 cost;
        uint64 commitBlock;
        uint64 revealBlock;
        uint32 nextPass;
        uint32 passes;
        uint8 state;
        bool bonded;
        uint32 die;
        uint32 gates;
        uint32 depth;
        uint256 seed;
    }

    Task[] internal tasks;
    Attempt[] internal attempts;
    mapping(uint256 => uint32[]) internal crownHistory;
    mapping(uint256 => uint32[]) internal attemptParents;
    mapping(uint256 => uint32[]) internal attemptParentGates;
    mapping(bytes32 => uint256) public commits; // hash => block
    mapping(uint256 => uint256) public pot; // taskId => wei
    mapping(uint256 => mapping(uint256 => uint256)) public directed; // day => taskId => wei
    mapping(uint256 => uint256) public directedTotal; // day => wei
    mapping(uint256 => mapping(uint256 => mapping(uint256 => uint256))) public crownSeconds; // taskId => day => die
    mapping(uint256 => mapping(uint256 => bool)) public claimed; // die => day
    mapping(uint256 => uint256) public royaltyOwed; // die => RETICLE
    mapping(uint256 => uint256) public ethOwed; // die => wei in escrow (pot winnings)
    mapping(uint256 => uint256) public ethOwedFrom; // die => when its escrow may be paid
    mapping(uint256 => uint256) public bondHeld; // die => wei

    event TaskPosted(uint256 indexed taskId, address indexed poster, uint8 nIn, uint8 nOut, uint8 objective, bytes32 label, address ref);
    event Committed(bytes32 indexed hash, address indexed by);
    event Revealed(uint256 indexed attempt, uint256 indexed taskId, address indexed designer, uint256 gates, uint256 depth, uint256 cost, uint256 passes);
    event Proving(uint256 indexed attempt, uint256 nextPass);
    event Failed(uint256 indexed attempt, uint256 atPass);
    event Proven(uint256 indexed attempt, uint256 indexed die, uint256 indexed taskId, bool crowned);
    event Crowned(uint256 indexed taskId, uint256 indexed die, uint256 cost, uint256 previous, uint256 potPaid);
    event Directed(uint256 indexed day, uint256 indexed taskId, uint256 amount);
    event Claimed(uint256 indexed die, uint256 indexed day, address to, uint256 amount, uint256 royalties);
    event RoyaltyPaid(uint256 indexed die, address to, uint256 amount);
    event EthPaid(uint256 indexed die, address to, uint256 amount);
    event Challenged(uint256 indexed die, address indexed challenger, uint256 input);
    event Revoked(uint256 indexed taskId, uint256 indexed die, uint256 restored);
    event BondReleased(uint256 indexed die, uint256 amount);

    error NotLauncher();
    error NotStepper();
    error AlreadyBound();
    error NotStarted();
    error BadFee();
    error BadObjective();
    error NoTask();
    error NoCommit();
    error TooSoon();
    error Interface();
    error NotBetter();
    error BrokenParent();
    error TooBig();
    error NotProving();
    error NotDone();
    error NotWide();
    error WindowClosed();
    error NotWrong();
    error NotSettled();
    error AlreadyClaimed();
    error Nothing();
    error Broken();
    error SendFailed();

    constructor(address launcher, address reticle, Die die, Verifier verifier, address furnace) {
        LAUNCHER = launcher;
        RETICLE = IReticleMint(reticle);
        DIE = die;
        VERIFIER = verifier;
        FURNACE = furnace;
    }

    /// @notice Once, by the launcher when it arms the hook: the hook that directs fees.
    function bind(address stepper_) external {
        if (msg.sender != LAUNCHER) revert NotLauncher();
        if (stepper != address(0)) revert AlreadyBound();
        stepper = stepper_;
    }

    /// @notice Once, by the hook, as the pool opens: day 0 begins. Before it nothing can be revealed or mined.
    function begin() external {
        if (msg.sender != stepper) revert NotStepper();
        if (start == 0) start = block.timestamp;
    }

    receive() external payable {}

    // ------------------------------------------------------------------------------------------------ tasks

    /// @notice Post a new task: its reference netlist is the specification. 0.01 ETH, to the furnace (the launcher's
    ///         genesis tasks are free).
    function postTask(bytes calldata ref, uint8 objective, bytes32 label) external payable returns (uint256 id) {
        if (msg.sender != LAUNCHER) {
            if (msg.value != POST_FEE) revert BadFee();
            _send(FURNACE, msg.value);
        } else if (msg.value != 0) {
            revert BadFee();
        }
        if (objective > 2) revert BadObjective();
        (uint256 nIn, uint256 nOut,) = VERIFIER.check(ref);
        (uint256 rg, uint256 rd) = VERIFIER.measure(ref);
        Task memory t;
        t.crownCost = uint64(VERIFIER.cost(rg, rd, objective));
        t.ref = _store(ref);
        t.nIn = uint8(nIn);
        t.nOut = uint8(nOut);
        t.objective = objective;
        t.wide = nIn > VERIFIER.EXHAUSTIVE_INPUTS();
        t.label = label;
        t.poster = msg.sender;
        tasks.push(t);
        id = tasks.length;
        emit TaskPosted(id, msg.sender, uint8(nIn), uint8(nOut), objective, label, t.ref);
    }

    // ------------------------------------------------------------------------------------------------ records

    /// @notice Fix a design without showing it. A hash committed twice keeps its first block.
    function commit(bytes32 hash) external {
        if (commits[hash] == 0) commits[hash] = block.number;
        emit Committed(hash, msg.sender);
    }

    /// @notice Reveal a committed design. It is flattened, measured and stored, and must already beat the crown.
    function reveal(uint32 taskId, bytes calldata source, bytes32 salt) external payable returns (uint256 id) {
        if (start == 0) revert NotStarted();
        Task storage t = _task(taskId);
        bytes32 h = keccak256(abi.encode(msg.sender, taskId, keccak256(source), salt));
        uint256 cb = commits[h];
        if (cb == 0) revert NoCommit();
        if (cb >= block.number) revert TooSoon();
        delete commits[h];
        if (msg.value != (t.wide ? WIDE_BOND : 0)) revert BadFee();

        uint32[] memory ids = VERIFIER.instancesOf(source);
        address[] memory ptrs = new address[](ids.length);
        for (uint256 k; k < ids.length; ++k) {
            Die.Record memory r = DIE.record(ids[k]);
            if (r.broken) revert BrokenParent();
            ptrs[k] = r.netlist;
        }
        (bytes memory flat, uint256[] memory inlined) = VERIFIER.flatten(source, ptrs);
        if (flat.length > MAX_CODE) revert TooBig();
        (uint256 nIn, uint256 nOut,) = VERIFIER.header(flat);
        if (nIn != t.nIn || nOut != t.nOut) revert Interface();
        (uint256 gates, uint256 depth) = VERIFIER.measure(flat);
        uint256 c = VERIFIER.cost(gates, depth, t.objective);
        if (!(c < t.crownCost || (t.crown != 0 && c == t.crownCost && cb < t.crownCommit))) revert NotBetter();

        Attempt memory a;
        a.designer = msg.sender;
        a.task = taskId;
        a.flat = _store(flat);
        a.cost = uint64(c);
        a.commitBlock = uint64(cb);
        a.revealBlock = uint64(block.number);
        a.passes = uint32(VERIFIER.passesFor(nIn));
        a.state = PROVING;
        a.bonded = t.wide;
        a.gates = uint32(gates);
        a.depth = uint32(depth);
        attempts.push(a);
        id = attempts.length;
        uint32[] memory g = new uint32[](ids.length);
        for (uint256 k; k < ids.length; ++k) g[k] = uint32(inlined[k]);
        attemptParents[id] = ids;
        attemptParentGates[id] = g;
        emit Revealed(id, taskId, msg.sender, gates, depth, c, a.passes);
    }

    /// @notice Run up to `maxPasses` more passes of an attempt's proof. Anyone may pay for them.
    function prove(uint256 id, uint256 maxPasses) external returns (bool done) {
        Attempt storage a = attempts[id - 1];
        if (a.state != PROVING) revert NotProving();
        Task storage t = tasks[a.task - 1];
        if (t.wide && a.seed == 0) {
            if (block.number <= a.revealBlock + 1) revert TooSoon();
            bytes32 bh = blockhash(a.revealBlock + 1);
            if (bh == bytes32(0)) {
                _fail(id, a, 0); // the seed went out of reach: the attempt fails, its bond goes back
                return false;
            }
            a.seed = uint256(bh);
        }
        uint256 from = a.nextPass;
        uint256 to = from + maxPasses;
        if (to > a.passes) to = a.passes;
        if (!VERIFIER.proveRange(a.flat, t.ref, from, to, a.seed)) {
            _fail(id, a, from);
            return false;
        }
        a.nextPass = uint32(to);
        emit Proving(id, to);
        if (to == a.passes) {
            _finish(id, a, t);
            return true;
        }
    }

    function _fail(uint256 id, Attempt storage a, uint256 atPass) internal {
        a.state = FAILED;
        emit Failed(id, atPass);
        if (a.bonded) {
            a.bonded = false;
            _send(a.designer, WIDE_BOND);
        }
    }

    function _finish(uint256 id, Attempt storage a, Task storage t) internal {
        a.state = PROVEN;
        Die.Record memory r = Die.Record({
            task: a.task,
            netlist: a.flat,
            gates: a.gates,
            depth: a.depth,
            cost: a.cost,
            commitBlock: a.commitBlock,
            provenAt: uint40(block.timestamp),
            wide: t.wide,
            broken: false,
            designer: a.designer
        });
        uint256 die = DIE.mint(a.designer, r, attemptParents[id], attemptParentGates[id]);
        a.die = uint32(die);
        if (a.bonded) bondHeld[die] = WIDE_BOND;
        bool better = a.cost < t.crownCost || (t.crown != 0 && a.cost == t.crownCost && a.commitBlock < t.crownCommit);
        if (better) _crown(a.task, t, die, a.cost, a.commitBlock);
        emit Proven(id, die, a.task, better);
    }

    function _crown(uint256 taskId, Task storage t, uint256 die, uint64 c, uint64 commitBlock) internal {
        _accrue(taskId, t);
        if (t.crownSince < block.timestamp) revert NotSettled(); // more than 120 days behind: poke() first
        uint256 previous = t.crown;
        bool strict = previous == 0 || c < t.crownCost;
        t.crown = uint32(die);
        t.crownCost = c;
        t.crownCommit = commitBlock;
        t.crownSince = uint40(block.timestamp);
        t.records += 1;
        crownHistory[taskId].push(uint32(die));
        uint256 paid;
        if (strict) {
            paid = (pot[taskId] * POT_TAKE_BPS) / 10_000;
            pot[taskId] -= paid;
            ethOwed[die] += paid;
            ethOwedFrom[die] = block.timestamp + (t.wide ? CHALLENGE_WINDOW : ESCROW);
        } else if (previous != 0 && ethOwed[previous] != 0) {
            // an equal design committed earlier: it takes the crown, and the escrow the later copy was holding
            paid = ethOwed[previous];
            ethOwed[previous] = 0;
            ethOwed[die] += paid;
            ethOwedFrom[die] = ethOwedFrom[previous] > block.timestamp ? ethOwedFrom[previous] : block.timestamp;
        }
        emit Crowned(taskId, die, c, previous, paid);
    }

    // ------------------------------------------------------------------------------------------------ fraud proofs

    /// @notice Break a wide-task die by naming one input on which it and its task's reference differ.
    function challenge(uint256 die, uint256 input) external {
        Die.Record memory r = DIE.record(die);
        if (!r.wide) revert NotWide();
        if (r.broken) revert Broken();
        if (block.timestamp >= uint256(r.provenAt) + CHALLENGE_WINDOW) revert WindowClosed();
        Task storage t = tasks[r.task - 1];
        if (VERIFIER.evalOne(r.netlist, input) == VERIFIER.evalOne(t.ref, input)) revert NotWrong();
        DIE.markBroken(die);
        uint256 bond = bondHeld[die];
        bondHeld[die] = 0;
        uint256 escrow = ethOwed[die];
        if (escrow != 0) {
            ethOwed[die] = 0;
            pot[r.task] += escrow; // a broken record's winnings go back to its task
        }
        emit Challenged(die, msg.sender, input);
        if (t.crown == die) {
            _accrue(r.task, t);
            if (t.crownSince < block.timestamp) revert NotSettled();
            uint32[] storage h = crownHistory[r.task];
            uint256 restored;
            while (h.length != 0) {
                uint32 last = h[h.length - 1];
                if (last != die && !DIE.record(last).broken) {
                    restored = last;
                    break;
                }
                h.pop();
            }
            t.crown = uint32(restored);
            t.crownSince = uint40(block.timestamp);
            if (restored != 0) {
                Die.Record memory p = DIE.record(restored);
                t.crownCost = p.cost;
                t.crownCommit = p.commitBlock;
            } else {
                // no record left: the reference is the bar again
                (uint256 rg, uint256 rd) = VERIFIER.measure(VERIFIER.load(t.ref));
                t.crownCost = uint64(VERIFIER.cost(rg, rd, t.objective));
                t.crownCommit = 0;
            }
            emit Revoked(r.task, die, restored);
        }
        if (bond != 0) _send(msg.sender, bond);
    }

    /// @notice A wide-task die that stood its three days gets its designer's bond back.
    function releaseBond(uint256 die) external {
        Die.Record memory r = DIE.record(die);
        if (r.broken) revert Broken();
        if (block.timestamp < uint256(r.provenAt) + CHALLENGE_WINDOW) revert TooSoon();
        uint256 b = bondHeld[die];
        if (b == 0) revert Nothing();
        bondHeld[die] = 0;
        _send(r.designer, b);
        emit BondReleased(die, b);
    }

    // ------------------------------------------------------------------------------------------------ Proof of Fee

    /// @notice By the hook, inside a swap: `amount` of the foundry's fee is directed to `task`. Returns false (and
    ///         books nothing) when there is no such task, so the hook sends that part to the furnace instead.
    function noteDirected(uint256 taskId, uint256 amount) external returns (bool) {
        if (msg.sender != stepper) revert NotStepper();
        if (taskId == 0 || taskId > tasks.length || amount == 0) return false;
        uint256 d = (block.timestamp - start) / DAY;
        directed[d][taskId] += amount;
        directedTotal[d] += amount;
        pot[taskId] += amount;
        emit Directed(d, taskId, amount);
        return true;
    }

    /// @notice Days since the pool opened; day 0 begins at the opening.
    function dayNow() public view returns (uint256) {
        if (start == 0) revert NotStarted();
        return (block.timestamp - start) / DAY;
    }

    /// @notice Day `d`'s full output before fee scaling: 273,972.6 RETICLE, halving every 1,460 days.
    function dayOutput(uint256 d) public pure returns (uint256) {
        uint256 h = d / HALVING_DAYS;
        return h >= 64 ? 0 : DAY0_OUTPUT >> h;
    }

    /// @notice A task's emission for a finished day: the day's output scaled by directed fees, times the task's
    ///         share of them (at most 20%).
    function taskEmission(uint256 taskId, uint256 d) public view returns (uint256) {
        uint256 w = directedTotal[d];
        if (w == 0) return 0;
        uint256 out = dayOutput(d);
        if (w < W_TARGET) out = (out * w) / W_TARGET;
        uint256 mine = directed[d][taskId] * 10_000;
        uint256 capped = w * TASK_CAP_BPS;
        return (out * (mine < capped ? mine : capped)) / (w * 10_000);
    }

    /// @notice Bring a task's crown time up to date (each claim does this for the crown it pays).
    function poke(uint32 taskId) external {
        _accrue(taskId, _task(taskId));
    }

    function _accrue(uint256 taskId, Task storage t) internal {
        uint256 nowT = block.timestamp;
        uint256 from = t.crownSince;
        if (t.crown == 0 || start == 0 || from >= nowT) {
            t.crownSince = uint40(nowT);
            return;
        }
        if (from < start) from = start;
        uint256 die = t.crown;
        for (uint256 i; i < MAX_ACCRUE_DAYS && from < nowT; ++i) {
            uint256 d = (from - start) / DAY;
            uint256 end = start + (d + 1) * DAY;
            uint256 to = end < nowT ? end : nowT;
            crownSeconds[taskId][d][die] += to - from;
            from = to;
        }
        t.crownSince = uint40(from);
    }

    /// @notice Mint a die's emission for one finished day to whoever holds the die now (royalties set aside).
    function claim(uint256 die, uint256 d) public returns (uint256 paid) {
        if (d >= dayNow()) revert NotSettled();
        Die.Record memory r = DIE.record(die);
        if (r.broken) revert Broken();
        if (r.wide && block.timestamp < uint256(r.provenAt) + CHALLENGE_WINDOW) revert TooSoon();
        Task storage t = tasks[r.task - 1];
        if (t.crown == die) {
            _accrue(r.task, t);
            if (t.crownSince < start + (d + 1) * DAY) revert NotSettled(); // more than 120 days behind: poke()
        }
        if (claimed[die][d]) revert AlreadyClaimed();
        claimed[die][d] = true;
        uint256 sec = crownSeconds[r.task][d][die];
        if (sec == 0) revert Nothing();
        uint256 amount = (taskEmission(r.task, d) * sec) / DAY;
        uint256 royalties = _royalties(die, r.gates, amount);
        paid = amount - royalties;
        address to = DIE.ownerOf(die);
        if (paid != 0) RETICLE.mint(to, paid);
        emit Claimed(die, d, to, paid, royalties);
    }

    /// @notice Several claim()s in one transaction, about 198,000 gas each: 40 fit well inside a block.
    function claimMany(uint256[] calldata dies, uint256[] calldata days_) external {
        for (uint256 i; i < dies.length; ++i) claim(dies[i], days_[i]);
    }

    function _royalties(uint256 die, uint256 gates, uint256 amount) internal returns (uint256 pool) {
        (uint32[] memory ids, uint32[] memory g) = DIE.parentsOf(die);
        if (ids.length == 0 || gates == 0) return 0;
        uint256 inlined;
        for (uint256 i; i < ids.length; ++i) inlined += g[i];
        pool = (amount * ROYALTY_BPS * inlined) / (10_000 * gates);
        if (inlined == 0) return pool;
        for (uint256 i; i < ids.length; ++i) {
            if (DIE.record(ids[i]).broken) continue; // a broken parent's part is never minted
            royaltyOwed[ids[i]] += (pool * g[i]) / inlined;
        }
    }

    /// @notice Mint the royalties another record's emission set aside for this die.
    function claimRoyalty(uint256 die) external returns (uint256 amount) {
        Die.Record memory r = DIE.record(die);
        if (r.broken) revert Broken();
        if (r.wide && block.timestamp < uint256(r.provenAt) + CHALLENGE_WINDOW) revert TooSoon();
        amount = royaltyOwed[die];
        if (amount == 0) revert Nothing();
        royaltyOwed[die] = 0;
        address to = DIE.ownerOf(die);
        RETICLE.mint(to, amount);
        emit RoyaltyPaid(die, to, amount);
    }

    /// @notice Pay a die's pot winnings (ETH) to whoever holds it.
    function claimEth(uint256 die) external returns (uint256 amount) {
        if (DIE.record(die).broken) revert Broken();
        if (block.timestamp < ethOwedFrom[die]) revert TooSoon();
        amount = ethOwed[die];
        if (amount == 0) revert Nothing();
        ethOwed[die] = 0;
        if (address(this).balance < amount) IStepperFlush(stepper).flush();
        address to = DIE.ownerOf(die);
        _send(to, amount);
        emit EthPaid(die, to, amount);
    }

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

    /// @notice How many tasks exist; ids run from 1.
    function taskCount() external view returns (uint256) {
        return tasks.length;
    }

    /// @notice A task, its record and its bar (crownCost is the reference's cost until a record exists).
    function task(uint256 id) external view returns (Task memory) {
        return tasks[id - 1];
    }

    /// @notice How many designs have been revealed; ids run from 1.
    function attemptCount() external view returns (uint256) {
        return attempts.length;
    }

    /// @notice A revealed design and how far its proof has run (state 1 proving, 2 proven, 3 failed).
    function attempt(uint256 id) external view returns (Attempt memory) {
        return attempts[id - 1];
    }

    /// @notice Every die that took the task's crown, oldest first (broken ones are popped when they fall).
    function historyOf(uint256 id) external view returns (uint32[] memory) {
        return crownHistory[id];
    }

    /// @notice The circuit a task runs today: its crown's netlist, or its reference before any record.
    function circuitFor(uint256 id) external view returns (address) {
        Task storage t = tasks[id - 1];
        return t.crown == 0 ? t.ref : DIE.netlistOf(t.crown);
    }

    /// @notice What claim(die, d) would pay now (0 if nothing, before royalties are set aside).
    function claimable(uint256 die, uint256 d) external view returns (uint256) {
        if (start == 0 || d >= dayNow() || claimed[die][d]) return 0;
        Die.Record memory r = DIE.record(die);
        if (r.broken) return 0;
        uint256 sec = crownSeconds[r.task][d][die];
        Task storage t = tasks[r.task - 1];
        if (t.crown == die && t.crownSince < start + (d + 1) * DAY) {
            uint256 from = t.crownSince < start + d * DAY ? start + d * DAY : t.crownSince;
            sec += start + (d + 1) * DAY - from;
        }
        return (taskEmission(r.task, d) * sec) / DAY;
    }

    // ------------------------------------------------------------------------------------------------ internals

    function _task(uint32 id) internal view returns (Task storage) {
        if (id == 0 || id > tasks.length) revert NoTask();
        return tasks[id - 1];
    }

    /// @dev Bytes as contract code (STOP guard first): constructor 0x61 size 80 600c 6000 39 6000 f3.
    function _store(bytes memory data) internal returns (address p) {
        uint256 size = data.length + 1;
        if (size > MAX_CODE + 1) revert TooBig();
        bytes memory init = abi.encodePacked(hex"61", uint16(size), hex"80600c6000396000f3", hex"00", data);
        assembly {
            p := create(0, add(init, 32), mload(init))
        }
        if (p == address(0)) revert TooBig();
    }

    function _send(address to, uint256 amount) internal {
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert SendFailed();
    }
}

src/Die.sol

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

// RETICLE · DATASHEET · DIE (part RT-D1)
// https://reticlefab.xyz   https://x.com/reticlefab
//
// FEATURES
//   ERC-721 "Reticle Die" / DIE. One token per circuit the foundry has proven equal to its task's reference, whether
//   or not it holds the record. Minted only by the foundry. Transferable: whoever holds a die is paid its record's
//   emission while it reigns, and its royalties whenever another record inlines it as an IP block.
//   Each die keeps its record for good: task, netlist (stored as contract code), gates, logic depth, cost, the block
//   its design was committed in, when it was proven, and the dies it inlined with how many gates each contributed.
//   The image is drawn on chain from the netlist itself (DieArt): a die shot.
//
// PIN DESCRIPTION
//   broken   set by the foundry when a fraud proof shows a wide-task die wrong on some input. A broken die earns no
//            emission and no royalty, and can never be inlined again.

interface IDieArt {
    function uri(uint256 id) external view returns (string memory);
}

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

contract Die {
    string public constant name = "Reticle Die";
    string public constant symbol = "DIE";

    struct Record {
        uint32 task;
        address netlist; // the flat netlist as contract code (STOP guard + bytes)
        uint32 gates;
        uint32 depth;
        uint64 cost;
        uint64 commitBlock;
        uint40 provenAt;
        bool wide;
        bool broken;
        address designer;
    }

    address public immutable LAUNCHER;
    address public foundry;
    IDieArt public art;
    uint256 public count;

    mapping(uint256 => Record) internal records;
    mapping(uint256 => uint32[]) internal parentIds;
    mapping(uint256 => uint32[]) internal parentGates;
    mapping(uint256 => address) internal owners;
    mapping(address => uint256) public balanceOf;
    mapping(uint256 => address) public getApproved;
    mapping(address => mapping(address => bool)) public isApprovedForAll;

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

    error NotLauncher();
    error NotFoundry();
    error AlreadyBound();
    error NoToken();
    error NotAllowed();
    error BadReceiver();
    error ZeroAddress();

    constructor(address launcher) {
        LAUNCHER = launcher;
    }

    /// @notice Once, by the launcher.
    function bind(address foundry_, address art_) external {
        if (msg.sender != LAUNCHER) revert NotLauncher();
        if (foundry != address(0)) revert AlreadyBound();
        foundry = foundry_;
        art = IDieArt(art_);
    }

    // ------------------------------------------------------------------------------------------------ foundry

    /// @notice By the foundry: a proven design becomes a die, minted to its designer.
    function mint(address to, Record calldata r, uint32[] calldata pIds, uint32[] calldata pGates)
        external
        returns (uint256 id)
    {
        if (msg.sender != foundry) revert NotFoundry();
        id = ++count;
        records[id] = r;
        parentIds[id] = pIds;
        parentGates[id] = pGates;
        owners[id] = to;
        unchecked {
            balanceOf[to] += 1;
        }
        emit Transfer(address(0), to, id);
    }

    /// @notice By the foundry, when a fraud proof breaks the die: it earns nothing more and cannot be inlined.
    function markBroken(uint256 id) external {
        if (msg.sender != foundry) revert NotFoundry();
        records[id].broken = true;
        emit Broken(id);
    }

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

    /// @notice Everything the chain keeps about a die.
    function record(uint256 id) external view returns (Record memory) {
        if (owners[id] == address(0)) revert NoToken();
        return records[id];
    }

    /// @notice Where a die's flat netlist is stored (contract code behind a STOP byte).
    function netlistOf(uint32 id) external view returns (address) {
        return records[id].netlist;
    }

    /// @notice The dies this one inlined, with the gates each contributed: the royalty shares.
    function parentsOf(uint256 id) external view returns (uint32[] memory ids, uint32[] memory gates) {
        return (parentIds[id], parentGates[id]);
    }

    /// @notice The holder of a die, who is paid its emission and royalties.
    function ownerOf(uint256 id) public view returns (address o) {
        o = owners[id];
        if (o == address(0)) revert NoToken();
    }

    /// @notice JSON metadata with the die shot, computed on chain by DieArt.
    function tokenURI(uint256 id) external view returns (string memory) {
        ownerOf(id);
        return art.uri(id);
    }

    /// @notice ERC-165.
    function supportsInterface(bytes4 i) external pure returns (bool) {
        return i == 0x01ffc9a7 || i == 0x80ac58cd || i == 0x5b5e139f; // ERC-165, ERC-721, metadata
    }

    // ------------------------------------------------------------------------------------------------ ERC-721

    /// @notice ERC-721: let `spender` move die `id`.
    function approve(address spender, uint256 id) external {
        address o = ownerOf(id);
        if (msg.sender != o && !isApprovedForAll[o][msg.sender]) revert NotAllowed();
        getApproved[id] = spender;
        emit Approval(o, spender, id);
    }

    /// @notice ERC-721: let `operator` move every die you hold.
    function setApprovalForAll(address operator, bool approved) external {
        isApprovedForAll[msg.sender][operator] = approved;
        emit ApprovalForAll(msg.sender, operator, approved);
    }

    /// @notice ERC-721 transfer. The die's future emission and royalties follow it.
    function transferFrom(address from, address to, uint256 id) public {
        if (to == address(0)) revert ZeroAddress();
        if (from != ownerOf(id)) revert NotAllowed();
        if (msg.sender != from && !isApprovedForAll[from][msg.sender] && msg.sender != getApproved[id]) revert NotAllowed();
        unchecked {
            balanceOf[from] -= 1;
            balanceOf[to] += 1;
        }
        owners[id] = to;
        delete getApproved[id];
        emit Transfer(from, to, id);
    }

    /// @notice ERC-721 transfer that checks a contract receiver accepts it.
    function safeTransferFrom(address from, address to, uint256 id) external {
        safeTransferFrom(from, to, id, "");
    }

    /// @notice ERC-721 transfer that checks a contract receiver accepts it, passing `data`.
    function safeTransferFrom(address from, address to, uint256 id, bytes memory data) public {
        transferFrom(from, to, id);
        if (to.code.length != 0) {
            if (IERC721Receiver(to).onERC721Received(msg.sender, from, id, data) != IERC721Receiver.onERC721Received.selector) {
                revert BadReceiver();
            }
        }
    }
}

src/Verifier.sol

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

// RETICLE · DATASHEET · VERIFIER (part RT-V1)
// https://reticlefab.xyz   https://x.com/reticlefab
//
// FUNCTION
//   Stateless. Flattens a design source (its own NAND gates plus instances of proven Die circuits) into one flat
//   netlist, measures it (gates, logic depth), and proves it equal to a task's reference netlist on every input,
//   256 input combinations per EVM word ("bit-sliced"): one AND and one NOT simulate a gate on 256 inputs at once.
//
// FLAT NETLIST (bytes)
//   nIn u8 | nOut u8 | nGates u16 | nGates x (a u16, b u16) | nOut x (wire u16)
//   wires 0..nIn-1 are inputs; wire nIn+k is gate k = NAND(wire a, wire b) with a, b < nIn+k (strictly earlier).
//
// DESIGN SOURCE (bytes)
//   nIn u8 | nOut u8 | nInst u8 | nGates u16 | instances | gates (a u16, b u16) | outputs (u16)
//   instance: dieId u32 | k u8 | k x (source wire u16)        k must equal the die's own input count
//   source wires: inputs, then each instance's outputs in order, then own gates. Every reference points earlier.
//
// MEASURED (forge, solc 0.8.26 viaIR, 1000 runs)
//   109 gas per gate per 256-input pass. 16 inputs exhaustively (256 passes): 8-bit adder of 68 gates 5.9M gas
//   with its reference; 8x8 multiplier of 600 gates 33.6M gas, proven over several transactions.
//
// ABSOLUTE MAXIMUM RATINGS
//   64 inputs, 64 outputs, 8,192 gates per flat netlist, 32 instances per source.

contract Verifier {
    uint256 public constant MAX_IO = 64;
    uint256 public constant MAX_GATES = 8192;
    uint256 public constant MAX_INSTANCES = 32;
    uint256 public constant EXHAUSTIVE_INPUTS = 16; // up to this many inputs, every combination is proven
    uint256 public constant RANDOM_PASSES = 32; // wider tasks: 32 x 256 = 8,192 vectors from a committed seed

    error Malformed();
    error TooBig();
    error Interface();

    // ------------------------------------------------------------------------------------------------ reading

    /// @notice Bytes of a netlist stored as contract code (the first code byte is a STOP guard).
    function load(address pointer) public view returns (bytes memory n) {
        uint256 size = pointer.code.length;
        if (size < 5) revert Malformed();
        n = new bytes(size - 1);
        assembly {
            extcodecopy(pointer, add(n, 32), 1, sub(size, 1))
        }
    }

    /// @notice A flat netlist's inputs, outputs and gate count, with its length checked against them.
    function header(bytes memory n) public pure returns (uint256 nIn, uint256 nOut, uint256 nGates) {
        if (n.length < 4) revert Malformed();
        nIn = uint8(n[0]);
        nOut = uint8(n[1]);
        nGates = (uint256(uint8(n[2])) << 8) | uint8(n[3]);
        if (nIn == 0 || nOut == 0 || nIn > MAX_IO || nOut > MAX_IO) revert Malformed();
        if (nGates > MAX_GATES) revert TooBig();
        if (n.length != 4 + nGates * 4 + nOut * 2) revert Malformed();
    }

    /// @notice A flat netlist is well formed: every gate reads strictly earlier wires, every output names a wire.
    function check(bytes memory n) public pure returns (uint256 nIn, uint256 nOut, uint256 nGates) {
        (nIn, nOut, nGates) = header(n);
        for (uint256 k; k < nGates; ++k) {
            uint256 o = 4 + k * 4;
            if (_u16(n, o) >= nIn + k || _u16(n, o + 2) >= nIn + k) revert Malformed();
        }
        uint256 base = 4 + nGates * 4;
        for (uint256 j; j < nOut; ++j) if (_u16(n, base + j * 2) >= nIn + nGates) revert Malformed();
    }

    /// @notice Gate count and logic depth (the longest NAND path from an input to an output).
    function measure(bytes memory n) public pure returns (uint256 gates, uint256 depth) {
        (uint256 nIn, uint256 nOut, uint256 nGates) = header(n);
        uint256[] memory level = new uint256[](nIn + nGates);
        for (uint256 k; k < nGates; ++k) {
            uint256 o = 4 + k * 4;
            uint256 la = level[_u16(n, o)];
            uint256 lb = level[_u16(n, o + 2)];
            level[nIn + k] = (la > lb ? la : lb) + 1;
        }
        uint256 base = 4 + nGates * 4;
        for (uint256 j; j < nOut; ++j) {
            uint256 l = level[_u16(n, base + j * 2)];
            if (l > depth) depth = l;
        }
        gates = nGates;
    }

    /// @notice The cost a task scores: objective 0 = gates, 1 = gates x depth, 2 = gates x depth^2 (depth >= 1).
    function cost(uint256 gates, uint256 depth, uint8 objective) public pure returns (uint256) {
        uint256 d = depth == 0 ? 1 : depth;
        if (objective == 0) return gates;
        if (objective == 1) return gates * d;
        return gates * d * d;
    }

    // ------------------------------------------------------------------------------------------------ flattening

    /// @notice The dies a source instantiates, in order.
    function instancesOf(bytes memory src) public pure returns (uint32[] memory ids) {
        (,, uint256 nInst,) = _srcHeader(src);
        ids = new uint32[](nInst);
        uint256 o = 5;
        for (uint256 k; k < nInst; ++k) {
            ids[k] = uint32(_u32(src, o));
            o += 5 + 2 * _u8(src, o + 4);
        }
    }

    /// @dev The flattening state shared by its helpers (one memory struct keeps the stack shallow).
    struct Ctx {
        bytes src;
        bytes flat;
        uint256[] map; // source wire -> flat wire
        uint256 nIn;
        uint256 s; // next source wire
        uint256 f; // next flat wire
        uint256 o; // read offset in src
    }

    /// @notice Inline every instance (given as the dies' netlist pointers, in order) and append the source's own
    ///         gates: one flat netlist. `inlined[k]` is how many gates instance k contributed (for royalties).
    function flatten(bytes memory src, address[] memory dies)
        public
        view
        returns (bytes memory flat, uint256[] memory inlined)
    {
        (uint256 nIn, uint256 nOut, uint256 nInst, uint256 ownGates) = _srcHeader(src);
        if (dies.length != nInst) revert Malformed();
        bytes[] memory subs = new bytes[](nInst);
        uint256 total = ownGates;
        uint256 srcWires = nIn + ownGates;
        for (uint256 k; k < nInst; ++k) {
            subs[k] = load(dies[k]);
            (, uint256 sOut, uint256 sGates) = header(subs[k]);
            total += sGates;
            srcWires += sOut;
        }
        if (total > MAX_GATES || nIn + total > type(uint16).max) revert TooBig();
        flat = new bytes(4 + total * 4 + nOut * 2);
        flat[0] = bytes1(uint8(nIn));
        flat[1] = bytes1(uint8(nOut));
        flat[2] = bytes1(uint8(total >> 8));
        flat[3] = bytes1(uint8(total));
        Ctx memory x = Ctx(src, flat, new uint256[](srcWires), nIn, nIn, nIn, 5);
        for (uint256 i; i < nIn; ++i) x.map[i] = i;
        inlined = new uint256[](nInst);
        for (uint256 k; k < nInst; ++k) inlined[k] = _inline(x, subs[k]);
        for (uint256 g; g < ownGates; ++g) _ownGate(x);
        _outputs(x, nOut, total);
    }

    /// @dev One instance: map its inputs, copy its gates renumbered, map its outputs. Returns its gate count.
    function _inline(Ctx memory x, bytes memory sub) private pure returns (uint256 sGates) {
        uint256 sIn;
        uint256 sOut;
        (sIn, sOut, sGates) = header(sub);
        if (_u8(x.src, x.o + 4) != sIn) revert Interface();
        uint256[] memory m = new uint256[](sIn + sGates); // die wire -> flat wire
        for (uint256 j; j < sIn; ++j) {
            uint256 w = _u16(x.src, x.o + 5 + 2 * j);
            if (w >= x.s) revert Malformed();
            m[j] = x.map[w];
        }
        x.o += 5 + 2 * sIn;
        for (uint256 g; g < sGates; ++g) {
            _gate(x.flat, x.f - x.nIn, m[_u16(sub, 4 + g * 4)], m[_u16(sub, 6 + g * 4)]);
            m[sIn + g] = x.f++;
        }
        uint256 base = 4 + sGates * 4;
        for (uint256 j; j < sOut; ++j) x.map[x.s++] = m[_u16(sub, base + j * 2)];
    }

    function _ownGate(Ctx memory x) private pure {
        uint256 a = _u16(x.src, x.o);
        uint256 b = _u16(x.src, x.o + 2);
        if (a >= x.s || b >= x.s) revert Malformed();
        _gate(x.flat, x.f - x.nIn, x.map[a], x.map[b]);
        x.map[x.s++] = x.f++;
        x.o += 4;
    }

    function _outputs(Ctx memory x, uint256 nOut, uint256 total) private pure {
        uint256 ob = 4 + total * 4;
        for (uint256 j; j < nOut; ++j) {
            uint256 w = _u16(x.src, x.o + 2 * j);
            if (w >= x.s) revert Malformed();
            uint256 fw = x.map[w];
            x.flat[ob + 2 * j] = bytes1(uint8(fw >> 8));
            x.flat[ob + 2 * j + 1] = bytes1(uint8(fw));
        }
        if (x.src.length != x.o + 2 * nOut) revert Malformed();
    }

    // ------------------------------------------------------------------------------------------------ proving

    /// @notice How many 256-input passes prove a task with `nIn` inputs.
    function passesFor(uint256 nIn) public pure returns (uint256) {
        if (nIn > EXHAUSTIVE_INPUTS) return RANDOM_PASSES;
        return nIn <= 8 ? 1 : 1 << (nIn - 8);
    }

    /// @notice Run passes [from, to) of the equivalence proof of `cand` against `ref`. For a task of more than 16
    ///         inputs, pass p feeds inputs drawn from keccak(seed, p, i); otherwise pass p is combinations
    ///         p*256 .. p*256+255. Returns false at the first output that differs.
    function proveRange(address cand, address ref, uint256 from, uint256 to, uint256 seed) external view returns (bool) {
        bytes memory c = load(cand);
        bytes memory r = load(ref);
        (uint256 nIn, uint256 nOut, uint256 cG) = header(c);
        (uint256 rIn, uint256 rOut, uint256 rG) = header(r);
        if (nIn != rIn || nOut != rOut) revert Interface();
        bool wide = nIn > EXHAUSTIVE_INPUTS;
        uint256 live = nIn >= 8 ? type(uint256).max : (uint256(1) << (1 << nIn)) - 1;
        uint256[] memory wa = new uint256[](nIn + cG);
        uint256[] memory wb = new uint256[](nIn + rG);
        uint256[] memory ca = _decode(c, wa, cG);
        uint256[] memory cb = _decode(r, wb, rG);
        uint256[] memory oa = _outs(c, nIn, cG, nOut);
        uint256[] memory ob = _outs(r, nIn, rG, nOut);
        uint256 da;
        uint256 db;
        assembly {
            da := add(add(wa, 32), shl(5, nIn))
            db := add(add(wb, 32), shl(5, nIn))
        }
        for (uint256 p = from; p < to; ++p) {
            for (uint256 i; i < nIn; ++i) {
                uint256 v = wide ? uint256(keccak256(abi.encode(seed, p, i))) : _lane(i, p);
                wa[i] = v;
                wb[i] = v;
            }
            _run(ca, da);
            _run(cb, db);
            for (uint256 j; j < nOut; ++j) if ((wa[oa[j]] ^ wb[ob[j]]) & live != 0) return false;
        }
        return true;
    }

    /// @notice One input vector through a netlist (bit i of `input` drives input i): the output bits.
    function evalOne(address pointer, uint256 input) public view returns (uint256 out) {
        bytes memory n = load(pointer);
        (uint256 nIn, uint256 nOut, uint256 nG) = header(n);
        uint256[] memory w = new uint256[](nIn + nG);
        for (uint256 i; i < nIn; ++i) w[i] = (input >> i) & 1;
        uint256[] memory code = _decode(n, w, nG);
        uint256 d;
        assembly {
            d := add(add(w, 32), shl(5, nIn))
        }
        _run(code, d);
        uint256 base = 4 + nG * 4;
        for (uint256 j; j < nOut; ++j) out |= (w[_u16(n, base + 2 * j)] & 1) << j;
    }

    // ------------------------------------------------------------------------------------------------ internals

    /// @dev Pass p, input i (< 8: a fixed lane pattern; >= 8: all ones or all zeros by bit i-8 of p).
    function _lane(uint256 i, uint256 p) private pure returns (uint256 w) {
        if (i >= 8) return ((p >> (i - 8)) & 1) == 1 ? type(uint256).max : 0;
        if (i == 0) return 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
        if (i == 1) return 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc;
        if (i == 2) return 0xf0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0;
        if (i == 3) return 0xff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00;
        if (i == 4) return 0xffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000;
        if (i == 5) return 0xffffffff00000000ffffffff00000000ffffffff00000000ffffffff00000000;
        if (i == 6) return 0xffffffffffffffff0000000000000000ffffffffffffffff0000000000000000;
        return 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000;
    }

    /// @dev Each gate once into one word: memory address of input a << 128 | memory address of input b.
    function _decode(bytes memory n, uint256[] memory wires, uint256 nGates) private pure returns (uint256[] memory code) {
        code = new uint256[](nGates);
        assembly {
            let w := add(wires, 32)
            let g := add(n, 36)
            let c := add(code, 32)
            let end := add(c, shl(5, nGates))
            for {} lt(c, end) {
                c := add(c, 32)
                g := add(g, 4)
            } {
                let x := mload(g)
                mstore(c, or(shl(128, add(w, shl(5, shr(240, x)))), add(w, shl(5, and(shr(224, x), 0xffff)))))
            }
        }
    }

    /// @dev The gate loop: writes gate outputs from `dst` on (the netlist's own order is topological).
    function _run(uint256[] memory code, uint256 dst) private pure {
        assembly {
            let c := add(code, 32)
            let end := add(c, shl(5, mload(code)))
            let m := 0xffffffffffffffffffffffffffffffff
            for {} lt(c, end) {
                c := add(c, 32)
                dst := add(dst, 32)
            } {
                let x := mload(c)
                mstore(dst, not(and(mload(shr(128, x)), mload(and(x, m)))))
            }
        }
    }

    function _outs(bytes memory n, uint256 nIn, uint256 nGates, uint256 nOut) private pure returns (uint256[] memory o) {
        o = new uint256[](nOut);
        uint256 base = 4 + nGates * 4;
        for (uint256 j; j < nOut; ++j) o[j] = _u16(n, base + 2 * j);
        nIn;
    }

    function _gate(bytes memory flat, uint256 k, uint256 a, uint256 b) private pure {
        uint256 o = 4 + k * 4;
        flat[o] = bytes1(uint8(a >> 8));
        flat[o + 1] = bytes1(uint8(a));
        flat[o + 2] = bytes1(uint8(b >> 8));
        flat[o + 3] = bytes1(uint8(b));
    }

    function _srcHeader(bytes memory src) private pure returns (uint256 nIn, uint256 nOut, uint256 nInst, uint256 nGates) {
        if (src.length < 5) revert Malformed();
        nIn = uint8(src[0]);
        nOut = uint8(src[1]);
        nInst = uint8(src[2]);
        nGates = (uint256(uint8(src[3])) << 8) | uint8(src[4]);
        if (nIn == 0 || nOut == 0 || nIn > MAX_IO || nOut > MAX_IO) revert Malformed();
        if (nInst > MAX_INSTANCES) revert TooBig();
        if (nGates > MAX_GATES) revert TooBig();
    }

    function _u8(bytes memory b, uint256 o) private pure returns (uint256) {
        if (o >= b.length) revert Malformed();
        return uint8(b[o]);
    }

    function _u16(bytes memory b, uint256 o) private pure returns (uint256) {
        if (o + 2 > b.length) revert Malformed();
        return (uint256(uint8(b[o])) << 8) | uint8(b[o + 1]);
    }

    function _u32(bytes memory b, uint256 o) private pure returns (uint256) {
        return (_u16(b, o) << 16) | _u16(b, o + 2);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "solmate/=lib/solmate/",
    "v4-core/=lib/v4-core/",
    "@uniswap/v4-core/=lib/v4-core/",
    "v4-periphery/=lib/v4-periphery/",
    "permit2/=lib/permit2/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.