// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {IIMD} from "./protocol/IIMD.sol"; import {IIntake} from "./protocol/IIntake.sol"; import {IIntakeReceiver} from "./protocol/IIntakeReceiver.sol"; import {IntakeBinding} from "./protocol/IntakeBinding.sol"; import {WishOrders} from "./orders/WishOrders.sol"; import {ChangeReceipt} from "./receipt/ChangeReceipt.sol"; /// @title changeme /// @notice A website owned by this contract. Anyone adds a short wish and pays IMD; every /// contribution mints a CHANGE receipt. When the oldest waiting round can cover the live Intake quote /// (and no build is running) the round is sent to the IMD swarm as one rebuild. Every attempt, /// round and successful version is kept on-chain forever. /// @dev One immutable, ownerless contract: no owner, admin, proxy, pause, fee, ERC-20 or pool. /// See README.md for the full price, batch, recovery and archive rules. contract Changeme is ChangeReceipt, IIntakeReceiver { // ------------------------------------------------------------------ constants /// @notice Smallest accepted contribution (0.1 IMD). uint256 public constant MIN_ENTRY = 0.1 ether; /// @notice Wishes per round, equal to the order encoder's per-request maximum. uint256 public constant MAX_ROUND_WISHES = WishOrders.MAX_WISHES; /// @notice Delay before recovering a silent attempt or an unproven success. uint256 public constant RECOVERY_DELAY = 1 days; /// @notice Largest result document `proveJob` accepts (bounds calldata scanning and proof gas). uint256 public constant MAX_RESULT_DOC_BYTES = 16_384; /// @notice Deepest JSON nesting `proveJob` accepts. uint256 public constant MAX_JSON_DEPTH = 64; /// @notice Most URI bytes a success callback copies into RoundBuilt (liveness-6). A longer URI is /// accepted, emitted truncated with its full length; the full URI is the `uri` of Intake's /// `Completed(requestId, ...)` event (see docs/security/CALLBACKS.md). uint256 public constant MAX_CALLBACK_URI_BYTES = 256; // ------------------------------------------------------------------ types enum RoundState { Open, // waiting to be sent (only the newest round can collect wishes) Sent, // an attempt for it is pending or awaiting retry/skip Built, // an attempt succeeded: it is a version Skipped // abandoned by skip(); its wishes stay in the archive } enum AttemptStatus { None, Pending, // paid, waiting for the Intake callback Succeeded, // onResult accepted while it was the active attempt Refused, // onFailure status 1 (admission refused) Failed, // onFailure any other nonzero status Abandoned // still pending when it was retried or skipped } /// @notice How the next build names its parent. enum HeadMode { Open, // no project yet: job.open Continue, // continue from a proven newest job NeedsProof, // newest success is unproven and still within RECOVERY_DELAY (anyone: proveJob) Unknown // failed, silent or overdue proof: only a caller-funded retry may name the head } struct Round { uint64 firstToken; // receipts firstToken .. firstToken + wishCount - 1 hold the wishes uint32 wishCount; RoundState state; uint32 attemptCount; uint64 lastAttempt; uint64 version; // nonzero once built uint256 contributed; // IMD paid by this round's contributors } struct Attempt { // slot 1 uint64 round; AttemptStatus status; bool continuation; // job.continue (true) or job.open (false) bool parentProven; // parent came from on-chain proof (false: caller supplied it) address sponsor; // zero for contributor-only payment; otherwise the retry or shortfall payer // slot 2 uint40 sentAt; uint40 settledAt; // slot 3 uint256 paid; // slots 4.. uint8 failureStatus; bytes32 requestId; bytes32 resultHash; bytes32 failureReason; string parentJobId; string jobId; // proven from the hash-committed result document } /// @notice Credit belongs to the receipt's original contributor, never its NFT holder. struct Credit { uint256 remaining; uint256 refundableAt; // earliest refund; fixed at contribution time and never extended bool cancelled; // a refund before Built excludes this wish from every later request } // ------------------------------------------------------------------ errors error Reentrancy(); error AmountBelowMinimum(uint256 amount, uint256 minimum); error ShortfallUnavailable(); error PullFailed(); error PriceAboveMax(uint256 price, uint256 maxPrice); error PriceUnavailable(bytes32 action); error NothingToRecover(); error NotRecoverableYet(uint256 attemptId, uint256 readyAt); error RetryNotNeeded(); error EmptyRound(uint256 round); error ParentNotAccepted(); error ParentRequired(); error ParentSuperseded(uint256 version); error HeadNeedsProof(uint256 attemptId); error UnknownRequest(bytes32 requestId); error UnknownAttempt(uint256 attemptId); error NotSucceeded(uint256 attemptId); error AlreadyProven(uint256 attemptId); error ResultHashMismatch(bytes32 expected, bytes32 actual); error BadResultDocument(); error UnknownVersion(uint256 version); error NotContributor(uint256 tokenId); error RefundNotReady(uint256 tokenId, uint256 readyAt); error NoCredit(uint256 tokenId); error RefundFailed(); // ------------------------------------------------------------------ events event Contributed( uint256 indexed round, uint256 indexed tokenId, address indexed contributor, uint256 amount, string wish ); event ShortfallFunded(uint256 indexed round, address indexed sponsor, uint256 amount); event RoundSent( uint256 indexed round, uint256 indexed attemptId, bytes32 indexed requestId, bool continuation, string parentJobId, uint256 price, address sponsor ); event RoundBuilt( uint256 indexed round, uint256 indexed attemptId, uint256 indexed version, bytes32 requestId, bytes32 resultHash, string uri, // at most MAX_CALLBACK_URI_BYTES bytes: a prefix when uriLength is larger uint256 uriLength ); event AttemptFailed( uint256 indexed round, uint256 indexed attemptId, bytes32 indexed requestId, uint8 status, bytes32 reason ); event StaleCallback(uint256 indexed attemptId, bytes32 indexed requestId, bool success); event RoundSkipped(uint256 indexed round, uint256 indexed attemptId, address caller); event JobProven(uint256 indexed attemptId, uint256 indexed version, string jobId); event ContributionRefunded( uint256 indexed round, uint256 indexed tokenId, address indexed contributor, uint256 amount, bool cancelled ); // ------------------------------------------------------------------ state uint256 private _lock = 1; /// @notice Round currently collecting wishes. Rounds are numbered from 1. uint256 public openRound; /// @notice Oldest waiting round, or the empty collecting tail when nothing is queued. uint256 public nextRound; /// @notice Total unspent contributions across all rounds, including archived rounds. uint256 public openPool; /// @notice Attempt waiting for a callback or for retry/skip; zero when idle. uint256 public activeAttempt; /// @notice Round accepting caller-funded recovery candidates; zero when none (funds-2). Candidates /// never hold `activeAttempt`: any sponsor may add one at any time while this is set. uint256 public recoveringRound; /// @notice Newest candidate ever sent (never cleared; zero: none). While `recoveringRound` is set, a free /// skip of that round waits for this candidate's sentAt + RECOVERY_DELAY. uint256 public newestCandidate; /// @notice Attempt that names the project head: the newest canonical attempt or winning candidate. uint256 public headAttempt; /// @notice Attempts are numbered 1..attemptCount, in send order. uint256 public attemptCount; /// @notice Versions (successful builds) are numbered 1..versionCount; the newest is shown. uint256 public versionCount; uint256 public totalContributed; uint256 public totalSponsored; uint256 public totalSpent; uint256 public totalRefunded; mapping(uint256 => Round) private _rounds; mapping(uint256 => Credit) public creditOf; mapping(uint256 => uint256) private _cancelledWishes; /// @dev Sum of `creditOf(t).remaining` over the round's receipts (funding-r3). mapping(uint256 => uint256) private _roundCredit; mapping(uint256 => Attempt) private _attempts; mapping(uint256 => uint256) private _versionAttempt; /// @dev keccak256(proven jobId) => version; written only in proveJob (recovery-r1). mapping(bytes32 => uint256) private _provenVersion; uint256 private _newestProven; /// @notice Intake request id to attempt id (zero: not ours). mapping(bytes32 => uint256) public attemptOfRequest; modifier nonReentrant() { _enter(); _; _lock = 1; } function _enter() private { if (_lock != 1) revert Reentrancy(); _lock = 2; } constructor() { openRound = 1; nextRound = 1; _rounds[1].firstToken = 1; } // ================================================================== contributing /// @notice Add a wish to the open round, paying exactly `amount` IMD (approve this contract first). /// Mints one CHANGE receipt. If no build is running and the pool now covers the live quote, /// the round is sent at once. /// @param maxPrice Highest job quote at which this transaction may send the round; if sending /// would need a higher quote the whole transaction reverts and nothing is charged. function contribute(string calldata wish, uint256 amount, uint256 maxPrice) external nonReentrant returns (uint256 tokenId, bool sent) { WishOrders.validateWish(wish); if (amount < MIN_ENTRY) revert AmountBelowMinimum(amount, MIN_ENTRY); // Admission must not take money for an action that is not currently sold. An unknown // head before the first version can recover through either open or continue: check both. (HeadMode mode,) = _head(); uint256 price = _requirePrice(mode == HeadMode.Open ? IntakeBinding.JOB_OPEN : IntakeBinding.JOB_CONTINUE); if (mode == HeadMode.Unknown && versionCount == 0) { uint256 openPrice = _requirePrice(IntakeBinding.JOB_OPEN); if (openPrice > price) price = openPrice; } uint256 roundId = openRound; Round storage r = _rounds[roundId]; _pull(msg.sender, amount); openPool += amount; totalContributed += amount; r.contributed += amount; r.wishCount += 1; uint256 credit = _roundCredit[roundId] += amount; tokenId = _mintReceipt(msg.sender, wish, roundId, amount); creditOf[tokenId] = Credit(amount, block.timestamp + RECOVERY_DELAY, false); emit Contributed(roundId, tokenId, msg.sender, amount, wish); // funding-r3: a batch is the wishes that together reach the quote (or 50 wishes), build running or not. if (credit >= price || r.wishCount == MAX_ROUND_WISHES) _advanceTail(); if (roundId == nextRound) sent = _dispatch(maxPrice, false); } /// @notice Send the oldest waiting round if its own funds cover the live quote and the head is ready. function dispatch() external nonReentrant returns (bool sent) { return _dispatch(type(uint256).max, false); } /// @notice Pay the exact live shortfall for the oldest full round and send it atomically. /// The payer receives no receipt because this payment adds no wish. /// @param roundId Expected oldest waiting round, to bind consent to one batch. /// @param maxShortfall Maximum extra IMD the caller authorizes, in wei. function fundShortfall(uint256 roundId, uint256 maxShortfall) external nonReentrant { if (roundId != nextRound || !_dispatch(maxShortfall, true)) revert ShortfallUnavailable(); } /// @notice Return all remaining credit to its original payer after one day. No Intake or /// head reads, approval, sponsor or dispatch. The receipt and original wish remain archived. /// Until this call, unspent credit keeps funding its own batch (even past the deadline): a send /// ordered first spends it on this wish; a refund ordered first removes it and the wish. function refund(uint256 tokenId) external nonReentrant returns (uint256 amount) { Receipt storage receipt = _receipts[tokenId]; if (receipt.contributor != msg.sender) revert NotContributor(tokenId); Credit storage c = creditOf[tokenId]; if (block.timestamp < c.refundableAt) revert RefundNotReady(tokenId, c.refundableAt); amount = c.remaining; if (amount == 0) revert NoCredit(tokenId); c.remaining = 0; _roundCredit[receipt.round] -= amount; if (_rounds[receipt.round].state != RoundState.Built) { c.cancelled = true; ++_cancelledWishes[receipt.round]; } openPool -= amount; totalRefunded += amount; emit ContributionRefunded(receipt.round, tokenId, msg.sender, amount, c.cancelled); IIMD token = IIMD(IntakeBinding.IMD); uint256 before = _balance(address(this)); uint256 received = _balance(msg.sender); if (!token.transfer(msg.sender, amount)) revert RefundFailed(); if (_balance(address(this)) != before - amount || _balance(msg.sender) != received + amount) { revert RefundFailed(); } } // ================================================================== recovery /// @notice Pay a new attempt yourself, at the live quote (at most `maxPrice`). Allowed when /// (a) the active attempt was sent at least RECOVERY_DELAY ago and has not succeeded (pending, /// refused or failed alike: liveness-4): the same round is sent again; or /// (b) nothing is running but the project head is unknown (including a success still unproven /// RECOVERY_DELAY after settlement): the oldest waiting round is sent. /// Contributors are never charged again. `parentJobId` must be empty unless the head is /// unknown; then pass the project's newest job id (empty opens a new project, only allowed /// before any version exists). With an unknown head the attempt is a recovery candidate /// (funds-2): it never takes `activeAttempt`, the round stays in `recoveringRound`, any other /// sponsor may add a candidate at once, and the first candidate whose success reaches this /// contract becomes the version. A wrong parent risks only the caller's payment. function retry(string calldata parentJobId, uint256 maxPrice) external nonReentrant returns (uint256 attemptId) { (HeadMode mode, string memory parent) = _head(); if (mode == HeadMode.NeedsProof) revert HeadNeedsProof(headAttempt); bool headUnknown = mode == HeadMode.Unknown; if (headUnknown) { if (bytes(parentJobId).length == 0) { if (versionCount != 0) revert ParentRequired(); mode = HeadMode.Open; } else { mode = HeadMode.Continue; parent = parentJobId; // shape checked by the encoder // recovery-r1: the chain refutes a parent proven for any version but the newest proven. uint256 pv = _provenVersion[keccak256(bytes(parentJobId))]; if (pv != 0 && pv != _newestProven) revert ParentSuperseded(pv); } } else if (bytes(parentJobId).length != 0) { revert ParentNotAccepted(); } bool continuation = mode == HeadMode.Continue; bytes32 action = continuation ? IntakeBinding.JOB_CONTINUE : IntakeBinding.JOB_OPEN; uint256 price = _requirePrice(action); if (price > maxPrice) revert PriceAboveMax(price, maxPrice); // funds-2: a round under recovery takes another candidate at once, without any lock. uint256 roundId = recoveringRound; if (roundId == 0) { uint256 active = activeAttempt; if (active != 0) { _requireRecoverable(active); roundId = _attempts[active].round; _closeActive(active); } else { roundId = nextRound; if (_rounds[roundId].wishCount == _cancelledWishes[roundId]) revert EmptyRound(roundId); if (!headUnknown) revert RetryNotNeeded(); _dequeue(roundId); } if (headUnknown) recoveringRound = roundId; } _pull(msg.sender, price); totalSponsored += price; attemptId = _send(roundId, continuation, parent, !headUnknown, price, msg.sender); if (headUnknown) newestCandidate = attemptId; } /// @notice Give up on the active round RECOVERY_DELAY after it was sent, whatever it reported. /// Its wishes and receipts stay in the archive; the last good version stays selected. /// A round under candidate recovery may be skipped RECOVERY_DELAY after its newest candidate was /// sent; candidates still running then become stale. /// @dev review-l1: the skip transition commits on its own. It neither reads the Intake quote nor /// touches IMD nor submits a request, so a positive quote with a reverting request, an unavailable /// quote, a failing approval or a silent Intake can never undo it. The next round is sent by a /// separate `dispatch()`, `contribute` or `proveJob` call once the head and the Intake allow it. function skip() external nonReentrant { uint256 id = activeAttempt; uint256 roundId = recoveringRound; if (id != 0) { _requireRecoverable(id); roundId = _attempts[id].round; _closeActive(id); } else if (roundId != 0) { id = newestCandidate; _requireRecoverable(id); recoveringRound = 0; } else { revert NothingToRecover(); } _rounds[roundId].state = RoundState.Skipped; emit RoundSkipped(roundId, id, msg.sender); } /// @notice Prove the job id of a successful attempt with its exact result document /// (keccak256 equals the callback's resultHash). Reads the document's top-level "jobId" with a /// strict, conservative JSON scan (at most MAX_RESULT_DOC_BYTES bytes and MAX_JSON_DEPTH levels; /// escaped root keys, duplicate root "jobId" and non-literal UUIDs are rejected). A rejected /// document changes nothing; the head then falls back to caller-funded recovery RECOVERY_DELAY /// after settlement. The newest attempt's proven job becomes the parent of the next continuation /// and the waiting round is dispatched in the same call when the pool covers it. Anyone may call. function proveJob(uint256 attemptId, bytes calldata resultDocument) external { _proveJob(attemptId, resultDocument, true); } /// @notice Prove the job independently of ordering the next build. function proveJobOnly(uint256 attemptId, bytes calldata resultDocument) external { _proveJob(attemptId, resultDocument, false); } function _proveJob(uint256 attemptId, bytes calldata resultDocument, bool dispatchNext) private nonReentrant { Attempt storage a = _attempts[attemptId]; if (a.status != AttemptStatus.Succeeded) revert NotSucceeded(attemptId); if (bytes(a.jobId).length != 0) revert AlreadyProven(attemptId); if (resultDocument.length > MAX_RESULT_DOC_BYTES) revert BadResultDocument(); bytes32 h = keccak256(resultDocument); if (h != a.resultHash) revert ResultHashMismatch(a.resultHash, h); string memory jobId = _topLevelJobId(resultDocument); a.jobId = jobId; uint256 pv = _rounds[a.round].version; _provenVersion[keccak256(bytes(jobId))] = pv; if (pv > _newestProven) _newestProven = pv; emit JobProven(attemptId, _rounds[a.round].version, jobId); if (dispatchNext && attemptId == headAttempt) _dispatch(type(uint256).max, false); } // ================================================================== Intake callbacks /// @dev intake-2 / liveness-6: authenticated caller, our own recorded request, and Intake's own /// record of that request (payer, callback target and selector are this contract, completed is /// set) before anything settles. URI work is capped at MAX_CALLBACK_URI_BYTES. Bounded work only: /// no proof parsing, no dispatch, no wish iteration; stays far below the 200,000 gas stipend. function onResult(bytes32 requestId, bytes32 resultHash, string calldata uri) external { uint256 id = _callbackAttempt(requestId); Attempt storage a = _attempts[id]; if (!_live(id, a, requestId, true)) return; a.status = AttemptStatus.Succeeded; a.settledAt = uint40(block.timestamp); a.resultHash = resultHash; // The canonical attempt or the first successful candidate of the recovering round. activeAttempt = 0; recoveringRound = 0; headAttempt = id; uint256 v = ++versionCount; _versionAttempt[v] = id; Round storage r = _rounds[a.round]; r.state = RoundState.Built; r.version = uint64(v); bytes calldata u = bytes(uri); uint256 n = u.length; if (n > MAX_CALLBACK_URI_BYTES) u = u[:MAX_CALLBACK_URI_BYTES]; emit RoundBuilt(a.round, id, v, requestId, resultHash, string(u), n); } function onFailure(bytes32 requestId, uint8 status, bytes32 reason, uint16, uint16, bytes calldata) external { uint256 id = _callbackAttempt(requestId); Attempt storage a = _attempts[id]; if (!_live(id, a, requestId, false)) return; // A failed candidate changes nothing else: the round stays open to other candidates. a.status = status == IntakeBinding.REFUSED ? AttemptStatus.Refused : AttemptStatus.Failed; a.settledAt = uint40(block.timestamp); a.failureStatus = status; a.failureReason = reason; emit AttemptFailed(a.round, id, requestId, status, reason); } /// @dev A report settles only a pending canonical attempt or a pending candidate of the recovering /// round. Any other pending attempt (a candidate that lost or whose round was skipped) is closed. function _live(uint256 id, Attempt storage a, bytes32 requestId, bool ok) private returns (bool) { if (a.status == AttemptStatus.Pending) { if (id == activeAttempt || a.round == recoveringRound) return true; a.status = AttemptStatus.Abandoned; a.settledAt = uint40(block.timestamp); } emit StaleCallback(id, requestId, ok); return false; } /// @dev Caller is Intake, the ID is one of ours, and Intake records it as our completed request. function _callbackAttempt(bytes32 requestId) private view returns (uint256 id) { IntakeBinding.requireCallbackCaller(); id = attemptOfRequest[requestId]; if (id == 0) revert UnknownRequest(requestId); IntakeBinding.requireCompletedOwnRequest(requestId); } // ================================================================== reads function round(uint256 roundId) external view returns (Round memory) { return _rounds[roundId]; } /// @notice Unspent principal of this receipt, attributed to its original contributor. /// Contributor-funded sends consume principal in receipt mint order within the round. function unspentContribution(uint256 tokenId) external view returns (uint256) { _requireOwned(tokenId); return creditOf[tokenId].remaining; } /// @notice Unspent, unreclaimed principal available for an Open round's first send. Age does /// not matter. function availableFunding(uint256 roundId) external view returns (uint256) { return _rounds[roundId].state == RoundState.Open ? _roundCredit[roundId] : 0; } function attempt(uint256 attemptId) external view returns (Attempt memory) { if (attemptId == 0 || attemptId > attemptCount) revert UnknownAttempt(attemptId); return _attempts[attemptId]; } /// @notice Receipt (NFT) ids and wishes of a round, in order. function roundWishes(uint256 roundId) public view returns (uint256[] memory tokenIds, string[] memory wishes) { return _wishes(roundId, true); } function _wishes(uint256 roundId, bool archive) private view returns (uint256[] memory tokenIds, string[] memory wishes) { Round storage r = _rounds[roundId]; uint256 count = r.wishCount - (archive ? 0 : _cancelledWishes[roundId]); tokenIds = new uint256[](count); wishes = new string[](count); uint256 j; for (uint256 i; i < r.wishCount; ++i) { uint256 tokenId = r.firstToken + i; if (archive || !creditOf[tokenId].cancelled) { tokenIds[j] = tokenId; wishes[j++] = wishOf(tokenId); } } } /// @notice Immutable record of a version: its round, attempt, Intake request, committed result /// document hash and (once proven) job id. The page's CID is the job's own site record. function version(uint256 v) external view returns (uint256 roundId, uint256 attemptId, bytes32 requestId, bytes32 resultHash, string memory jobId) { if (v == 0 || v > versionCount) revert UnknownVersion(v); attemptId = _versionAttempt[v]; Attempt storage a = _attempts[attemptId]; return (a.round, attemptId, a.requestId, a.resultHash, a.jobId); } /// @notice How the next build names its parent, and that parent if known. function head() external view returns (HeadMode mode, string memory parentJobId) { return _head(); } // ================================================================== internals function _dispatch(uint256 cap, bool topUp) private returns (bool) { uint256 roundId = nextRound; { uint256 n = _rounds[roundId].wishCount; // Retire one completely cancelled batch per call, even while Intake/head are unavailable. // Never walk a backlog or make a refund depend on advancing this cursor. if (n != 0 && n == _cancelledWishes[roundId]) { _retire(roundId); return false; } if (activeAttempt != 0 || n == 0) return false; } // funding-r3: only a sealed batch (its credit reached the quote, or it holds 50 wishes) takes a top-up. if (topUp && roundId >= openRound) return false; (HeadMode mode, string memory parent) = _head(); if (mode > HeadMode.Continue) return false; bool continuation = mode == HeadMode.Continue; (bool ok, uint256 price) = _livePrice(continuation ? IntakeBinding.JOB_CONTINUE : IntakeBinding.JOB_OPEN); if (!ok) return false; uint256 funds = _roundCredit[roundId]; uint256 spend = price; address sponsor; if (price > funds) { if (!topUp) { _retireUnderfunded(roundId); return false; } sponsor = _payShortfall(roundId, price - funds, cap); spend = funds; } else { if (topUp) return false; if (price > cap) revert PriceAboveMax(price, cap); } _dequeue(roundId); _spendCredit(roundId, spend, funds); openPool -= spend; _send(roundId, continuation, parent, true, price, sponsor); return true; } /// @dev funding-r3: an underfunded sealed batch cannot hold the queue for free. Once its newest /// receipt may be refunded, retire it as Skipped; its credit stays refundable. function _retireUnderfunded(uint256 roundId) private { Round storage r = _rounds[roundId]; if (roundId < openRound && block.timestamp >= creditOf[r.firstToken + r.wishCount - 1].refundableAt) { _retire(roundId); } } function _payShortfall(uint256 roundId, uint256 shortfall, uint256 cap) private returns (address) { if (shortfall > cap) revert PriceAboveMax(shortfall, cap); _pull(msg.sender, shortfall); totalSponsored += shortfall; emit ShortfallFunded(roundId, msg.sender, shortfall); return msg.sender; } function _retire(uint256 roundId) private { _rounds[roundId].state = RoundState.Skipped; _dequeue(roundId); emit RoundSkipped(roundId, 0, msg.sender); } function _dequeue(uint256 roundId) private { if (roundId == openRound) _advanceTail(); nextRound = roundId + 1; } function _advanceTail() private { _rounds[++openRound].firstToken = uint64(totalSupply() + 1); } /// @dev In receipt order within one round; refunded receipts hold zero. Surplus never rolls over. /// funding-r3: if the surplus is smaller than the newest receipt's credit, earlier receipts pay in full /// and only the newest keeps change. A larger surplus (the quote fell after sealing) is shared pro /// rata, so no wish of the batch rides on another's payment; the newest nonzero credit takes the dust. function _spendCredit(uint256 roundId, uint256 amount, uint256 funds) private { Round storage r = _rounds[roundId]; uint256 t = r.firstToken; uint256 end = t + r.wishCount; _roundCredit[roundId] = funds - amount; bool share = funds - amount >= creditOf[end - 1].remaining; for (; amount != 0 && t < end; ++t) { Credit storage c = creditOf[t]; uint256 rem = c.remaining; uint256 take = share ? rem * amount / funds : (rem < amount ? rem : amount); // take <= rem and take <= amount <= funds; funds stays the sum of the credits not yet visited. unchecked { funds -= rem; c.remaining = rem - take; amount -= take; } } assert(amount == 0); } function _send( uint256 roundId, bool continuation, string memory parent, bool proven, uint256 price, address sponsor ) private returns (uint256 id) { (, string[] memory wishes) = _wishes(roundId, false); if (wishes.length == 0) revert EmptyRound(roundId); bytes32 action; bytes memory body; if (continuation) { (action, body) = WishOrders.continueFrom(parent, wishes); } else { // Open heads already supply an empty parent. (action, body) = WishOrders.open(wishes); } id = ++attemptCount; Round storage r = _rounds[roundId]; r.attemptCount += 1; r.lastAttempt = uint64(id); r.state = RoundState.Sent; Attempt storage a = _attempts[id]; a.round = uint64(roundId); a.status = AttemptStatus.Pending; a.continuation = continuation; a.parentProven = proven; a.sponsor = sponsor; a.sentAt = uint40(block.timestamp); a.paid = price; a.parentJobId = parent; if (proven) { // Canonical: holds the single active slot and names the head. Candidates hold neither. activeAttempt = id; headAttempt = id; } totalSpent += price; bytes32 requestId = IntakeBinding.submit(action, body, price); a.requestId = requestId; attemptOfRequest[requestId] = id; emit RoundSent(roundId, id, requestId, continuation, parent, price, sponsor); } function _closeActive(uint256 active) private { Attempt storage a = _attempts[active]; if (a.status == AttemptStatus.Pending) { a.status = AttemptStatus.Abandoned; a.settledAt = uint40(block.timestamp); } activeAttempt = 0; } function _requireRecoverable(uint256 active) private view { // liveness-4: Pending, Refused and Failed alike wait a full day from sentAt. uint256 readyAt = uint256(_attempts[active].sentAt) + RECOVERY_DELAY; if (block.timestamp < readyAt) revert NotRecoverableYet(active, readyAt); } /// @dev Derived from headAttempt (canonical builds are serialized); unknown while candidates run, and /// after a refused continuation if any candidate was ever sent. function _head() private view returns (HeadMode mode, string memory parent) { if (recoveringRound != 0) return (HeadMode.Unknown, ""); uint256 last = headAttempt; if (last == 0) return (HeadMode.Open, ""); Attempt storage a = _attempts[last]; if (a.status == AttemptStatus.Succeeded) { if (bytes(a.jobId).length != 0) return (HeadMode.Continue, a.jobId); if (block.timestamp < uint256(a.settledAt) + RECOVERY_DELAY) return (HeadMode.NeedsProof, ""); } if (a.status == AttemptStatus.Refused && a.parentProven) { // Admission refused: no job was created, so the head is what this attempt named. if (!a.continuation) return (HeadMode.Open, ""); // recovery-r3: once any candidate was sent, a job newer than this parent may exist, and the // refusal may be for that reason. Do not spend the pool on the same parent again. if (newestCandidate == 0) return (HeadMode.Continue, a.parentJobId); } return (HeadMode.Unknown, ""); } function _livePrice(bytes32 action) private view returns (bool ok, uint256 price) { if (block.chainid != IntakeBinding.CHAIN_ID) return (false, 0); bytes4 selector = IIntake.priceOf.selector; address intake = IntakeBinding.INTAKE; address asset = IntakeBinding.IMD; // Copy only the one-word quote. Missing code, revert and malformed return data all mean // unavailable, without a return-data allocation or an uncaught ABI decoding failure. assembly ("memory-safe") { let p := mload(0x40) mstore(p, selector) mstore(add(p, 4), action) mstore(add(p, 36), asset) let success := staticcall(gas(), intake, p, 68, p, 32) if and(success, eq(returndatasize(), 32)) { price := mload(p) ok := iszero(iszero(price)) } } } function _requirePrice(bytes32 action) private view returns (uint256 price) { bool ok; (ok, price) = _livePrice(action); if (!ok) revert PriceUnavailable(action); } /// @dev Pulls exactly `amount` from `from`; only ever the calling payer. function _pull(address from, uint256 amount) private { IIMD token = IIMD(IntakeBinding.IMD); uint256 before = _balance(address(this)); if (!token.transferFrom(from, address(this), amount)) revert PullFailed(); if (_balance(address(this)) != before + amount) revert PullFailed(); } function _balance(address account) private view returns (uint256 value) { address token = IntakeBinding.IMD; bytes4 selector = IIMD.balanceOf.selector; assembly ("memory-safe") { let p := mload(0x40) mstore(p, selector) mstore(add(p, 4), account) if iszero(staticcall(gas(), token, p, 36, p, 32)) { returndatacopy(p, 0, returndatasize()) revert(p, returndatasize()) } if lt(returndatasize(), 32) { revert(0, 0) } value := mload(p) } } /// @dev Strict validating JSON scan of the whole document (bounded by MAX_RESULT_DOC_BYTES and /// MAX_JSON_DEPTH). Returns the root object's own "jobId" string. Conservative by design: the root /// value must be an object; delimiters must match by type; strings reject raw control bytes and /// invalid escapes; any root key containing a backslash escape is rejected (so no escaped alias can /// name "jobId"); a duplicate root "jobId" is rejected; the value must be a literal 36-byte lowercase /// UUID string. Nested members are validated but otherwise ignored. Number grammar is checked by /// character class only. Reads past the end yield 0x00, which no rule accepts. function _topLevelJobId(bytes calldata d) private pure returns (string memory jobId) { uint256 pos; uint256 maxDepth = MAX_JSON_DEPTH; assembly ("memory-safe") { function ch(q, e) -> c { if lt(q, e) { c := byte(0, calldataload(q)) } } function skip(q, e) -> r { for { r := q } lt(r, e) { r := add(r, 1) } { if iszero(and(shr(byte(0, calldataload(r)), 0x100002600), 1)) { leave } } } // q at the opening quote; r = index after the closing quote, 0 if invalid function str(q, e) -> r, esc { for { q := add(q, 1) } lt(q, e) { q := add(q, 1) } { // skip 32 plain bytes at a time (none is a quote, backslash or control byte) for {} iszero(gt(add(q, 32), e)) { q := add(q, 32) } { let w := calldataload(q) let x := xor(w, 0x2222222222222222222222222222222222222222222222222222222222222222) let y := xor(w, 0x5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c) if and( or( or(and(sub(x, 0x0101010101010101010101010101010101010101010101010101010101010101), not(x)), and(sub(y, 0x0101010101010101010101010101010101010101010101010101010101010101), not(y))), and(sub(w, 0x2020202020202020202020202020202020202020202020202020202020202020), not(w)) ), 0x8080808080808080808080808080808080808080808080808080808080808080 ) { break } } if iszero(lt(q, e)) { break } let c := byte(0, calldataload(q)) if gt(c, 0x5c) { continue } if eq(c, 0x22) { r := add(q, 1) leave } if lt(c, 0x20) { leave } if eq(c, 0x5c) { esc := 1 q := add(q, 1) c := ch(q, e) switch c case 0x75 { for { let k := 0 } lt(k, 4) { k := add(k, 1) } { q := add(q, 1) if iszero(and(shr(ch(q, e), 0x7e0000007e03ff000000000000), 1)) { leave } } } default { if iszero(and(shr(c, 0x144044100000000000800400000000), 1)) { leave } } } } } // true, false, null or a number; r = index after it, 0 if invalid function scalar(q, e) -> r { let c := ch(q, e) if or(eq(c, 0x74), eq(c, 0x6e)) { let w := shr(224, calldataload(q)) if and(lt(add(q, 3), e), or(eq(w, 0x74727565), eq(w, 0x6e756c6c))) { r := add(q, 4) } leave } if eq(c, 0x66) { if and(lt(add(q, 4), e), eq(shr(216, calldataload(q)), 0x66616c7365)) { r := add(q, 5) } leave } if iszero(and(shr(c, 0x3ff200000000000), 1)) { leave } for { r := add(q, 1) } and(shr(ch(r, e), 0x200000002003ff680000000000), 1) {} { r := add(r, 1) } } // calldata index of the root jobId value's first byte, or 0 if the document is rejected function parse(p, e, maxDepth_) -> result { let q := skip(p, e) if iszero(eq(ch(q, e), 0x7b)) { leave } let found := 0 let depth := 0 let arrays := 0 // bit k set: level k is an array let state := 0 // 0 value, 1 value or close-array, 2 key, 3 key or close-object, 4 comma or close for {} 1 {} { q := skip(q, e) let c := ch(q, e) let inArr := and(shr(depth, arrays), 1) if or( or(and(eq(state, 1), eq(c, 0x5d)), and(eq(state, 3), eq(c, 0x7d))), and(eq(state, 4), or(and(eq(c, 0x5d), inArr), and(eq(c, 0x7d), iszero(inArr)))) ) { q := add(q, 1) state := 4 depth := sub(depth, 1) if iszero(depth) { break } continue } if eq(state, 4) { if iszero(eq(c, 0x2c)) { leave } q := add(q, 1) state := mul(iszero(inArr), 2) continue } if lt(state, 2) { if or(eq(c, 0x7b), eq(c, 0x5b)) { depth := add(depth, 1) if gt(depth, maxDepth_) { leave } switch c case 0x5b { arrays := or(arrays, shl(depth, 1)) state := 1 } default { arrays := and(arrays, not(shl(depth, 1))) state := 3 } q := add(q, 1) continue } state := 4 switch c case 0x22 { let unused q, unused := str(q, e) } default { q := scalar(q, e) } if iszero(q) { leave } continue } // a key if iszero(eq(c, 0x22)) { leave } let r, esc := str(q, e) if iszero(r) { leave } let s := add(q, 1) q := skip(r, e) if iszero(eq(ch(q, e), 0x3a)) { leave } q := add(q, 1) state := 0 if eq(depth, 1) { if esc { leave } // escaped root keys are never trusted if and(eq(sub(r, s), 6), eq(shr(216, calldataload(s)), 0x6a6f624964)) { if found { leave } // duplicate root "jobId" q := skip(q, e) if iszero(and(eq(ch(q, e), 0x22), eq(ch(add(q, 37), e), 0x22))) { leave } found := add(q, 1) q := add(q, 38) state := 4 } } } // root object closed: only whitespace may follow if eq(skip(q, e), e) { result := found } } pos := parse(d.offset, add(d.offset, d.length), maxDepth) if pos { pos := sub(pos, d.offset) } // relative; a jobId value never starts at index 0 } if (pos == 0) revert BadResultDocument(); jobId = string(d[pos:pos + 36]); if (!WishOrders.isJobId(bytes(jobId))) revert BadResultDocument(); } }