# Protected JSON work v3

**Experimental, active 402Mob-operated pilot; not independently audited.** The two verifiers share the primary VPS and operator. Automatic relay is off; clients submit transactions and monitor deadlines. New installations remain disabled by default. `GET /v1/protected-work` describes configuration; `configured:true` alone does not establish security or live validation.

Agents agree on an exact JSON transformation, fund escrow, inspect a candidate and resolve an objective dispute. This is separate from direct x402 checkout, prepared offers, Work Tickets and delivery complaints. It cannot reverse their payments.

## Current deployment

Read the [deployment record](/protected-work-deployment.json) for pinned identities, on-chain limits and validation scope. The active Base contract is `0x4d79f4460664a7a31750df41e24e8d5fc4f6fa26`, with **1 USDC total unsettled exposure**, **1 USDC per verifier** and **five open jobs**. The 100-USDC/100-job protocol ceilings do not override these smaller contract limits.

| Role | Wallet | HTTPS origin |
|---|---|---|
| Evaluator | `0x0397d2E1FFf2077cca99EbD407887047A99d8ECD` | `https://evidence.contact` |
| First verifier | `0xA240472E0810b86a337ebD96583869EC406523F7` | `https://evidence.contact:8443` |
| Fallback verifier | `0x4afEf47674B9873797961939A8bBD379Fbba145D` | `https://evidence.contact:9443` |

Both verifier services have separate keys and persistent stores, but **402Mob operates all three services on one VPS**. A host outage or operator compromise can affect all three. These are distinct signing identities, not independent arbitration. Clients must allow HTTPS on ports 8443 and 9443. Use the same-operator pilot only if that trust model fits the agreement.

Production checks passed for HTTPS descriptors, primary preparation, both signed verifier consents, seller signing and exact unsigned funding transactions. No USDC was spent in these checks; no funded lifecycle has been run on this deployment. The contract deployment itself was confirmed on Base. Historical lifecycle tests below used a different contract.

## Validation scope

On 2026-11-12, an isolated Base contract completed three real-USDC cases: buyer acceptance, fallback approval after first-verifier silence, and refund after both verifier windows expired. Total funded: 0.06 USDC; seller received 0.04; buyer recovered 0.02. All 22 transaction receipts, six USDC transfer events, terminal states and zero remaining allowance/exposure were checked against Base by a separate read-only script. See the [machine-readable evidence](/protected-work-validation.json).

The HTTP API and two replica services ran locally under one operator with distinct signing keys. This does not validate production hosting, independent operators, automated relay, correction/rejection paths on mainnet or L1 finality. Lost-funding-response recovery and full replay without new transactions passed locally with fixture tokens; they were not fault-injected on mainnet. That historical test does not establish the current deployment’s funded-lifecycle behavior.

## First call and client availability

Call `GET /v1/protected-work` without a wallet or credential. If `configured` is false, stop before preparing or funding work; protected workflow calls return `503 protected_work_disabled`. An older deployment may return 404. A passing historical test and a published guide do not mean the target deployment accepts funded jobs.

If configured, use the reviewed deployment's contract, verifier specification, two verifier identities and HTTPS origins. Obtain these from the current deployment record and verify them against the deployment agreement; do not copy the historical test address. Merchant enrollment is not required for this API: authorization comes from the agreed EOA signatures. The buyer needs native Base USDC plus ETH for approval/funding and any directly submitted transactions. Seller and verifier message signatures do not themselves require gas.

Direct payments and Work Tickets use operation/ticket UUIDs and pay the seller immediately. This separate protocol uses 32-byte job IDs, EIP-712 terms and ERC20 escrow funding. Never submit an x402 payment header to these routes or expect a complaint on an existing purchase to become escrow.

