Verified contractPartialMIT
WorkOrders
Address0x730cb6c845d896e33283d3a4ed8967f8baa778d2
- Balance
0 ETH
- Transactions
7
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,184,581
- Creation transaction
- 0xfb28bef9c4…1bfff7bf9c
15 files
- src/desk/WorkOrders.solmain52.12 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol13.31 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol2.85 KB
- lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol5.08 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- src/desk/OrderHeader.sol2.66 KB
- src/desk/SpecText.sol3.45 KB
- src/interfaces/IPayroll.sol2.25 KB
- src/interfaces/IWorkOrders.sol5.41 KB
- src/interfaces/IWorkOrdersRunner.sol29.41 KB
- src/interfaces/IWorkProof.sol2.75 KB
src/desk/WorkOrders.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {IPayroll} from "../interfaces/IPayroll.sol";
import {IWorkEmployer, IWorkOrders} from "../interfaces/IWorkOrders.sol";
import {IWorkOrdersRunner} from "../interfaces/IWorkOrdersRunner.sol";
import {IWorkProof} from "../interfaces/IWorkProof.sol";
import {OrderHeader} from "./OrderHeader.sol";
import {SpecText} from "./SpecText.sol";
/// @title WorkOrders, the hire desk
/// @notice A job board where the employer can be a contract. An employer escrows IMD against a
/// pinned job text (the spec). A runner posts a bond, opens the job with IdentityMD's swarm with the
/// order's header in front of the spec, and registers the job id. The escrow pays out in one of
/// three ways only:
///
/// - Proven: anyone submits the job's work record and WorkProof confirms it is the receipt the
/// IdentityMD WorkRegistry holds for that job, that it ended "completed", and that its objective
/// is exactly this claim's header followed by the order's spec.
/// - Claimed (only if the employer opted in with `FLAG_ALLOW_CLAIMED`): the runner states that the
/// job was delivered, a 24 hour challenge window passes with no challenge, and the order is paid
/// as delivered but marked unproven until someone later stamps it with the receipt.
/// - Arbitrated (only on such an order, and only if the employer named an arbiter): a delivery
/// claim was challenged and the arbiter decided for the runner. Also marked unproven.
///
/// Everything else gives the escrow back to the employer.
///
/// @dev There is no owner, no setter and no pause; the three addresses given at construction never
/// change. What the desk trusts, and how far:
///
/// - WorkProof, and through it IdentityMD's WorkRegistry, decide what a record says. Whoever
/// controls the registry's writer can record a hash for a record of its own making, and so be
/// paid for any order it takes: every escrow a runner can claim is exposed to that key. It is
/// the same party that runs the swarm and already decides what the work was. If WorkProof or
/// the registry stop answering, nothing can be proven and every order ends by timeout or refund.
/// - Payroll receives the fee and the tip. Each of its two calls is offered `PAYROLL_GAS`;
/// whatever it does not take, for any reason, is sent to it by plain transfer. A settlement
/// never waits for it.
/// - The employer's callback and the condition target are untrusted. The first runs last, with a
/// fixed gas allowance, after everything is final. The second is a gas-capped static call that is
/// consulted only until the condition has once been seen true.
///
/// What a runner should check before taking an order, because the desk cannot: that `kindHash` is
/// the kind the swarm writes for the template it will use (a work record's `kind` is the name of
/// the job's template); and, for the claimed path, who the order's arbiter is (an arbiter decides
/// a disputed claim before a receipt does).
///
/// What an employer accepts by setting `FLAG_ALLOW_CLAIMED`, stated plainly:
///
/// - Until a receipt is matched, the job id and the record hash of a delivery claim are the
/// runner's word. An untrue claim that nobody challenges within 24 hours is paid.
/// - A challenge costs the challenger no IMD when nothing decides the dispute: with no receipt
/// and no arbiter decision by the delivery deadline, the employer is refunded and the
/// challenger's bond returned. So while receipts are late, a challenger can keep a true claim
/// from being paid at no cost to itself but gas and the use of its bond until then.
/// - A runner whose challenged claim is not upheld never gets off more cheaply than by `release`:
/// whoever the challenger was, its own second address included, the employer receives at least
/// the release share of the runner's bond.
///
/// An order's arbiter is the answer for an employer who wants neither of the first two. Orders
/// without the flag are untouched by any of this: they pay on a matched receipt or not at all.
///
/// What a challenger accepts by posting its bond: the bond is held until a receipt, the arbiter or
/// the delivery deadline ends the dispute, and that deadline can be 90 days after the job was
/// registered; a dispute that nothing decides returns the bond and pays nothing for the wait; and
/// an order's arbiter decides either way, with no evidence required. An employer may be its own
/// runner and its own arbiter. So a challenger looks at an order's employer, arbiter, bond and
/// deadline first, and defends the orders it has a reason to defend.
///
/// The surface is declared in two interfaces: `IWorkOrders` (what an employer contract compiles
/// against) and `IWorkOrdersRunner` (what a runner or a keeper uses, with the order and claim
/// records, every event and every error). This contract implements both and adds nothing public
/// beyond them.
contract WorkOrders is IWorkOrdersRunner, ReentrancyGuardTransient {
using SafeERC20 for IERC20;
/// @inheritdoc IWorkOrders
uint8 public constant FLAG_ALLOW_CLAIMED = 1;
/// @inheritdoc IWorkOrders
uint8 public constant FLAG_CALLBACK = 2;
/// @inheritdoc IWorkOrders
uint8 public constant FLAG_COND_ARG = 4;
/// @inheritdoc IWorkOrders
uint96 public constant MIN_BOND = 0.25e18;
/// @inheritdoc IWorkOrders
uint32 public constant MIN_DELIVERY = 3 days;
/// @notice The longest delivery time an order may ask for. One runner's bond can keep an
/// order's escrow out of reach for the whole delivery time, so a mistaken value must not be
/// able to make that years.
uint32 public constant MAX_DELIVERY = 90 days;
/// @notice The fee, in basis points of the fixed price, sent to Payroll at delivery.
uint256 public constant FEE_BPS = 500;
/// @notice The tip, in basis points of the fixed price, sent to Payroll for the agents that worked.
uint256 public constant TIP_BPS = 500;
/// @notice The release share: the part of the bond, in basis points, a runner loses to the
/// employer when it releases an order, and at least loses when a challenged claim is not upheld.
uint256 public constant RELEASE_BPS = 1000;
/// @notice How long a runner may hold an order without registering a job.
uint256 public constant CLAIM_WINDOW = 1 hours;
/// @notice How long a delivery claim can be challenged.
uint256 public constant CHALLENGE_WINDOW = 24 hours;
/// @notice The least time a challenged delivery claim has, before the delivery deadline, for a
/// receipt or the arbiter to decide it. `claimDelivered` is refused when it would be less.
uint256 public constant DISPUTE_WINDOW = 24 hours;
/// @notice Gas given to the employer's `onWorkDelivered`.
/// @dev Enough to record a delivery, not to open a new order (about 260,000 gas): an employer
/// contract that hires again does so in a call of its own.
uint256 public constant CALLBACK_GAS = 150_000;
/// @notice Gas given to an order's condition call.
uint256 public constant CONDITION_GAS = 100_000;
/// @notice Gas given to each of the two Payroll calls made at delivery.
uint256 public constant PAYROLL_GAS = 1_000_000;
/// @notice Length of the order header at the start of a job's objective.
uint256 public constant HEADER_LEN = OrderHeader.LENGTH;
uint256 private constant BPS = 10_000;
/// @dev Room for the few operations between a gas check and the call it protects.
uint256 private constant GAS_SLACK = 10_000;
bytes32 private constant COMPLETED = keccak256("completed");
/// @inheritdoc IWorkOrders
address public immutable IMD;
/// @notice The contract that checks work records against the IdentityMD WorkRegistry.
address public immutable WORK_PROOF;
/// @notice Where fees and tips go.
address public immutable PAYROLL;
/// @inheritdoc IWorkOrders
uint256 public orderCount;
/// @notice The order a job's receipt was matched for, or zero.
/// @dev Written only when a receipt is matched (`settle`, `stamp`), never when a job id is
/// registered or merely claimed as delivered, so registering somebody else's job id cannot
/// stand in the way of that job's own order. On the claimed path a job id is the runner's word
/// until then: two unchallenged claims that name the same job id are both paid.
mapping(bytes16 jobId => uint256 orderId) public orderOfJob;
/// @notice True once a runner has released an order; it may not take that order again.
mapping(uint256 orderId => mapping(address runner => bool)) public barred;
mapping(uint256 orderId => Order) private _orders;
mapping(uint256 orderId => Claim) private _claims;
/// @dev Makes no call and checks no code, so it can run on an empty chain; it only refuses a
/// zero address. An address that is wrong in another way shows on first use: without a real IMD
/// no order can be funded, and so no money can ever depend on the other two.
/// @param imd The IMD token.
/// @param workProof The WorkProof contract of the same launch.
/// @param payroll The Payroll contract of the earlier launch.
constructor(address imd, address workProof, address payroll) {
if (imd == address(0) || workProof == address(0) || payroll == address(0)) revert ZeroAddress();
IMD = imd;
WORK_PROOF = workProof;
PAYROLL = payroll;
}
// ------------------------------------------------------------------------------------------
// Employer
// ------------------------------------------------------------------------------------------
/// @inheritdoc IWorkOrders
/// @dev Anyone may call. Reverts when the spec breaks the character rules, when the pay range,
/// delivery time, bond, expiry, flags or condition fields are out of range, or when the caller
/// has not approved `p.maxPay` IMD. A conditional order starts closed: see `trigger`.
function createOrder(OrderParams calldata p, bytes calldata spec) external nonReentrant returns (uint256 id) {
uint256 at = SpecText.firstBad(spec);
if (at != SpecText.NONE) revert SpecInvalid(at);
if (p.maxPay == 0 || p.minPay > p.maxPay) revert PayRange();
if (p.deliverySecs < MIN_DELIVERY) revert DeliveryTooShort();
if (p.deliverySecs > MAX_DELIVERY) revert DeliveryTooLong();
if (p.bond < MIN_BOND) revert BondTooLow();
if (p.expiresAt <= block.timestamp) revert Expired();
bool conditional = p.condTarget != address(0);
if (p.flags > 7 || (!conditional && p.flags & FLAG_COND_ARG != 0)) revert BadFlags();
if (p.condCmp > 6 || conditional == (p.condCmp == 0)) revert BadCondition();
id = ++orderCount;
bytes32 specHash = keccak256(spec);
_orders[id] = Order({
employer: msg.sender,
expiresAt: p.expiresAt,
rampFrom: conditional ? 0 : _timestamp(),
state: State.Open,
flags: p.flags,
kindHash: p.kindHash,
specHash: specHash,
minPay: p.minPay,
maxPay: p.maxPay,
rampSecs: p.rampSecs,
deliverySecs: p.deliverySecs,
runnerOnly: p.runnerOnly,
bond: p.bond,
arbiter: p.arbiter,
escrow: p.maxPay,
condTarget: p.condTarget,
condSelector: p.condSelector,
condCmp: p.condCmp,
condMet: !conditional,
proven: false,
notified: false,
seq: 0,
condArg: p.condArg,
condThreshold: p.condThreshold,
spent: 0,
returned: 0
});
emit OrderOpened(id, msg.sender, p.kindHash, specHash, p, spec);
IERC20(IMD).safeTransferFrom(msg.sender, address(this), p.maxPay);
}
/// @inheritdoc IWorkOrders
/// @dev Only the employer, and only while the order is open. Once a runner holds the order the
/// employer can no longer withdraw it; if the claim ends without a delivery it becomes open again.
function cancel(uint256 id) external nonReentrant {
Order storage o = _orders[id];
if (o.state != State.Open) revert BadState();
if (msg.sender != o.employer) revert NotEmployer();
uint256 escrow = o.escrow;
o.escrow = 0;
o.state = State.Cancelled;
_credit(o, escrow);
emit Cancelled(id, escrow);
_send(msg.sender, escrow);
}
/// @inheritdoc IWorkOrders
/// @dev Reverts `TooEarly` before `expiresAt`. An order somebody holds is never refunded here;
/// it is refunded when its claim ends after the expiry.
function refund(uint256 id) external nonReentrant {
Order storage o = _orders[id];
if (o.state != State.Open) revert BadState();
if (block.timestamp < o.expiresAt) revert TooEarly();
_send(o.employer, _close(id, o, true));
}
// ------------------------------------------------------------------------------------------
// Condition: WHEN a view call crosses a line, THEN hire
// ------------------------------------------------------------------------------------------
/// @notice Records that a conditional order's condition holds now, which opens the order to
/// runners for good and starts its price ramp. Anyone may call.
/// @dev Reverts `BadState` when the order is not open, has no condition, or is already
/// triggered; `ConditionNotMet` when the condition call fails, returns fewer than 32 bytes or
/// compares false; `GasShort` when too little gas is left to offer the target its whole
/// `CONDITION_GAS`, so that the caller cannot choose how much gas the target answers on.
///
/// One true reading is enough and the condition is never consulted again. An employer should
/// therefore not point a condition at something a caller can make true for the length of one
/// transaction (a spot balance, a pool price): whoever can do that can open the order.
function trigger(uint256 id) external nonReentrant {
Order storage o = _orders[id];
if (o.state != State.Open || o.condMet) revert BadState();
_latch(id, o);
}
// ------------------------------------------------------------------------------------------
// Runner
// ------------------------------------------------------------------------------------------
/// @notice Takes an open order: posts the order's bond, fixes the price at what `priceNow`
/// shows, and starts the one hour in which a job must be registered.
/// @dev Reverts when the order is not open (`BadState`), has expired (`Expired`), is reserved
/// for another runner (`NotRunner`), was released by the caller before (`Barred`), or has a
/// condition that has never been seen true and is not true now (`ConditionNotMet`, or
/// `GasShort` as in `trigger`). `BooksFull` cannot happen with amounts of IMD that exist: see
/// `accountOf`.
/// @return ticket The value to put in the header of the swarm job (see `headerOf`).
function claim(uint256 id) external nonReentrant returns (bytes32 ticket) {
Order storage o = _orders[id];
if (o.state != State.Open) revert BadState();
if (block.timestamp >= o.expiresAt) revert Expired();
address only = o.runnerOnly;
if (only != address(0) && only != msg.sender) revert NotRunner();
if (barred[id][msg.sender]) revert Barred();
if (!o.condMet) _latch(id, o);
uint96 price = _price(o);
uint256 bond = o.bond;
// What keeps `returned` exact: see `_credit`.
if (uint256(o.returned) + o.escrow + bond > type(uint96).max) revert BooksFull();
uint256 seq = ++o.seq;
o.state = State.Claimed;
_claims[id] = Claim({
runner: msg.sender,
claimedAt: _timestamp(),
registeredAt: 0,
price: price,
jobId: 0,
challenger: address(0),
assertedAt: 0,
recordHash: 0
});
ticket = OrderHeader.ticket(block.chainid, address(this), id, seq, msg.sender);
emit Claimed(id, msg.sender, seq, price, bond, ticket);
IERC20(IMD).safeTransferFrom(msg.sender, address(this), bond);
}
/// @notice The runner gives the order back before registering a job. It gets 90% of its bond,
/// the employer gets 10%, and the runner may not take this order again.
/// @dev Only inside the claim window (`TooLate` afterwards). Past the window the only ways on
/// are `register` and `evict`, so a runner that overstays cannot wait for an eviction to appear
/// and then swap the whole bond for a tenth of it.
function release(uint256 id) external nonReentrant {
Order storage o = _orders[id];
Claim storage c = _claims[id];
if (o.state != State.Claimed) revert BadState();
if (msg.sender != c.runner) revert NotRunner();
if (block.timestamp >= c.claimedAt + CLAIM_WINDOW) revert TooLate();
barred[id][msg.sender] = true;
uint256 bond = o.bond;
uint256 cut = _releaseCut(bond);
_endClaim(id, o, c, End.Released, bond - cut, cut, 0);
}
/// @notice Removes a runner that registered no job within the claim window. Anyone may call.
/// The whole bond goes to the employer.
/// @dev Lazy: until somebody calls this, the runner can still register.
function evict(uint256 id) external nonReentrant {
Order storage o = _orders[id];
Claim storage c = _claims[id];
if (o.state != State.Claimed) revert BadState();
if (block.timestamp < c.claimedAt + CLAIM_WINDOW) revert TooEarly();
_endClaim(id, o, c, End.Evicted, 0, o.bond, 0);
}
/// @notice The runner records the swarm job it opened for the order. It may call again, before
/// the order is settled, to replace the job with a retry.
/// @dev The delivery time runs from the first registration and a retry does not restart it.
/// Registering a job id reserves nothing: a job is tied to an order only when its receipt is
/// matched, so a runner cannot be blocked by somebody registering its job id elsewhere. A job
/// whose receipt already settled another order is refused (`JobUsed`): it could never settle
/// this one.
function register(uint256 id, bytes16 jobId) external nonReentrant {
Order storage o = _orders[id];
Claim storage c = _claims[id];
State s = o.state;
if (s != State.Claimed && s != State.Registered) revert BadState();
if (msg.sender != c.runner) revert NotRunner();
if (jobId == 0) revert ZeroJob();
if (orderOfJob[jobId] != 0) revert JobUsed();
if (s == State.Claimed) {
o.state = State.Registered;
c.registeredAt = _timestamp();
}
c.jobId = jobId;
emit Registered(id, jobId);
}
// ------------------------------------------------------------------------------------------
// Proven path
// ------------------------------------------------------------------------------------------
/// @notice Pays the order out against the work record of its registered job. Anyone may call.
/// @dev WorkProof must confirm the record is the WorkRegistry's receipt for the job. The record
/// must be "completed", of the order's kind, and its objective must be this claim's header
/// followed by the order's spec. The job must not have settled another order. Nothing else
/// counts: after a delivery claim, challenged or not, any receipt that passes these checks
/// pays the runner, whether or not its hash is the one the runner named (a job can be given a
/// newer receipt, and the registry then answers with that one).
///
/// Out of the fixed price: 5% fee and 5% tip to Payroll (each rounded up to the next wei), the
/// rest to the runner together with its bond (and the challenger's bond after a dispute). The
/// escrow above the price returns to the employer. The tip is passed on with the agent ids
/// WorkProof read from the record; a job's later receipt can carry none, and the tip of a
/// settlement made after such a receipt goes to Payroll's seat pool instead.
///
/// Gas: `GasShort` unless `PAYROLL_GAS` can be handed to each Payroll call, and, when the
/// employer asked for a callback, `CALLBACK_GAS` to its `onWorkDelivered`, which is called
/// last. So the caller cannot make either fail by underfunding it. Gas that is not used is
/// returned as usual.
///
/// Timeouts are lazy: until somebody calls `timeout`, a late receipt still settles here.
/// @param record The work record as IdentityMD serves it, byte for byte (the served file has no
/// trailing newline). Ignored when `chunks` is not empty.
/// @param chunks For a record too large for one transaction: data contracts holding it in
/// order (see `IWorkProof.proveChunks`).
function settle(uint256 id, bytes calldata record, address[] calldata chunks) external {
_settle(id, record, chunks);
_notify(id);
}
/// @notice Ends a claim with a receipt of its registered job that does not settle the order.
/// @dev WorkProof must confirm the record is the WorkRegistry's receipt for the job, as in
/// `settle`. What happens to the runner's bond depends on what the receipt shows and on where
/// the claim stands.
///
/// While the job is only registered (no delivery was claimed):
///
/// - This claim's objective, but the job did not end "completed": the swarm failed a job the
/// runner opened correctly. Only the runner may report this (it decides whether to give up
/// or to register a retry, and a job's first receipt need not be its last), and it gets its
/// whole bond back. It already lost the swarm's fee; taking its bond for the swarm's failure
/// would make honest runners avoid the desk.
/// - This claim's objective and "completed", but under another kind than the order's: this job
/// can never settle the order. Anyone may report it, so the order is free again as soon as
/// the receipt exists. The bond goes back to the runner, because the kind is written by the
/// swarm from the job's template and the desk cannot tell a runner's wrong template from a
/// kind the swarm renamed. A runner that picks a wrong template on purpose pays the swarm's
/// fee each time and holds the order only until the receipt lands.
/// - Any other objective, one too short to hold a header included: the runner registered a
/// job that is not this claim's. Anyone may report it and the whole bond goes to the
/// employer, as in `timeout`, only sooner.
///
/// After the runner claimed delivery, any receipt of the registered job that does not settle
/// the order contradicts the claim, and anyone may report it:
///
/// - Unchallenged: the whole bond goes to the employer.
/// - Challenged: the employer gets the release share of the runner's bond and the challenger
/// gets the rest together with its own bond. The employer's share is what keeps a runner
/// from saving its bond by challenging its own claim from a second address.
///
/// A receipt that settles the order is never a failure, whatever hash the runner named
/// (`NotFailed`). In every case the order becomes open again, or is refunded if it has expired.
///
/// One kind of receipt cannot be used here: a record WorkProof cannot read at all (not a
/// canonical work record of the pinned schema) proves nothing either way, and a claim whose
/// job has such a record ends by `timeout`.
function reportFailed(uint256 id, bytes calldata record, address[] calldata chunks) external nonReentrant {
Order storage o = _orders[id];
Claim storage c = _claims[id];
State s = o.state;
if (s < State.Registered || s > State.Disputed) revert BadState();
bytes16 jobId = c.jobId;
IWorkProof.Proof memory proof = _prove(jobId, record, chunks, true);
bool sameObjective = proof.headHash == _headHash(id, o, c) && proof.specHash == o.specHash;
bool completed = proof.stateHash == COMPLETED;
if (sameObjective && completed && proof.kindHash == o.kindHash) revert NotFailed();
emit Failed(id, jobId, proof.recordHash);
uint256 bond = o.bond;
if (s == State.Disputed) {
_refute(id, o, c);
} else if (s == State.Asserted) {
_endClaim(id, o, c, End.Refuted, 0, bond, 0);
} else if (sameObjective) {
if (!completed && msg.sender != c.runner) revert NotRunner();
_endClaim(id, o, c, End.SwarmFailed, bond, 0, 0);
} else {
_endClaim(id, o, c, End.WrongJob, 0, bond, 0);
}
}
/// @notice Ends a claim whose delivery time has passed. Anyone may call.
/// @dev A registered job with no settlement: the bond goes to the employer and the order becomes
/// open again, or is refunded if it has expired.
///
/// A challenged delivery claim that neither a receipt nor the arbiter decided: the employer is
/// refunded for good, the challenger gets its bond back, and the runner is treated as if it
/// had released the order: the release share of its bond goes to the employer and the rest
/// back to it. So claiming delivery and having a second address challenge is never cheaper
/// than releasing.
///
/// An unchallenged delivery claim is not touched by this: it can only be paid (`finalize`,
/// `settle`) or refuted by a receipt (`reportFailed`).
function timeout(uint256 id) external nonReentrant {
Order storage o = _orders[id];
Claim storage c = _claims[id];
State s = o.state;
if (s != State.Registered && s != State.Disputed) revert BadState();
if (block.timestamp < uint256(c.registeredAt) + o.deliverySecs) revert TooEarly();
uint256 bond = o.bond;
if (s == State.Registered) {
_endClaim(id, o, c, End.TimedOut, 0, bond, 0);
} else {
uint256 cut = _releaseCut(bond);
_endClaim(id, o, c, End.DisputeExpired, bond - cut, cut, bond);
}
}
// ------------------------------------------------------------------------------------------
// Claimed path (only for orders with FLAG_ALLOW_CLAIMED)
// ------------------------------------------------------------------------------------------
/// @notice The runner states that its registered job was delivered as the record with this
/// hash, and opens the 24 hour challenge window.
/// @dev Only the runner, only once per claim, and only on orders whose employer allowed it.
/// Reverts `TooLate` unless the challenge window and, after it, the `DISPUTE_WINDOW` both end
/// by the delivery deadline: the deadline bounds this path too, and a claim that is challenged
/// in the last second of its window still leaves a receipt or the arbiter a day to decide it.
///
/// The job id and the hash are the runner's word and nothing more until a receipt is matched.
/// The hash is there so that a watcher can compare it with the records IdentityMD's API lists
/// for the job (the API lists a record's hash even while its on-chain receipt is queued). It
/// plays no part in what a receipt later decides. What protects the employer on this path is
/// the challenge window, not this function.
function claimDelivered(uint256 id, bytes32 recordHash) external nonReentrant {
Order storage o = _orders[id];
Claim storage c = _claims[id];
if (o.state != State.Registered) revert BadState();
if (msg.sender != c.runner) revert NotRunner();
if (o.flags & FLAG_ALLOW_CLAIMED == 0) revert ClaimedPathOff();
if (recordHash == 0) revert ZeroHash();
uint256 until = block.timestamp + CHALLENGE_WINDOW;
if (until + DISPUTE_WINDOW > uint256(c.registeredAt) + o.deliverySecs) revert TooLate();
o.state = State.Asserted;
c.assertedAt = _timestamp();
c.recordHash = recordHash;
emit DeliveryClaimed(id, c.jobId, recordHash, until);
}
/// @notice Disputes a delivery claim by posting a bond equal to the runner's. Anyone may call,
/// once per claim, inside the challenge window.
/// @dev From here only a receipt, the order's arbiter or the delivery deadline ends the claim:
///
/// - A receipt that settles the order (`settle`), or the arbiter deciding for the runner: the
/// runner is paid and takes the challenger's bond.
/// - A receipt of the registered job that does not settle the order (`reportFailed`), or the
/// arbiter deciding against the runner: the challenger gets its bond back together with the
/// runner's, less the release share, which goes to the employer.
/// - Neither by the delivery deadline (`timeout`): the challenger gets its bond back and
/// nothing more.
///
/// A record hash that differs from the one the runner named is not by itself a reason to
/// challenge: a job can have more than one record, and any receipt that settles the order pays.
///
/// The bond stays in the desk until one of the three happens: at the longest until the
/// delivery deadline (`registeredAt + deliverySecs`, up to 90 days after the job was
/// registered). A claim that names a job with no receipt, on an order with no arbiter, cannot
/// be decided before then. The first challenge to be mined is the only one: a second caller's
/// transaction reverts `BadState` and costs it gas alone.
function challenge(uint256 id) external nonReentrant {
Order storage o = _orders[id];
Claim storage c = _claims[id];
if (o.state != State.Asserted) revert BadState();
if (block.timestamp >= c.assertedAt + CHALLENGE_WINDOW) revert TooLate();
o.state = State.Disputed;
c.challenger = msg.sender;
uint256 bond = o.bond;
emit Challenged(id, msg.sender, bond);
IERC20(IMD).safeTransferFrom(msg.sender, address(this), bond);
}
/// @notice Pays out a delivery claim nobody challenged in time. Anyone may call.
/// @dev The order is marked unproven and the tip goes to Payroll with no agent list. The
/// employer's callback, if any, receives the record hash the runner named. `TooEarly` inside
/// the challenge window; `GasShort` as in `settle`. This is so even when the job's receipt has
/// landed by then: whoever wants the tip to name the agents that worked calls `settle` with
/// the record instead, which pays the same amounts.
function finalize(uint256 id) external {
_finalize(id);
_notify(id);
}
/// @notice The order's arbiter decides a disputed claim. Lazy like a late receipt: it can
/// still decide after the delivery deadline, until somebody calls `timeout`.
/// @param delivered True pays the runner as delivered (unproven) and gives it the challenger's
/// bond. False ends the claim as a receipt against the runner would (see `reportFailed`): the
/// employer gets the release share of the runner's bond, the challenger the rest with its own,
/// and the order becomes open again, or is refunded if it has expired.
function resolve(uint256 id, bool delivered) external {
_resolve(id, delivered);
if (delivered) _notify(id);
}
/// @notice Tries the employer's `onWorkDelivered` again for a delivered order whose callback
/// failed. Anyone may call. No money moves.
/// @dev Reverts `BadState` unless the order is delivered, asked for a callback, and has not
/// had one go through yet; `GasShort` as in `settle`. It cannot be called from inside another
/// call to the desk (from Payroll during a settlement, say): the callback is only ever made
/// once everything else is done.
function redeliver(uint256 id) external {
if (_reentrancyGuardEntered()) revert ReentrancyGuardReentrantCall();
Order storage o = _orders[id];
if (o.state != State.Delivered || o.notified || o.flags & FLAG_CALLBACK == 0) revert BadState();
_notify(id);
if (o.notified) emit Redelivered(id);
}
/// @notice Marks an order that was paid on a claim as proven, once its receipt exists. Anyone
/// may call. No money moves.
/// @dev The same checks as `settle`: any receipt of the registered job that passes them will
/// do, whatever hash the runner named. The order's record hash becomes the receipt's.
function stamp(uint256 id, bytes calldata record, address[] calldata chunks) external nonReentrant {
Order storage o = _orders[id];
Claim storage c = _claims[id];
if (o.state != State.Delivered || o.proven) revert BadState();
bytes16 jobId = c.jobId;
IWorkProof.Proof memory proof = _prove(jobId, record, chunks, false);
_requireSettles(id, o, c, proof);
orderOfJob[jobId] = id;
o.proven = true;
c.recordHash = proof.recordHash;
emit Proven(id, jobId, proof.recordHash);
}
// ------------------------------------------------------------------------------------------
// Views
// ------------------------------------------------------------------------------------------
/// @inheritdoc IWorkOrders
function stateOf(uint256 id) external view returns (State) {
return _orders[id].state;
}
/// @inheritdoc IWorkOrders
/// @dev `returned` is exact: it is the sum of every transfer the desk has made to the employer
/// for this order as its employer (the escrow at cancel or refund, the unused escrow at
/// delivery, and every forfeited bond or share of a bond). It never saturates and is never
/// estimated; `claim` refuses an order (`BooksFull`) before the figure could pass the 96 bits
/// it is reported in, which takes more than 79 billion IMD. Money the desk pays the same
/// address in another role (as the order's runner, or as a challenger) is not counted.
function accountOf(uint256 id)
external
view
returns (State state, address employer, uint96 escrow, uint96 spent, uint96 returned)
{
Order storage o = _orders[id];
return (o.state, o.employer, o.escrow, o.spent, o.returned);
}
/// @notice Everything stored about an order. The spec text itself is in its `OrderOpened` event.
function orderOf(uint256 id) external view returns (Order memory) {
return _orders[id];
}
/// @notice The order's current claim. After a claim ended without delivery this still shows
/// that last claim, until the next runner takes the order.
function claimOf(uint256 id) external view returns (Claim memory) {
return _claims[id];
}
/// @notice What a runner claiming now would be paid in total (fee and tip included): `minPay`
/// rising in a straight line to `maxPay` over `rampSecs` of time the order has spent open,
/// counted from creation, or from the trigger for a conditional order (one not yet triggered
/// shows the price at the start of its ramp).
/// @dev While a runner holds the order, and once it is delivered, this is the price that
/// runner's claim fixed. The ramp stands still while the order is held: when a claim ends
/// without delivery the price goes on from where that claim found it, so holding an order
/// cannot be used to push its price up. Zero for an unknown order.
function priceNow(uint256 id) external view returns (uint96) {
Order storage o = _orders[id];
State s = o.state;
return s >= State.Claimed && s <= State.Delivered ? _claims[id].price : _price(o);
}
/// @notice The ticket of the order's current (or last) claim.
function ticketOf(uint256 id) public view returns (bytes32) {
return OrderHeader.ticket(block.chainid, address(this), id, _orders[id].seq, _claims[id].runner);
}
/// @notice The 85 bytes the runner must put at the very start of the swarm job's objective,
/// directly followed by the spec.
/// @dev Reverts `BadState` unless a runner holds the order or the order was delivered.
function headerOf(uint256 id) external view returns (bytes memory) {
State s = _orders[id].state;
if (s < State.Claimed || s > State.Delivered) revert BadState();
return OrderHeader.build(ticketOf(id));
}
/// @notice The status of an order's condition.
/// @dev A reading taken here is only as good as the gas the call was given: the target is
/// offered at most `CONDITION_GAS`, and less when the caller has less to pass on. `trigger`
/// and `claim` insist on the whole allowance; this view cannot.
/// @return met True when the order can be taken as far as its condition goes: it has none, or
/// it was seen true once.
/// @return holdsNow Whether the condition call compares true at this moment (true for an order
/// with no condition).
/// @return value The word the condition call returned, or zero if it failed.
function conditionOf(uint256 id) external view returns (bool met, bool holdsNow, uint256 value) {
Order storage o = _orders[id];
met = o.condMet;
if (o.condTarget == address(0)) return (met, met, 0);
(holdsNow, value) = _condition(o);
}
// ------------------------------------------------------------------------------------------
// Internals
// ------------------------------------------------------------------------------------------
function _settle(uint256 id, bytes calldata record, address[] calldata chunks) private nonReentrant {
Order storage o = _orders[id];
Claim storage c = _claims[id];
State s = o.state;
if (s < State.Registered || s > State.Disputed) revert BadState();
bytes16 jobId = c.jobId;
IWorkProof.Proof memory proof = _prove(jobId, record, chunks, false);
_requireSettles(id, o, c, proof);
orderOfJob[jobId] = id;
_deliver(id, o, c, proof.recordHash, true, proof.agentIds);
}
function _finalize(uint256 id) private nonReentrant {
Order storage o = _orders[id];
Claim storage c = _claims[id];
if (o.state != State.Asserted) revert BadState();
if (block.timestamp < c.assertedAt + CHALLENGE_WINDOW) revert TooEarly();
_deliver(id, o, c, c.recordHash, false, new uint256[](0));
}
function _resolve(uint256 id, bool delivered) private nonReentrant {
Order storage o = _orders[id];
Claim storage c = _claims[id];
if (o.state != State.Disputed) revert BadState();
if (msg.sender != o.arbiter) revert NotArbiter();
emit Resolved(id, msg.sender, delivered);
if (delivered) _deliver(id, o, c, c.recordHash, false, new uint256[](0));
else _refute(id, o, c);
}
/// @dev Asks WorkProof what the registered job's record says, with the header split off. It
/// reverts unless the record is the registry's receipt for `jobId`, and its revert is passed on
/// unchanged. With `anyObjective`, a record whose objective is shorter than a header (WorkProof
/// answers `HeadTooLong`) is read once more with nothing split off: it is proven like any
/// other, and its `headHash` is then the hash of nothing, which is no claim's header.
function _prove(bytes16 jobId, bytes calldata record, address[] calldata chunks, bool anyObjective)
private
view
returns (IWorkProof.Proof memory)
{
(bool ok, bytes memory ret) = _askProof(jobId, record, chunks, HEADER_LEN);
// Only the first four bytes of the revert data are wanted: the error's selector.
// forge-lint: disable-next-line(unsafe-typecast)
if (!ok && anyObjective && bytes4(ret) == IWorkProof.HeadTooLong.selector) {
(ok, ret) = _askProof(jobId, record, chunks, 0);
}
if (!ok) {
assembly ("memory-safe") {
revert(add(ret, 0x20), mload(ret))
}
}
return abi.decode(ret, (IWorkProof.Proof));
}
function _askProof(bytes16 jobId, bytes calldata record, address[] calldata chunks, uint256 headLen)
private
view
returns (bool ok, bytes memory ret)
{
(ok, ret) = WORK_PROOF.staticcall(
chunks.length == 0
? abi.encodeCall(IWorkProof.prove, (jobId, record, headLen))
: abi.encodeCall(IWorkProof.proveChunks, (jobId, chunks, headLen))
);
}
function _headHash(uint256 id, Order storage o, Claim storage c) private view returns (bytes32) {
return OrderHeader.hash(OrderHeader.ticket(block.chainid, address(this), id, o.seq, c.runner));
}
/// @dev The conditions under which a receipt pays this claim.
function _requireSettles(uint256 id, Order storage o, Claim storage c, IWorkProof.Proof memory proof) private view {
if (orderOfJob[c.jobId] != 0) revert JobUsed();
if (proof.stateHash != COMPLETED) revert NotCompleted();
if (proof.kindHash != o.kindHash) revert WrongKind();
if (proof.headHash != _headHash(id, o, c)) revert WrongHeader();
if (proof.specHash != o.specHash) revert WrongSpec();
}
/// @dev Pays a delivered order. State first, then the transfers, then Payroll.
function _deliver(
uint256 id,
Order storage o,
Claim storage c,
bytes32 recordHash,
bool proven,
uint256[] memory agentIds
) private {
uint96 fixedPrice = c.price;
uint256 price = fixedPrice;
// Rounded up, so the fee side never loses a fraction; the runner gets what is left.
uint256 fee = (price * FEE_BPS + BPS - 1) / BPS;
uint256 tip = (price * TIP_BPS + BPS - 1) / BPS;
if (tip > price - fee) tip = price - fee;
uint256 runnerPay = price - fee - tip;
uint256 unused = o.escrow - price;
uint256 bonds = o.state == State.Disputed ? uint256(o.bond) * 2 : o.bond;
address runner = c.runner;
o.state = State.Delivered;
o.proven = proven;
o.escrow = 0;
o.spent = fixedPrice;
_credit(o, unused);
c.recordHash = recordHash;
emit Delivered(id, c.jobId, runner, recordHash, proven, runnerPay, fee, tip, unused, bonds, agentIds);
_send(runner, runnerPay + bonds);
_send(o.employer, unused);
_payPayroll(id, fee, tip, agentIds);
}
/// @dev Ends a challenged claim against the runner: the release share of its bond to the
/// employer, the rest to the challenger together with the challenger's own bond.
function _refute(uint256 id, Order storage o, Claim storage c) private {
uint256 bond = o.bond;
uint256 cut = _releaseCut(bond);
_endClaim(id, o, c, End.Refuted, 0, cut, bond * 2 - cut);
}
/// @dev Ends a claim without delivery. This is the only place a bond leaves the desk other than
/// with a delivery, and each call names exactly where it goes.
function _endClaim(
uint256 id,
Order storage o,
Claim storage c,
End reason,
uint256 toRunner,
uint256 toEmployer,
uint256 toChallenger
) private {
address runner = c.runner;
uint256 back = toEmployer + _close(id, o, reason == End.DisputeExpired);
if (o.state == State.Open) {
// Open again: the ramp goes on from where this claim found it. Never past the present,
// because `rampFrom` was no later than the claim.
// forge-lint: disable-next-line(unsafe-typecast)
o.rampFrom += uint40(block.timestamp - c.claimedAt);
}
_credit(o, toEmployer);
emit ClaimEnded(id, runner, reason, toRunner, toEmployer, toChallenger, o.state);
_send(runner, toRunner);
_send(c.challenger, toChallenger);
_send(o.employer, back);
}
/// @dev An order nobody holds any more: open again, or refunded when it has expired (or when
/// `refundNow`). Returns the escrow to send to the employer, already booked as returned.
function _close(uint256 id, Order storage o, bool refundNow) private returns (uint256 escrow) {
if (refundNow || block.timestamp >= o.expiresAt) {
escrow = o.escrow;
o.escrow = 0;
o.state = State.Refunded;
_credit(o, escrow);
emit Refunded(id, escrow);
} else {
o.state = State.Open;
}
}
/// @dev Adds to what the employer got back; called once for every transfer to the employer.
/// The sum cannot pass its 96 bits. Whenever an order is open, `returned + escrow` fits: that
/// is true at creation, and `claim` goes ahead only if `returned + escrow + bond` fits. Until
/// the order is open again or finished, the employer can receive at most that bond and that
/// escrow. So this addition, though checked, never reverts and never stands in the way of a
/// payment.
function _credit(Order storage o, uint256 amount) private {
// An escrow, a bond or a part of one: each is a uint96.
// forge-lint: disable-next-line(unsafe-typecast)
o.returned += uint96(amount);
}
function _releaseCut(uint256 bond) private pure returns (uint256) {
return bond * RELEASE_BPS / BPS;
}
function _send(address to, uint256 amount) private {
if (amount != 0) IERC20(IMD).safeTransfer(to, amount);
}
/// @dev Hands the fee and the tip to Payroll. Payroll pulls them through an allowance; whatever
/// it did not pull, for any reason, is sent by plain transfer (its `book()` picks that up), so
/// exactly `fee + tip` leaves the desk whatever Payroll does. A tip of zero (a price of one
/// wei) is not announced.
function _payPayroll(uint256 id, uint256 fee, uint256 tip, uint256[] memory agentIds) private {
uint256 total = fee + tip;
if (total == 0) return;
IERC20 imd = IERC20(IMD);
imd.forceApprove(PAYROLL, total);
_callPayroll(abi.encodeCall(IPayroll.pay, (fee, bytes32(id))));
if (tip != 0) _callPayroll(abi.encodeCall(IPayroll.tip, (agentIds, tip)));
uint256 left = imd.allowance(address(this), PAYROLL);
if (left != 0) {
imd.forceApprove(PAYROLL, 0);
imd.safeTransfer(PAYROLL, left);
emit PayrollFallback(id, left);
}
}
/// @dev Tells the employer, if it asked. Runs after the reentrancy lock is released and after
/// every state change and payment, so the employer may call back into the desk. The gas check
/// comes first: an employer contract can rely on its callback having been offered the whole
/// `CALLBACK_GAS`, whoever sent the transaction.
function _notify(uint256 id) private {
Order storage o = _orders[id];
if (o.flags & FLAG_CALLBACK == 0 || o.notified) return;
Claim storage c = _claims[id];
bytes memory data = abi.encodeCall(IWorkEmployer.onWorkDelivered, (id, c.jobId, c.recordHash));
address employer = o.employer;
if (gasleft() < CALLBACK_GAS * 64 / 63 + GAS_SLACK) revert GasShort();
// Set before the call, so a callback that calls `redeliver` on its own order finds nothing to do.
o.notified = true;
if (!_call(employer, CALLBACK_GAS, data)) {
o.notified = false;
emit CallbackFailed(id);
}
}
/// @dev One Payroll call, always offered the whole `PAYROLL_GAS`: the check comes first, so a
/// caller cannot push a payment onto the plain-transfer path, or change what Payroll does with
/// it, by sending too little gas. Whether the call then succeeds does not matter here; what
/// counts is how much of the allowance it took.
function _callPayroll(bytes memory data) private {
if (gasleft() < PAYROLL_GAS * 64 / 63 + GAS_SLACK) revert GasShort();
_call(PAYROLL, PAYROLL_GAS, data);
}
/// @dev A call that may fail without stopping the caller: fixed gas, no return data copied, no
/// code check on the target.
function _call(address target, uint256 gasCap, bytes memory data) private returns (bool ok) {
assembly ("memory-safe") {
ok := call(gasCap, target, 0, add(data, 0x20), mload(data), 0, 0)
}
}
/// @dev Records a condition that holds now. The answer is kept for good, so the target must
/// have been offered its whole allowance: with less, some targets answer differently (one that
/// reads another contract and falls back to zero when that read runs dry, for example).
function _latch(uint256 id, Order storage o) private {
if (gasleft() < CONDITION_GAS * 64 / 63 + GAS_SLACK) revert GasShort();
(bool holds, uint256 value) = _condition(o);
if (!holds) revert ConditionNotMet();
o.condMet = true;
o.rampFrom = _timestamp();
emit Triggered(id, value);
}
/// @dev One gas-capped static call. Anything but a clean return of at least 32 bytes counts as
/// "does not hold"; only the first word is read, so a large return costs nothing here.
function _condition(Order storage o) private view returns (bool holds, uint256 value) {
address target = o.condTarget;
bytes memory data = o.flags & FLAG_COND_ARG == 0
? abi.encodePacked(o.condSelector)
: abi.encodePacked(o.condSelector, o.condArg);
bool ok;
assembly ("memory-safe") {
ok := staticcall(CONDITION_GAS, target, add(data, 0x20), mload(data), 0x00, 0x20)
ok := and(ok, gt(returndatasize(), 0x1f))
value := mul(ok, mload(0x00))
}
if (ok) {
uint256 cmp = o.condCmp;
uint256 threshold = o.condThreshold;
if (cmp == 1) holds = value >= threshold;
else if (cmp == 2) holds = value <= threshold;
else if (cmp == 3) holds = value > threshold;
else if (cmp == 4) holds = value < threshold;
else if (cmp == 5) holds = value == threshold;
else holds = value != threshold;
}
}
/// @dev A straight line from `minPay` to `maxPay` over `rampSecs`, rounded down in the employer's
/// favour. A conditional order that has not been triggered is priced as if it were triggered
/// now, which is what a claim that latches the condition would fix.
function _price(Order storage o) private view returns (uint96) {
uint256 from = o.rampFrom;
uint256 elapsed = from == 0 ? 0 : block.timestamp - from;
uint256 rampSecs = o.rampSecs;
uint256 price = o.maxPay;
if (elapsed < rampSecs) {
uint256 minPay = o.minPay;
price = minPay + (price - minPay) * elapsed / rampSecs;
}
// Between `minPay` and `maxPay`, which are both uint96.
// forge-lint: disable-next-line(unsafe-typecast)
return uint96(price);
}
/// @dev The block time as stored in orders and claims. Forty bits hold seconds for some
/// thirty-four thousand years.
function _timestamp() private view returns (uint40) {
// forge-lint: disable-next-line(unsafe-typecast)
return uint40(block.timestamp);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
* return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
* value: the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
* the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*
* @custom:stateless
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
_reentrancyGuardStorageSlot().asBoolean().tstore(false);
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _reentrancyGuardStorageSlot().asBoolean().tload();
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represents a slot holding an address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/desk/OrderHeader.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title OrderHeader: the ticket and the 85 bytes a runner puts in front of the job text
/// @notice A swarm job counts for an order only when its objective starts with that order's header.
/// The header carries a ticket, and the ticket commits to the chain, the desk, the order, the claim
/// and the runner, so a work record written for one claim can never pay another one.
///
/// @dev The runner bot and the web app build the same bytes off chain; `test/fixtures/desk/header-vectors.json`
/// holds vectors both sides are tested against.
///
/// ticket = keccak256(abi.encode(chainId, desk, orderId, claimSeq, runner))
/// header = "[help-wanted order " ‖ 64 lowercase hex characters of the ticket ‖ "] "
/// objective = header ‖ spec
library OrderHeader {
/// @dev 19 bytes of prefix, 64 of hex, 2 of suffix.
uint256 internal constant LENGTH = 85;
/// @notice The ticket of one claim.
/// @param chainId The chain the desk lives on, so a record cannot be replayed on another chain.
/// @param desk The WorkOrders contract, so it cannot be replayed on another desk.
/// @param orderId The order.
/// @param claimSeq How many times the order has been claimed, counting this claim, from 1.
/// @param runner The address that holds the claim.
function ticket(uint256 chainId, address desk, uint256 orderId, uint256 claimSeq, address runner)
internal
pure
returns (bytes32)
{
return keccak256(abi.encode(chainId, desk, orderId, claimSeq, runner));
}
/// @notice The 85 header bytes for a ticket.
function build(bytes32 ticket_) internal pure returns (bytes memory out) {
out = new bytes(LENGTH);
assembly ("memory-safe") {
// The 19 prefix bytes; the 13 zero bytes that follow are overwritten by the hex below.
mstore(add(out, 0x20), "[help-wanted order ")
let digits := "0123456789abcdef"
let cursor := add(out, 51) // 0x20 + 19
for { let i := 0 } lt(i, 32) { i := add(i, 1) } {
let b := byte(i, ticket_)
mstore8(cursor, byte(shr(4, b), digits))
mstore8(add(cursor, 1), byte(and(b, 0x0f), digits))
cursor := add(cursor, 2)
}
mstore8(cursor, 0x5d) // "]"
mstore8(add(cursor, 1), 0x20) // " "
}
}
/// @notice keccak256 of the header: what a proof's `headHash` must equal for this ticket.
function hash(bytes32 ticket_) internal pure returns (bytes32) {
return keccak256(build(ticket_));
}
}
src/desk/SpecText.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title SpecText: the character rules of a job spec
/// @notice A spec is the job text a runner sends to the swarm after the order header. The desk
/// accepts only text whose JSON-escaped form is the text itself, because the work record stores
/// the objective JSON-escaped and the desk compares hashes of raw bytes. A spec that passes here
/// can always be matched against a record; one that fails could never be settled.
///
/// @dev The rules: 1 to 7,900 bytes; every byte printable ASCII (0x20 to 0x7E); no `"` (0x22) and
/// no `\` (0x5C); the first and the last byte are not a space, so nothing that trims text on the way
/// to the swarm can change it.
library SpecText {
uint256 internal constant MAX_LENGTH = 7900;
/// @dev What `firstBad` returns for a spec that breaks no rule.
uint256 internal constant NONE = type(uint256).max;
/// @notice Finds the first byte that breaks a rule.
/// @return at `NONE` when the spec is acceptable. Otherwise: 0 for an empty spec; `MAX_LENGTH`
/// (the index of the first byte over the limit) for one that is too long; else the lowest index
/// of a byte that is not allowed where it stands.
function firstBad(bytes calldata spec) internal pure returns (uint256 at) {
uint256 len = spec.length;
if (len == 0) return 0;
if (len > MAX_LENGTH) return MAX_LENGTH;
if (spec[0] == 0x20) return 0;
at = NONE;
assembly ("memory-safe") {
let ones := 0x0101010101010101010101010101010101010101010101010101010101010101
let highs := 0x8080808080808080808080808080808080808080808080808080808080808080
let start := spec.offset
for { let i := 0 } lt(i, len) { i := add(i, 0x20) } {
let w := calldataload(add(start, i))
let left := sub(len, i)
if lt(left, 0x20) {
// The word runs past the end of the spec: read those bytes as "a".
let pad := shr(shl(3, left), not(0))
w := or(and(w, not(pad)), and(mul(ones, 0x61), pad))
}
// A set high bit in `bad` means: some byte of the word is over 0x7F, is under 0x20,
// or equals 0x7F, 0x22 or 0x5C. The word-wide tests can only say "somewhere in this
// word", so the exact byte is then found one at a time.
let bad := and(w, highs)
bad := or(bad, and(and(sub(w, mul(ones, 0x20)), not(w)), highs))
let x := xor(w, mul(ones, 0x7f))
bad := or(bad, and(and(sub(x, ones), not(x)), highs))
x := xor(w, mul(ones, 0x22))
bad := or(bad, and(and(sub(x, ones), not(x)), highs))
x := xor(w, mul(ones, 0x5c))
bad := or(bad, and(and(sub(x, ones), not(x)), highs))
if bad {
for { let j := 0 } lt(j, 0x20) { j := add(j, 1) } {
let c := byte(j, w)
if or(or(lt(c, 0x20), gt(c, 0x7e)), or(eq(c, 0x22), eq(c, 0x5c))) {
at := add(i, j)
break
}
}
if iszero(eq(at, not(0))) { break }
}
}
}
if (at == NONE && spec[len - 1] == 0x20) return len - 1;
}
}
src/interfaces/IPayroll.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title Payroll: where HELP WANTED's fees arrive and how they leave
/// @notice No owner and no setters. Everything that arrives is split by fixed shares between
/// sIMD stakers (a slow stream), seat owners (pull claims) and the budget that buys the house
/// feeds. Later launches only ever call `pay` and `tip`; Payroll never needs to know them.
///
/// @dev The functions below are the frozen surface other launches compile against. The
/// implementation may add views and events, never change these signatures.
interface IPayroll {
/// @notice Pulls `amount` IMD from the caller and books it as revenue.
/// @param memo A free label for the ledger (an order id, `bytes32("grant")`, …). It changes
/// nothing about how the money is split.
function pay(uint256 amount, bytes32 memo) external;
/// @notice Pulls `amount` IMD from the caller as a tip for the agents that did one job.
/// @dev Split equally between `agentIds`; each share waits for `claimTip`. Only the first 16
/// ids share the tip; ids after that are ignored. What the equal split leaves over joins the
/// seat pool, and an empty list sends the whole amount there. Never reverts because of what
/// the list contains.
function tip(uint256[] calldata agentIds, uint256 amount) external;
/// @notice Splits any IMD that arrived by plain transfer since the last call.
function book() external returns (uint256 booked);
/// @notice Moves the due part of the staker stream into sIMD. Anyone may call.
function drip() external returns (uint256 sent);
/// @notice Pays the current seat owner. A contract owner must initiate its claim, except Payroll itself.
function claimSeat(uint256 tokenId) external returns (uint256 paid);
function claimSeats(uint256[] calldata tokenIds) external returns (uint256 paid);
/// @notice Pays the bound seat's owner. A contract owner must initiate its claim, except Payroll itself.
function claimTip(uint256 agentId) external returns (uint256 paid);
function seatClaimable(uint256 tokenId) external view returns (uint256);
function tipOwed(uint256 agentId) external view returns (uint256);
}
src/interfaces/IWorkOrders.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title What a contract employer implements to hear that its order was delivered
/// @dev Called last, after every payout, with a fixed gas allowance inside a try. A revert here
/// changes nothing about the settlement. Opt in with `FLAG_CALLBACK`.
interface IWorkEmployer {
function onWorkDelivered(uint256 orderId, bytes16 jobId, bytes32 recordHash) external;
}
/// @title WorkOrders, the hire desk, as an employer sees it
/// @notice An employer (a wallet or a contract) escrows IMD against a pinned job spec. A bonded
/// runner opens the swarm job; the escrow pays only when the job's work record is proven against
/// IdentityMD's WorkRegistry, or, if the employer opted in, when a bonded delivery claim goes
/// unchallenged. Anything else returns the money to the employer.
///
/// @dev This is the frozen surface other contracts (CrowdPots, the Doorbell, Rules, Zap) compile
/// against. The implementation adds the runner and settlement functions.
interface IWorkOrders {
enum State {
None,
/// Escrowed and waiting for a runner (or for its condition).
Open,
/// A runner posted a bond and holds the order for a short exclusive window.
Claimed,
/// The runner opened the swarm job and registered its id.
Registered,
/// The runner claimed delivery without a receipt; the challenge window is running.
Asserted,
/// A delivery claim was challenged; only a receipt (or the order's arbiter) decides it.
Disputed,
/// Paid out. Terminal.
Delivered,
/// Withdrawn by the employer before any runner took it. Terminal.
Cancelled,
/// Expired or timed out; escrow returned. Terminal.
Refunded
}
/// @dev `flags` bits.
/// FLAG_ALLOW_CLAIMED: the employer accepts the bonded claim path when no receipt is available.
/// FLAG_CALLBACK: call `IWorkEmployer.onWorkDelivered` on the employer at settlement.
/// FLAG_COND_ARG: the condition call takes `condArg` as its single argument.
struct OrderParams {
/// keccak256 of the work record's `kind` string the employer wants, e.g. keccak256("audit").
bytes32 kindHash;
/// The price starts here and rises linearly to `maxPay` over `rampSecs`. A runner's claim
/// fixes the price at that moment.
uint96 minPay;
/// Pulled from the employer at creation. Whatever the fixed price leaves is returned.
uint96 maxPay;
uint32 rampSecs;
/// How long the runner has, after registering the job, for a receipt to exist.
uint32 deliverySecs;
/// After this time an order nobody holds can be refunded by anyone.
uint40 expiresAt;
/// The bond a runner must post to take the order.
uint96 bond;
uint8 flags;
/// Zero for any runner, or the one address allowed to take the order.
address runnerOnly;
/// Zero for none, or the address allowed to decide a disputed claim.
address arbiter;
/// Zero for an ordinary order. Otherwise the order can only be taken once
/// `condTarget.staticcall(condSelector [++ condArg])` has returned a word that compares true
/// against `condThreshold` under `condCmp`: WHEN that happens, THEN hire.
address condTarget;
bytes4 condSelector;
bytes32 condArg;
/// 0 none, 1 >=, 2 <=, 3 >, 4 <, 5 ==, 6 !=
uint8 condCmp;
uint256 condThreshold;
}
/// @notice Opens an order. Pulls `p.maxPay` IMD from the caller, who becomes the employer.
/// @param spec The job text a runner must send to the swarm, byte for byte, after the order
/// header. Printable ASCII (0x20 to 0x7E) without `"` or `\`, no leading or trailing space,
/// 1 to 7,900 bytes.
function createOrder(OrderParams calldata p, bytes calldata spec) external returns (uint256 id);
/// @notice The employer withdraws an order nobody has taken.
function cancel(uint256 id) external;
/// @notice Anyone returns the escrow of an order that expired with nobody holding it.
function refund(uint256 id) external;
function stateOf(uint256 id) external view returns (State);
/// @notice The money side of one order, for employer contracts that keep their own books.
/// @param escrow IMD the desk still holds for the order.
/// @param spent IMD paid out for delivered work (runner, fee and tip together).
/// @param returned IMD sent back to the employer so far, including any runner bond it was awarded.
/// Every transfer the desk makes to the employer for this order is counted here, so an employer
/// contract that holds many orders' money can keep its books from this figure alone.
function accountOf(uint256 id)
external
view
returns (State state, address employer, uint96 escrow, uint96 spent, uint96 returned);
function orderCount() external view returns (uint256);
function FLAG_ALLOW_CLAIMED() external view returns (uint8);
function FLAG_CALLBACK() external view returns (uint8);
function FLAG_COND_ARG() external view returns (uint8);
function MIN_BOND() external view returns (uint96);
function MIN_DELIVERY() external view returns (uint32);
function IMD() external view returns (address);
}
src/interfaces/IWorkOrdersRunner.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IWorkOrders} from "./IWorkOrders.sol";
/// @title WorkOrders, the hire desk, as a runner or a keeper sees it
/// @notice Everything you need to earn from the desk without asking anybody. A runner takes an
/// order, buys the job from IdentityMD's swarm with its own wallet, and is paid when the job's
/// work record is proven on chain. A keeper makes the calls that nothing makes by itself (ending
/// what ran out of time, paying what is due) and needs no permission either. There is no list of
/// allowed runners or keepers and no owner who could add one.
///
/// @dev THE RUNNER'S LOOP, in the order the calls are made:
///
/// 1. Find an order. Every order is announced by `OrderOpened`, which carries the full job text
/// (`spec`) and every parameter. Before taking one, check what the desk cannot check for you:
/// that `kindHash` is the keccak256 of a `kind` the swarm writes (a work record's `kind` is the
/// name of the job template, for example `audit` or `skill:research-report`), that the price
/// (`priceNow`) covers the swarm's fee and your gas, and, if the order allows the claimed path,
/// who its `arbiter` is. A conditional order must have been triggered (`conditionOf`), or its
/// condition must hold now.
/// 2. `claim(id)`: you post the order's bond (approve the desk for it first) and the price is
/// fixed. The call returns a ticket; `headerOf(id)` gives the 85 bytes built from it.
/// 3. Open the job with IdentityMD within one hour (`CLAIM_WINDOW`). Its objective must be exactly
/// `headerOf(id)` followed by the order's spec, byte for byte, under the template whose name is
/// the order's kind. The header ties the job to this chain, this desk, this order, this claim
/// and your address, so nobody else's job can be passed off as yours and yours can pay nobody
/// else. If you change your mind inside the hour, `release(id)` costs a tenth of the bond.
/// 4. `register(id, jobId)` with the job's id (the 16 bytes of its UUID) inside that hour. From
/// then on you have the order's `deliverySecs` for a receipt to exist. If the job fails, you
/// may open another and call `register` again; the time does not restart.
/// 5. When IdentityMD has written the job's receipt to its WorkRegistry, fetch the work record
/// from `https://api.imd.fun/work-records/<record hash>.json` and call
/// `settle(id, record, [])` with those bytes exactly as served. You are paid the fixed price
/// less 10% (a 5% fee and a 5% tip for the agents that worked), and your bond comes back, in
/// the same transaction. Anyone may make this call for you. Offer it more gas than it will
/// use: the desk insists on being able to hand 1,000,000 gas to each of its two Payroll calls
/// and refuses (`GasShort`) otherwise. A small record needs about 1.4M to 1.6M gas on offer
/// and uses 0.4M to 0.6M; a record naming sixteen agents never tipped before, or the costliest
/// record seen, needs 1.6M to 2.0M and uses 1.0M to 1.1M (the calldata's own charge comes on
/// top). An ordinary gas estimate finds the figure; what is not used is returned as usual.
/// A record above about 128 KB does not fit in one transaction: store it as data contracts
/// (`0x00` followed by a slice, see `IWorkProof.proveChunks`) and pass their addresses as
/// `chunks`.
///
/// WHEN THE JOB DID NOT WORK OUT. A receipt that shows your objective but a state other than
/// `completed` is the swarm's failure, not yours: `reportFailed(id, record, [])`, which only you
/// may call for it, returns your whole bond and frees the order. Or register a retry job instead.
/// With no settlement by the delivery deadline, anyone may call `timeout(id)` and the bond goes
/// to the employer. Timeouts are lazy: until that call is made, a late receipt still settles.
///
/// WHEN RECEIPTS ARE LATE (orders with `FLAG_ALLOW_CLAIMED` only). After registering, and with at
/// least 48 hours of delivery time left, `claimDelivered(id, recordHash)` states that the job was
/// delivered as the record with that hash (the hash IdentityMD's API lists for the job). If
/// nobody challenges within 24 hours, `finalize(id)` pays you exactly as `settle` does, marked
/// unproven; later anyone can `stamp(id, record, [])` to mark it proven, which moves no money. If
/// somebody does challenge, a receipt that settles the order still pays you, and gives you the
/// challenger's bond as well. A receipt that does not settle it, or the arbiter deciding against
/// you, costs you the bond. With nothing decided by the delivery deadline the employer is
/// refunded and you get back 90% of the bond.
///
/// THE KEEPER'S CALLS, each open to anyone and each refused until it is due:
/// `trigger` (a conditional order whose condition holds), `refund` (an order that expired with
/// nobody holding it), `evict` (a runner that registered no job within the hour), `timeout` (a
/// delivery deadline that passed), `settle` and `stamp` (a receipt exists), `reportFailed` (a
/// receipt that contradicts a claim, or shows another job than the claim's), `challenge` (a
/// delivery claim you can show to be untrue; it needs a bond), `finalize` (a delivery claim
/// nobody challenged) and `redeliver` (an employer callback that failed). None of them pays the
/// keeper anything from the desk; a keeper runs them for an employer, for a runner or for itself.
///
/// WHAT YOU TRUST. The desk has no owner and cannot be changed or paused. What a work record says
/// is decided by WorkProof against IdentityMD's WorkRegistry: if the registry writes no receipt
/// for your job in time, a receipt-only order does not pay and your bond is forfeited at the
/// deadline, so look at how receipts are flowing before you take one (the registry's newest
/// `WorkRecorded` event tells you).
interface IWorkOrdersRunner is IWorkOrders {
/// @notice Everything the desk stores about an order, apart from its current claim.
/// @dev `rampFrom` is the moment the price ramp is counted from: creation for an ordinary
/// order, the moment the condition was first seen true for a conditional one (zero until then),
/// moved forward by the time runners held the order without delivering, so that only time spent
/// open raises the price. `escrow` is the IMD still held for the order; `spent` and `returned`
/// are as in `accountOf`. `seq` counts claims; `proven` is set once a registry receipt has been
/// matched; `notified` once the employer's callback has run without failing.
struct Order {
address employer;
uint40 expiresAt;
uint40 rampFrom;
State state;
uint8 flags;
bytes32 kindHash;
bytes32 specHash;
uint96 minPay;
uint96 maxPay;
uint32 rampSecs;
uint32 deliverySecs;
address runnerOnly;
uint96 bond;
address arbiter;
uint96 escrow;
address condTarget;
bytes4 condSelector;
uint8 condCmp;
bool condMet;
bool proven;
bool notified;
uint32 seq;
bytes32 condArg;
uint256 condThreshold;
uint96 spent;
uint96 returned;
}
/// @notice The current claim of an order (or its last one, once the order is free again).
/// @dev `price` was fixed when the runner claimed. `recordHash` is the hash the runner stated
/// on the claimed path, replaced by the receipt's hash once a receipt has been matched.
struct Claim {
address runner;
uint40 claimedAt;
uint40 registeredAt;
uint96 price;
bytes16 jobId;
address challenger;
uint40 assertedAt;
bytes32 recordHash;
}
/// @notice Why a claim ended without a delivery.
enum End {
/// The runner gave the order back before registering a job: the release share (10%) of the
/// bond to the employer, the rest back to the runner.
Released,
/// No job was registered within the claim window: the bond to the employer.
Evicted,
/// No receipt settled the order within the delivery time: the bond to the employer.
TimedOut,
/// The receipt shows this claim's objective but no completed work of the order's kind: the
/// bond goes back to the runner.
SwarmFailed,
/// The receipt shows another objective than this claim's: the bond to the employer.
WrongJob,
/// A delivery claim was contradicted by a receipt or by the arbiter. Unchallenged: the bond
/// to the employer. Challenged: the release share of the bond to the employer, the rest to
/// the challenger together with its own bond.
Refuted,
/// A challenged claim reached the delivery deadline undecided: the employer is refunded,
/// the challenger's bond returned, and the runner is treated as if it had released (the
/// release share of its bond to the employer, the rest back).
DisputeExpired
}
// ------------------------------------------------------------------------------------------
// Events: what to watch
// ------------------------------------------------------------------------------------------
/// @notice A new order. `spec` is the full job text; the desk itself keeps only its hash.
event OrderOpened(
uint256 indexed id,
address indexed employer,
bytes32 indexed kindHash,
bytes32 specHash,
OrderParams params,
bytes spec
);
/// @notice The order's condition was seen true with `value`; the order can be taken from now on.
event Triggered(uint256 indexed id, uint256 value);
/// @notice A runner took the order. `ticket` goes into the header of the job it must open.
event Claimed(uint256 indexed id, address indexed runner, uint256 seq, uint256 price, uint256 bond, bytes32 ticket);
/// @notice The runner recorded the swarm job it opened for the order (again for a retry job).
event Registered(uint256 indexed id, bytes16 indexed jobId);
/// @notice The runner claimed delivery without a receipt; it can be challenged until `challengeUntil`.
event DeliveryClaimed(uint256 indexed id, bytes16 indexed jobId, bytes32 recordHash, uint256 challengeUntil);
/// @notice Somebody posted `bond` against the delivery claim.
event Challenged(uint256 indexed id, address indexed challenger, uint256 bond);
/// @notice The order's arbiter decided a disputed claim.
event Resolved(uint256 indexed id, address indexed arbiter, bool delivered);
/// @notice A receipt was submitted that does not settle the order.
event Failed(uint256 indexed id, bytes16 indexed jobId, bytes32 recordHash);
/// @notice A claim ended without a delivery. The three amounts are where the bond money went
/// (`toChallenger` includes the challenger's own bond); `next` is the order's new state.
event ClaimEnded(
uint256 indexed id,
address indexed runner,
End reason,
uint256 toRunner,
uint256 toEmployer,
uint256 toChallenger,
State next
);
/// @notice The order was paid out. `runnerPay + fee + tip` is the fixed price; `toEmployer` is
/// the unused escrow; `bonds` went to the runner on top (its own, plus a losing challenger's).
event Delivered(
uint256 indexed id,
bytes16 indexed jobId,
address indexed runner,
bytes32 recordHash,
bool proven,
uint256 runnerPay,
uint256 fee,
uint256 tip,
uint256 toEmployer,
uint256 bonds,
uint256[] agentIds
);
/// @notice An order paid on an unchallenged or arbitrated claim was later matched to its receipt.
event Proven(uint256 indexed id, bytes16 indexed jobId, bytes32 recordHash);
/// @notice The employer withdrew an order nobody held.
event Cancelled(uint256 indexed id, uint256 toEmployer);
/// @notice The escrow went back to the employer (expiry, or an undecided dispute).
event Refunded(uint256 indexed id, uint256 toEmployer);
/// @notice The employer's `onWorkDelivered` reverted or ran out of gas. The delivery stands, and
/// anyone may try the callback again with `redeliver`.
event CallbackFailed(uint256 indexed id);
/// @notice A callback that had failed went through on a later try.
event Redelivered(uint256 indexed id);
/// @notice Payroll did not take all of the fee and tip; `amount` was sent to it by plain transfer.
event PayrollFallback(uint256 indexed id, uint256 amount);
// ------------------------------------------------------------------------------------------
// Errors
// ------------------------------------------------------------------------------------------
//
// Besides the errors below, a call can revert with three kinds of error that are not the desk's
// own. `settle`, `reportFailed` and `stamp` pass on, unchanged, whatever WorkProof reverts with
// when it turns a record away: the errors of `IWorkProof` (`NoReceipt`, `HashMismatch`,
// `Malformed`, `MissingKey`, `WrongSchema`, `JobIdMismatch`) and WorkProof's own `BadChunk` and
// `InsufficientGas`. A call made from inside another call to the desk reverts
// `ReentrancyGuardReentrantCall()`. A token transfer the token refuses reverts with the
// token's error or `SafeERC20FailedOperation(address)`.
/// @notice A constructor argument is the zero address.
error ZeroAddress();
/// @notice The order is not in a state that allows this call.
error BadState();
/// @notice Only the order's employer may do this.
error NotEmployer();
/// @notice Only the runner that holds the order may do this, or the order is reserved for another runner.
error NotRunner();
/// @notice Only the order's arbiter may do this (nobody, if the order has none).
error NotArbiter();
/// @notice The spec breaks the character rules at byte `at` (see `SpecText`).
error SpecInvalid(uint256 at);
/// @notice `maxPay` is zero or `minPay` is above it.
error PayRange();
/// @notice `deliverySecs` is under `MIN_DELIVERY`.
error DeliveryTooShort();
/// @notice `deliverySecs` is over `MAX_DELIVERY`.
error DeliveryTooLong();
/// @notice `bond` is under `MIN_BOND`.
error BondTooLow();
/// @notice An unknown flag bit, or `FLAG_COND_ARG` on an order with no condition.
error BadFlags();
/// @notice `condCmp` is out of range, or set without a target, or a target without it.
error BadCondition();
/// @notice The order's expiry is not in the future.
error Expired();
/// @notice The time this call waits for has not come yet.
error TooEarly();
/// @notice The time in which this call was possible has passed.
error TooLate();
/// @notice The caller released this order before.
error Barred();
/// @notice The order's condition does not hold now and has never been seen to hold.
error ConditionNotMet();
/// @notice The employer did not allow the claimed path for this order.
error ClaimedPathOff();
/// @notice A job id of zero cannot be registered.
error ZeroJob();
/// @notice A record hash of zero cannot be claimed.
error ZeroHash();
/// @notice This job's receipt already settled another order.
error JobUsed();
/// @notice The record's state is not "completed".
error NotCompleted();
/// @notice The record's kind is not the order's.
error WrongKind();
/// @notice The record's objective does not start with this claim's header.
error WrongHeader();
/// @notice The record's objective does not continue with the order's spec.
error WrongSpec();
/// @notice The receipt is one that settles the order; use `settle`.
error NotFailed();
/// @notice Not enough gas was supplied to give a protected call its full allowance.
error GasShort();
/// @notice One more claim could take the order's `returned` figure past what it can hold.
error BooksFull();
// ------------------------------------------------------------------------------------------
// Taking an order
// ------------------------------------------------------------------------------------------
/// @notice Records that a conditional order's condition holds now, which opens the order to
/// runners for good and starts its price ramp. Anyone may call.
/// @dev Reverts `BadState` when the order is not open, has no condition or is already
/// triggered, `ConditionNotMet` when the condition does not hold, and `GasShort` unless the
/// call can hand the condition target its whole `CONDITION_GAS` (send 150,000 gas or more).
/// `claim` does the same by itself, so a runner need not call this first.
function trigger(uint256 id) external;
/// @notice Takes an open order: pulls the order's bond from the caller (approve the desk for
/// it first), fixes the price at what `priceNow` shows, and starts the hour in which a job must
/// be registered.
/// @dev Reverts `BadState` (not open), `Expired`, `NotRunner` (reserved for another runner),
/// `Barred` (the caller released this order before) and `ConditionNotMet` (a condition that
/// has never been seen true and is not true now).
/// @return ticket The value that goes into the job's header; `headerOf(id)` builds the header.
function claim(uint256 id) external returns (bytes32 ticket);
/// @notice Gives the order back before a job is registered, inside the claim window only. The
/// caller gets 90% of its bond, the employer 10%, and the caller may not take this order again.
/// @dev Only the runner that holds the order. `TooLate` once `CLAIM_WINDOW` has passed.
function release(uint256 id) external;
/// @notice Removes a runner that registered no job within the claim window. Anyone may call.
/// The whole bond goes to the employer and the order is open again, or refunded if it expired.
/// @dev `TooEarly` inside the window. Lazy: until somebody calls this, the runner can still register.
function evict(uint256 id) external;
/// @notice Records the swarm job the runner opened for the order. May be called again, before
/// the order is settled, to replace the job with a retry.
/// @dev Only the runner that holds the order. `ZeroJob` for a zero id; `JobUsed` for a job
/// whose receipt already settled another order. The delivery time runs from the first
/// registration and a retry does not restart it.
/// @param jobId The job's UUID as 16 bytes (the 32 hex digits without the dashes).
function register(uint256 id, bytes16 jobId) external;
// ------------------------------------------------------------------------------------------
// Being paid on a receipt
// ------------------------------------------------------------------------------------------
/// @notice Pays the order out against the work record of its registered job. Anyone may call.
/// @dev Reverts with WorkProof's own error unless `record` is the receipt the WorkRegistry
/// holds for the job, and with `NotCompleted`, `WrongKind`, `WrongHeader`, `WrongSpec` or
/// `JobUsed` when the record does not settle this claim. `GasShort` unless about 1.25M to
/// 1.65M gas is on offer beyond what the proof itself uses (the figure moves with what the
/// first Payroll call spends); unused gas is returned.
///
/// The runner receives the fixed price less the 5% fee and the 5% tip (each rounded up),
/// together with its bond, and a challenger's bond after a dispute. Any receipt of the
/// registered job that passes the checks pays, whatever hash a delivery claim named.
/// @param record The work record exactly as IdentityMD serves it (no trailing newline). Ignored
/// when `chunks` is not empty.
/// @param chunks For a record too large for one transaction: data contracts holding it in order.
function settle(uint256 id, bytes calldata record, address[] calldata chunks) external;
/// @notice Ends a claim with a receipt of its registered job that does not settle the order.
/// @dev While the job is only registered: a receipt with this claim's objective that did not
/// end `completed` may be reported by the runner alone, and returns its whole bond; one that
/// is `completed` under another kind may be reported by anyone, and also returns the bond; one
/// with any other objective may be reported by anyone and sends the bond to the employer.
/// After a delivery claim, any such receipt may be reported by anyone and the runner loses
/// its bond (to the employer, or shared between the employer and the challenger). `NotFailed`
/// for a receipt that settles the order. The order is open again afterwards, or refunded if
/// it has expired.
function reportFailed(uint256 id, bytes calldata record, address[] calldata chunks) external;
/// @notice Ends a claim whose delivery time has passed. Anyone may call.
/// @dev A registered job: the bond goes to the employer and the order is open again, or
/// refunded if it has expired. A challenged delivery claim that nothing decided: the employer
/// is refunded, the challenger gets its bond back and the runner 90% of its own. `TooEarly`
/// before the deadline (`claimOf(id).registeredAt + orderOf(id).deliverySecs`); `BadState` for
/// an unchallenged delivery claim, which only `finalize`, `settle` or `reportFailed` end.
function timeout(uint256 id) external;
// ------------------------------------------------------------------------------------------
// Being paid on a claim (orders with FLAG_ALLOW_CLAIMED)
// ------------------------------------------------------------------------------------------
/// @notice The runner states that its registered job was delivered as the record with this
/// hash, and opens the 24-hour challenge window.
/// @dev Only the runner, once per claim. `ClaimedPathOff` on an order without the flag,
/// `ZeroHash`, and `TooLate` unless `CHALLENGE_WINDOW + DISPUTE_WINDOW` (48 hours) still fit
/// before the delivery deadline. Name the hash IdentityMD's API lists for the job, so that a
/// watcher can compare; it plays no part in what a receipt later decides.
function claimDelivered(uint256 id, bytes32 recordHash) external;
/// @notice Disputes a delivery claim by posting a bond equal to the runner's (approve the desk
/// for it first). Anyone may call, once per claim, inside the challenge window.
/// @dev The challenger wins the runner's bond, less the employer's tenth, if a receipt of the
/// registered job fails to settle the order or the arbiter decides against the runner. It
/// loses its own bond to the runner if a receipt settles the order or the arbiter decides for
/// the runner. With nothing decided by the delivery deadline it gets its bond back. A record
/// hash that differs from the one the runner named is not by itself a reason to challenge.
///
/// Before posting, read `orderOf(id)`: the bond is held until the dispute ends, at the longest
/// until `claimOf(id).registeredAt + deliverySecs` (up to 90 days); the order's `arbiter`, if
/// it has one, decides with no evidence and may be the employer itself; and the employer may
/// be its own runner, in which case a dispute that nothing decides costs it nothing.
function challenge(uint256 id) external;
/// @notice Pays out a delivery claim nobody challenged in time. Anyone may call.
/// @dev `TooEarly` inside the challenge window; `GasShort` as in `settle`. The order is marked
/// unproven and the tip goes to Payroll with no agent list, also when a receipt exists by
/// then: to have the agents named, call `settle` with the record instead.
function finalize(uint256 id) external;
/// @notice The order's arbiter decides a disputed claim.
/// @dev `NotArbiter` for anyone else. True pays the runner as delivered (unproven) and gives
/// it the challenger's bond; that call needs the gas `settle` needs. False ends the claim
/// against the runner as a contradicting receipt would.
function resolve(uint256 id, bool delivered) external;
/// @notice Marks an order that was paid on a claim as proven, once its receipt exists. Anyone
/// may call. No money moves.
/// @dev The same checks as `settle`. `BadState` unless the order is delivered and unproven.
function stamp(uint256 id, bytes calldata record, address[] calldata chunks) external;
/// @notice Tries the employer's `onWorkDelivered` again for a delivered order whose callback
/// failed. Anyone may call. No money moves.
/// @dev `BadState` unless the order is delivered, asked for a callback and has not had one go
/// through; `GasShort` unless `CALLBACK_GAS` can be handed over (send 200,000 gas or more).
function redeliver(uint256 id) external;
// ------------------------------------------------------------------------------------------
// Views
// ------------------------------------------------------------------------------------------
/// @notice Everything stored about an order. The spec text itself is in its `OrderOpened` event.
function orderOf(uint256 id) external view returns (Order memory);
/// @notice The order's current claim. After a claim ended without delivery this still shows
/// that last claim, until the next runner takes the order.
function claimOf(uint256 id) external view returns (Claim memory);
/// @notice What a runner claiming now would be paid in total (fee and tip included). While a
/// runner holds the order, and once it is delivered, the price that runner's claim fixed.
function priceNow(uint256 id) external view returns (uint96);
/// @notice The ticket of the order's current (or last) claim:
/// `keccak256(abi.encode(chainId, desk, orderId, claimSeq, runner))`.
function ticketOf(uint256 id) external view returns (bytes32);
/// @notice The 85 bytes the runner must put at the very start of the swarm job's objective,
/// directly followed by the spec: `"[help-wanted order "`, the ticket as 64 lowercase hex
/// digits, `"] "`.
/// @dev Reverts `BadState` unless a runner holds the order or the order was delivered.
function headerOf(uint256 id) external view returns (bytes memory);
/// @notice The status of an order's condition.
/// @return met True when the order can be taken as far as its condition goes.
/// @return holdsNow Whether the condition call compares true at this moment.
/// @return value The word the condition call returned, or zero if it failed.
function conditionOf(uint256 id) external view returns (bool met, bool holdsNow, uint256 value);
/// @notice The order a job's receipt was matched for, or zero. Such a job can settle no other order.
function orderOfJob(bytes16 jobId) external view returns (uint256 orderId);
/// @notice True once `runner` has released order `orderId`; it may not take that order again.
function barred(uint256 orderId, address runner) external view returns (bool);
/// @notice The longest delivery time an order may ask for.
function MAX_DELIVERY() external view returns (uint32);
/// @notice The fee, in basis points of the fixed price, sent to Payroll at delivery.
function FEE_BPS() external view returns (uint256);
/// @notice The tip, in basis points of the fixed price, sent to Payroll for the agents that worked.
function TIP_BPS() external view returns (uint256);
/// @notice The part of the bond, in basis points, a runner loses to the employer when it
/// releases an order, and at least loses when a challenged claim is not upheld.
function RELEASE_BPS() external view returns (uint256);
/// @notice How long a runner may hold an order without registering a job, in seconds.
function CLAIM_WINDOW() external view returns (uint256);
/// @notice How long a delivery claim can be challenged, in seconds.
function CHALLENGE_WINDOW() external view returns (uint256);
/// @notice The least time a challenged delivery claim has, before the delivery deadline, for a
/// receipt or the arbiter to decide it, in seconds.
function DISPUTE_WINDOW() external view returns (uint256);
/// @notice Gas given to the employer's `onWorkDelivered`.
function CALLBACK_GAS() external view returns (uint256);
/// @notice Gas given to an order's condition call.
function CONDITION_GAS() external view returns (uint256);
/// @notice Gas given to each of the two Payroll calls made at delivery.
function PAYROLL_GAS() external view returns (uint256);
/// @notice Length of the order header at the start of a job's objective: 85.
function HEADER_LEN() external view returns (uint256);
/// @notice The contract that checks work records against the IdentityMD WorkRegistry.
function WORK_PROOF() external view returns (address);
/// @notice Where fees and tips go.
function PAYROLL() external view returns (address);
}
src/interfaces/IWorkProof.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title WorkProof: checks a swarm work record against IdentityMD's on-chain receipt
/// @notice Stateless. Anyone, including other builders' contracts, can call it to learn what a job
/// was asked to do, how it ended and which agents worked on it, with nothing trusted beyond the
/// WorkRegistry itself.
///
/// @dev Frozen surface. `record` is the canonical work-record JSON byte for byte as IdentityMD serves it
/// (the served file has no trailing newline; nothing is stripped or added). `headLen` is how many
/// leading bytes of the top-level `objective` string the caller wants hashed separately from the rest
/// (the order header).
interface IWorkProof {
struct Proof {
/// @dev keccak256 of the whole record; equal to `WorkRegistry.latest(jobId)`.
bytes32 recordHash;
/// @dev keccak256 of the top-level `kind` string's contents.
bytes32 kindHash;
/// @dev keccak256 of the first `headLen` raw bytes of the top-level `objective` contents.
bytes32 headHash;
/// @dev keccak256 of the rest of the `objective` contents, raw (still JSON-escaped) bytes.
bytes32 specHash;
/// @dev keccak256 of the top-level `state` string's contents.
bytes32 stateHash;
/// @dev The ERC-8004 agent ids in the top-level `signals`, de-duplicated, at most 16. An
/// agent whose signals all record a submission that verification rejected (`value` 0) is
/// left out. Empty when the list cannot be read, and for a job's later, superseding
/// record, which carries no signals; an empty list never makes a proof fail.
uint256[] agentIds;
}
error NoReceipt(bytes16 jobId);
error HashMismatch(bytes32 expected, bytes32 got);
error Malformed(uint256 pos);
error MissingKey();
error WrongSchema();
error JobIdMismatch();
error HeadTooLong();
/// @notice Reverts unless `record` is the receipt the WorkRegistry holds for `jobId`.
function prove(bytes16 jobId, bytes calldata record, uint256 headLen) external view returns (Proof memory);
/// @notice The same, for a record too large for one transaction, stored across data contracts.
/// @dev Each chunk is a contract whose code is one `0x00` byte followed by a slice of the record.
function proveChunks(bytes16 jobId, address[] calldata chunks, uint256 headLen) external view returns (Proof memory);
/// @notice Parses a record without consulting the registry. For tools and tests; proves nothing.
function scan(bytes calldata record, uint256 headLen) external pure returns (bytes16 jobId, Proof memory);
function WORK_REGISTRY() external view returns (address);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none"
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
":forge-std/=lib/forge-std/src/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.