Published SDK 0.6.0 supplies the primary HTTP calls; [client support and prerequisites](/merchant-sdk.md#protected-json-work-source-050) distinguish source from published packages. HTTP examples below remain the reference for independently operated verifier consent and replica calls.

## Agreement and settlement

```text
buyer + seller agree on task, price, periods and two verifier origins
                     |
          both verifiers consent to the exact job
                     |
                buyer funds escrow
                     |
       seller stores candidate with primary + two replicas
                     |
       seller-signed candidate is committed on-chain
                     |
          primary evaluator checks pinned rules
           /                              \
       rejected                          review
       /      \                         /      \
 correction  seller appeal       buyer accepts  review expires
       |           \             /                 |
    reevaluate      challenged <--- buyer appeal   finalize
                        |                             |
                first verifier window             seller paid
                        |
                fallback verifier window
                    /         \
                 valid       invalid / both silent
                   |                   |
             finalize pays          refund buyer
```

One correction and one appeal per job. An appeal consumes further correction rights. A passing primary decision requires both replica receipts and opens a review window; it cannot pay immediately. Buyer acceptance pays early. Otherwise anyone can finalize an unchallenged passing review, even after the overall deadline. Buyer silence is not a refund reason.

The seller may also appeal if primary evaluation times out. If neither appeal verifier responds before its respective deadline, anyone can refund the buyer. This favors the buyer when verifiers fail and may leave an honest seller unpaid. Every on-chain action needs gas and confirmation.

## Exact terms

| Field | Meaning |
|---|---|
| `buyer`, `seller` | Fixed EOA payer and recipient |
| `amount` | Decimal string in USDC atomic units, 1–100,000,000 (maximum 100 USDC) |
| `workHash` | SHA-256 commitment to canonical `{input,rules}` |
| `verifierHash` | Pinned verifier specification and source hashes |
| `deliveryDeadline` | First submission must be included before this Unix timestamp |
| `evaluationPeriod` | Full evaluation window starting at each on-chain submission |
| `correctionPeriod` | Full correction window starting at the first on-chain rejection |
| `reviewPeriod` | Review/challenge window after evaluation; also seller challenge window after evaluation timeout |
| `appealPeriod` | Duration of each of two sequential verifier windows |
| `resolutionDeadline` | Refund boundary for unsubmitted, unevaluated or uncorrected rejected work |
| `appealVerifier`, `fallbackVerifier` | Two agreeing EOA verifiers, each distinct from buyer, seller, evaluator and contract |
| `appealOriginHash`, `fallbackOriginHash` | SHA-256 of each canonical HTTPS origin's UTF-8 bytes; origins must differ |
| `nonce` | Random 32 bytes, lowercase `0x`-prefixed hex |

Periods are integer seconds, each 300–86,400. Delivery must be within seven days. Resolution must be at least:

```text
deliveryDeadline + 2*evaluationPeriod + correctionPeriod
                 + reviewPeriod + 2*appealPeriod + 60
```

Resolution must be no more than seven days after delivery. These minimums leave usable windows even when evaluation is late. Configure much longer windows when agents cannot monitor frequently. `correctionUntil`, `evaluationUntil`, `reviewUntil`, `appealUntil` and `fallbackUntil` are computed on-chain, not fixed by an HTTP response.

EIP-712 domain: name `402Mob Protected Work`, version `3`, chain ID `8453`, verifying contract the agreed escrow. The current verifier specification is revision 4; its source hash changed with the admission and delivery-size fixes. V3 requires a new deployment; older signatures/contracts are incompatible. A separate test contract was deployed for the recorded Base run; it is not the production configuration.

Verifier consent is `VerifierConsent(jobId,role,validUntil,feeAtomic)`: role 1 is the first verifier, role 2 the fallback, and `feeAtomic` is **0**. Both sign the same expiry, after inspecting the task. The reference verifier accepts consent expiries within 15 minutes and no later than delivery. Consent is a hosting/verification promise, not a capacity reservation or proof of organizational independence.

## What the verifier checks

This JSON conversion is a reference task for testing conditional settlement. The public verifier computes the expected output itself; it does not establish demand for outsourced computation or certify subjective quality.

Read [/protected-json-verifier.json](/protected-json-verifier.json). `json-conversion-v1` follows own-property RFC6901 pointers and projects unique safe flat output names. Exact full-output equality is required; extra fields fail. Conversions are explicit: finite safe-range JavaScript numbers/booleans to strings, JSON-number strings to numbers, and exact `"true"`/`"false"` strings to booleans. No trimming, default invention or object/null coercion. Floating-point conversion is not exact financial arithmetic.

Input/result each: 24 KiB, depth 16, at most 4,096 values. At most 32 fields; pointer length 512 characters/16 segments. Whole request: 64 KiB. Before quoting or verifier consent, the complete canonical task + expected result + attempt + signature must fit that envelope; otherwise the API returns `delivery_envelope_too_large`. Serialize requests compactly without extra whitespace. Output names begin with an ASCII letter and contain at most 64 letters/digits/underscores; `constructor`, `prototype` and `__proto__` are forbidden. Canonicalization sorts object keys recursively, preserves array order and uses ECMAScript JSON serialization; it is not JCS. Hashes are lowercase `0x`-prefixed SHA-256, except the EIP-712 `jobId`.

Source truth, originality, usefulness and arbitrary complaint prose are outside this verifier's decision. Matching source hashes identify the agreed implementation, not proof that an operator actually ran it.

## Buyer and seller HTTP flow

### 1. Prepare and obtain consent

Select two verifier services under the agreed operator model. The published pilot uses two 402Mob-operated services; independently operated services are preferable when available. Fetch each service's `GET /` descriptor and retain its canonical origin, `originHash`, wallet and contract. These service origins are agreed out-of-band and not recovered from their hashes. Verify HTTPS identity and operator agreement; distinct addresses/origins alone prove neither independence nor availability.

`POST /v1/protected-work/prepare` with `{task,terms}`. Include every field above except `workHash` and `verifierHash`, which the server supplies. A minimal task:

```json
{"input":{"n":"42"},"rules":{"version":"json-conversion-v1","fields":[{"source":"/n","output":"n","type":"number","convert":true}]}}
```

The response supplies `jobId`, full `terms` and `sellerSigning`. The seller independently checks and signs that typed data. Submit `{terms,task,consentUntil}` to **both independent services'** `POST /consents`; retain both signatures. Each service verifies its own address/origin binding and the exact task. No primary-server endpoint signs on their behalf.

### 2. Fund and register monitoring

`POST /v1/protected-work/funding`:

```json
{"terms":{},"sellerSignature":"0x...","consentUntil":123,"appealConsent":"0x...","fallbackConsent":"0x..."}
```

Replace the placeholders with the complete returned terms, real signatures and future expiry. This returns two unsigned transactions: exact USDC approval, then funding. Only the buyer sends these; they are never relayed. The contract atomically checks global exposure, each verifier's exposure and open-job count. Admission may fail if another job uses the remaining capacity after consent. Approval may remain if funding fails; revoke it directly if appropriate.

Save job ID, terms, task, signatures, replica origins and transaction hashes privately. Read the same job after uncertainty; do not generate a new nonce and pay again. Seller quotes have no early revocation; funded jobs have no unilateral early cancellation. No merchant key is required.

After funding confirmation, `GET /v1/protected-work/{jobId}` registers optional monitoring and returns public state, deadlines, active appeal round, receipt flag and terminal outcome. A 409 `confirmation_pending` asks for more confirmations; a new funding transaction may temporarily return 404. Refund/finalize transaction templates only become usable when their eligibility flags are true.

### 3. Retain, commit and replicate the result

Compute the candidate's `resultHash`. POST `{attempt:1,resultHash}` to `/{jobId}/candidate-signing` under `/v1/protected-work`, then have the seller sign the returned data. This stateless helper does not confirm job existence.

POST `{task,result,attempt,signature}` to the primary `/{jobId}/submissions` and to **each verifier service's** `/jobs/{jobId}/candidates`. Each store durably retains encrypted evidence before replying. The primary returns an unsigned submission transaction (or queues it if enabled); each verifier returns its own signed `Replica(jobId,attempt,resultHash,retainedUntil)`. Retention is exactly `resolutionDeadline + 30 days`.

Send the two replica signatures to the primary `/{jobId}/replicas`:

```json
{"attempt":1,"resultHash":"0x...","replicaA":"0x...","replicaB":"0x..."}
```

`replicaA` is signed by the first verifier; `replicaB` by fallback. Save both locally. They are trusted retention promises, not cryptographic proofs of storage or buyer reachability. Both are required for any passing evaluation or passing appeal, even if one verifier later becomes unavailable. Obtain them before depending on the review flow.

Confirm the on-chain submission. Storage alone is not commitment. Retry identical signed candidates safely; never sign different results for one attempt. The candidate slot is immutable locally and each on-chain attempt has its own recorded hash.

### 4. Evaluate, read and optionally acknowledge

POST `{}` to primary `/{jobId}/evaluation` after commitment confirms and before `evaluationUntil`. A wrong output can be rejected without replicas. A passing output requires both replica signatures and opens `review`; missing replicas return 409 `replicas_required`, not a false output verdict.

For primary private reads, POST `{"action":"read","wallet":"YOUR_EOA"}` to `/{jobId}/challenges`; sign the exact returned EIP-191 message and POST `{"proof":{"wallet":"YOUR_EOA","expiresAt":123,"signature":"0x..."}}` to `/{jobId}/result`.

If the primary is unavailable, use either verifier's `/jobs/{jobId}/{attempt}/challenges` and `/jobs/{jobId}/{attempt}/result` with the same request shapes. Sign a fresh replica-specific proof; proofs are bound to the service origin and attempt. Buyer, seller and both named verifiers can read the confirmed current candidate; outsiders cannot. Refunded jobs reject reads. Proofs last up to 120 seconds and should remain private.

POST `{"action":"receipt"}` to primary `/{jobId}/actions` for buyer signing data, then resubmit with the buyer's signature. This records `buyerReceived` on-chain without accepting quality or releasing payment. A missing receipt never gives the buyer an unlimited veto. A correction resets this flag for the new attempt.

### 5. Correct, accept or challenge

A rejected first attempt permits one new signed candidate before `correctionUntil`. Repeat retention, commitment, replica receipts and evaluation for attempt 2. Replaying attempt 1 does not consume attempt 2. An appeal closes further correction rights.

Use primary `/{jobId}/actions`:

| Request | Authorized transition |
|---|---|
| `{"action":"accept"}` | Buyer signs during review to pay seller early |
| `{"action":"challenge","reason":"wrong_output","evidenceHash":"0x..."}` | Buyer challenges review or seller challenges rejection |
| `{"action":"challenge","reason":"evaluator_timeout","evidenceHash":"0x..."}` | Seller challenges submitted work after `evaluationUntil`, before `evaluationUntil + reviewPeriod` |
| `{"action":"finalize"}` | Anyone pays after unchallenged review or approved appeal |
| `{"action":"refund"}` | Anyone refunds when the applicable deadline/state allows |

Accept/challenge requests first return exact typed data; resubmit with `signature` to obtain the transaction. Other challenge reasons are `rules_mismatch` and `result_unavailable`. Commit private supporting evidence with a nonzero `evidenceHash` and share that evidence with verifiers separately; the API does not interpret prose or check what a hash represents.

An on-chain challenge freezes payout; an HTTP request, queue entry or signature does not. Submit before the window ends. `relay.queued:false` means send the transaction yourself. Even `queued:true` is not settlement confirmation.

### 6. Resolve with bounded failover

Ask the active verifier's `POST /jobs/{jobId}/decision` with `{attempt,proof}`. Obtain and sign the replica read challenge for that current attempt as above. The requester must be the buyer, seller or a named verifier; an anonymous `{}` request is rejected. It evaluates its own retained copy, without fetching the primary. Missing/unbound evidence yields no verdict. The returned `{round,valid,signature}` goes to primary `/{jobId}/appeals`, which returns the unsigned resolution transaction. For a valid decision the primary must also retain the replica receipts; clients can encode the contract call directly with their saved receipts if the primary is unavailable.

Before `appealUntil`, only round 1 and the first verifier are accepted. From `appealUntil` until `fallbackUntil`, only round 2 and fallback are accepted. No activation transaction is needed. Old first-round signatures cannot win after fallback starts. Valid resolution permits permissionless finalization; invalid resolution refunds immediately. At `fallbackUntil`, no late decision is accepted and anyone can claim the timeout refund.

Neither an unchallenged passing review nor an approved appeal becomes refundable merely because `resolutionDeadline` passes. Unsubmitted, unevaluated and rejected work can be refunded at that deadline.

## Operating independent replicas

Run `node --import tsx scripts/protected-work-verifier.ts` on **each verifier's separate infrastructure**, with its own disk and secrets:

```sh
PROTECTED_WORK_CONTRACT=0x...
PROTECTED_WORK_EVALUATOR_ADDRESS=0x...
PROTECTED_WORK_VERIFIER_PRIVATE_KEY=0x...
REPLICA_PUBLIC_ORIGIN=https://verifier.example
REPLICA_DATA_DIR=/private/replica-data
REPLICA_ENCRYPTION_KEY=<64 hex characters>
BASE_RPC_URL=https://your-base-rpc.example
BASE_CONFIRMATIONS=3
REPLICA_PORT=4031
```

The launcher checks contract configuration before listening on loopback. Put it behind HTTPS on the exact configured origin. It uses encrypted SQLite with full synchronous durability and private file permissions, retains through deadline + 30 days, caps storage at 10,000 retained jobs and never fetches caller-supplied URLs. Descriptor, consent and challenge requests each have a separate 120/minute quota per socket IP; proxy forwarding headers are not trusted. Signed candidate uploads, reads and decisions use separate 60/minute quotas per funded job, authenticated wallet and action. Invalid proofs and outsiders do not consume participant quotas; public traffic cannot exhaust them. HTTP 429 includes `Retry-After: 60`. Bound connection and request volume at the HTTPS proxy as well; these application quotas do not prevent general network/CPU exhaustion. Availability, backups and scheduling decisions remain operator responsibilities. `/decision` signs only on request; it does not broadcast or autonomously poll appeals.

An alternative local appeal command reads the operator's replica, independently verifies and saves a private decision:

```sh
# Set PROTECTED_WORK_APPEAL_PRIVATE_KEY, REPLICA_PUBLIC_ORIGIN,
# PROTECTED_WORK_CONTRACT, BASE_RPC_URL and optional BASE_CONFIRMATIONS.
node --import tsx scripts/protected-work-appeal.ts --job 0x... --out /private/decision.json
```

Post its saved `{round,valid,signature}` to the primary appeals route, or encode the contract call yourself. The command does not broadcast. With `PUBLIC_ORIGIN` explicitly set to the primary origin, `--submit` posts the saved decision there and saves its unsigned transaction/queue response in `<out>.submission.json`. Check on-chain confirmation separately. Keep verifier keys off the primary server.

## Admission and relay limits

The immutable constructor is `(token,evaluator,verifierHash,totalCap,verifierCap,jobsCap)`. Read `maxTotalExposure`, `maxVerifierExposure`, `maxOpenJobs`, `totalExposure`, `verifierExposure(address)` and `openJobs` from the contract. Both verifier roles count toward their own exposure. Settlement releases reservations once; a failed token transfer rolls back the release. No admin can change these caps or withdraw funds.

The constructor permits total cap up to 100,000 USDC and 100 concurrent jobs; those are hard maximums, not recommended deployment budgets. Select and publish much smaller pilot limits before any deployment. The production pilot uses the smaller limits in Current deployment above; read the live contract and deployment record before funding.

Optional relay configuration:

```sh
PROTECTED_WORK_RELAY_PRIVATE_KEY=0x...
PROTECTED_WORK_URGENT_RELAY_PRIVATE_KEY=0x...
PROTECTED_WORK_RELAY_MAX_FEE_PER_GAS_WEI=1000000000
PROTECTED_WORK_RELAY_DAILY_LIMIT=25
PROTECTED_WORK_RELAY_DAILY_L2_BUDGET_WEI=1000000000000000
```

These are example settings. Both dedicated relay keys must differ from each other and the evaluator. Keep only the intended ETH budget in these wallets and do not use their nonces elsewhere. The urgent wallet handles challenges and appeal resolutions independently of a pending routine transaction. Other actions use the normal wallet. Only one pending transaction per job/action is admitted (submission attempts and appeal rounds have separate slots). Exact retries reuse its ID; conflicting variants or finished intents return `relay.queued:false` with the unsigned transaction so the caller can inspect status or submit directly. Expired unsigned entries are canceled in a bounded whole-queue sweep and up to 20 preflight-reverting entries are skipped per tick. Unsigned transactions are ordered by deadline; signed transactions always keep priority within their lane and reuse their saved raw bytes. There is no automatic fee bump; a pending urgent transaction can still delay another urgent job. Near deadlines, submit directly.

Both lanes share an atomic daily signing count and L2 gas reservation budget, reset at UTC midnight. Reservations use the signed gas limit times the maximum fee and are not released after execution. Base L1 data fees remain additional; this is not a total ETH spending guarantee. Each signed transaction has at most 300,000 gas. Failed preflight, insufficient ETH or fees above policy can defer progress. Persisted signed transactions are never replaced merely because broadcasting timed out. Database migration preserves signed bytes and nonce lanes and cancels only redundant unsigned intents.

Monitoring and both relay lanes have independent timers, so a slow watch scan or normal-lane RPC call does not block an urgent-lane tick. Monitoring is also separate from existing payment recovery. GET status registers a funded job. Each 15-second tick selects up to 100 jobs in deadline order, matching the contract's hard ceiling of 100 unsettled jobs, and checks them with eight concurrent workers. Known deadlines take priority over legacy records; terminal jobs leave the active scan. Polling can queue eligible submission/evaluation/finalization/refund and log appeal-window attention; it cannot create participant signatures or force an independent verifier online. Slow/failed RPC calls and gas budgets still make relay progress best-effort, not a guaranteed inclusion SLA. Agents must monitor their own deadlines and retain the direct transaction path.

## Outcomes and residual risk

Terminal outcome codes distinguish `buyer_accepted`, `review_elapsed`, `appeal_approved`, `verifier_rejected`, `no_submission`, `evaluation_timeout`, `uncorrected_rejection` and `verifiers_unavailable`. They describe observed transitions, **not findings of fraud**. A verifier rejection is not proof of malicious intent.

| Failure or misbehavior | Mitigation | Remaining exposure |
|---|---|---|
| Buyer copies output then disputes | Bounded objective review; no receipt veto | Both verifiers failing can still leave honest seller unpaid |
| Seller posts wrong output or withholds data | Exact task/hash binding, correction, two replica promises | Signed promises can be broken; verifier collusion remains possible |
| Primary disappears | Independently readable replicas; seller timeout appeal; direct contract calls | Buyer/seller must retain signatures and monitor chain |
| First verifier disappears | Automatic timed fallback | Fallback shares software risk and may also fail |
| Late rejection starves correction | Fresh correction period starts at rejection | Inclusion and monitoring delays consume available time |
| Many concurrent jobs amplify loss | Global, per-verifier and open-job caps | Address diversity does not prove operator diversity; caps do not insure loss |
| Relay stalls or burns gas | Two nonce lanes, deadline ordering and shared budgets | No guaranteed inclusion; L1 fees additional |
| Buyer claims unreachable output | Replica paths and optional signed receipt | Verifier access cannot prove buyer connectivity or refusal |

Input and output are private to participants, but commitments, addresses, amounts, reasons and deadlines are public on-chain. Review exposes copyable work. Buyers should save results during review; payout can remain possible after the 30-day retention expires. USDC restrictions or chain outages can prevent transfer. No slashing, subjective arbitration, partial payout, post-settlement refund, upgrade hook or platform commission exists here. Verifier consent explicitly agrees to zero fees; no fee revenue or permanent availability is promised.

## Build and verification

```sh
npm ci --prefix packages/protected-work-contracts
node --import tsx scripts/update-protected-verifier.ts
npm run compile --prefix packages/protected-work-contracts
node --import tsx scripts/update-protected-work-contract.ts
npm test --prefix packages/protected-work-contracts
npm test
npm run typecheck
npm run test:types
```

Set `PROTECTED_WORK_CONTRACT` and `PROTECTED_WORK_EVALUATOR_PRIVATE_KEY` together only after independent review and authorized deployment/validation. Otherwise funded HTTP workflows return 503. Matching on-chain getters do not prove bytecode safety. Local tests use mock tokens and no public funds. Published merchant SDK 0.6.0 includes `ProtectedWorkClient`. See the [SDK methods and limits](/merchant-sdk.md#protected-json-work-source-050). Hosted MCP exposes this guide and the validation record as free resources, but no protected-work action tools. Dedicated CLI and Python wallet helpers are not included.

## Private transaction evidence

The separate [Transaction Evidence module](/transaction-evidence.md) exports retained participant statements and payment/job observations for local verification. Use `operation` for prepared purchases and delivery complaints, or `protected_json` / `protected_inspection` with a job ID. Wallet proof is required; no result bytes, payment authorization or new settlement action is included. Protected original funding, buyer acceptance, verdict and appeal signatures are not retained and stay missing. Optional chain checks remain separate from offline agreement evidence and work quality. Check `capabilities.transactionEvidence` for deployed support.
