# Autonomous Agent Workflows & Crypto Rails: A Solo Founder's Playbook

**A curated research pack with ready-to-use templates for deploying revenue-generating AI agents on IMD, x402, and crypto rails.**

*Edition date: 2026-10-21. Prices, addresses, and statistics were checked against the primary sources cited inline on that date. Anything time-sensitive is flagged.*

---

## How to read this pack (epistemic legend)

This is a research product, so every claim is labeled by how we know it:

- **[FACT]** — stated by a primary source (official docs, the protocol's own site, an on-chain address). The source is linked next to the claim.
- **[REPORTED]** — stated by a secondary source (press, explainers, exchange blogs). Plausible but not independently verified here.
- **[INFERENCE]** — our conclusion from facts; the reasoning is given so you can check it.
- **[UNCERTAIN]** — likely to change, disputed, or not confirmable from available sources.

Section 13 collects the open questions this pack could **not** answer. If a claim matters to money you are about to spend, re-verify it against the linked source first — all three rails below ship changes faster than any PDF can track.

---

# Page 1 — Executive summary

Three pieces of infrastructure matured in 2025–2026 that together let one person ship a paid, autonomous AI agent in days:

1. **x402** — an open HTTP-native payment standard (revived HTTP status code 402) that lets any API endpoint charge stablecoins per request, with no accounts, API keys, or checkout. Launched by Coinbase in May 2025, now governed by the x402 Foundation under the Linux Foundation. **[FACT]** — [x402.org](https://www.x402.org/), [Coinbase launch post](https://www.coinbase.com/developer-platform/discover/launches/x402). As of 2026-10-21, x402.org's live counters showed ~75.4M transactions and ~$24.2M volume in the trailing 30 days, with ~22K sellers. **[FACT, time-sensitive]** — [x402.org](https://www.x402.org/).

2. **ERC-8004 ("Trustless Agents")** — a draft Ethereum standard giving agents portable on-chain identity (ERC-721), reputation, and validation registries, authored by contributors from MetaMask, the Ethereum Foundation, Google, and Coinbase. **[FACT, draft status — may change]** — [Ethereum Magicians thread](https://ethereum-magicians.org/t/erc-8004-trustless-agents/25098).

3. **IMD / IdentityMD** — a live agent network on Ethereum where 2,000 NFT-gated agent seats do paid software work (Solidity, websites, research, oracle answers), coordinated by a control plane and paid over x402 in the IMD token at a flat **0.5 IMD per paid action**. **[FACT]** — [imd.fun/docs](https://imd.fun/docs/). You can be a *buyer* (pay 0.5 IMD, get a contract/site/report/oracle answer) or a *seller* (run a seat and earn from launches and accepted work).

**The thesis of this playbook [INFERENCE]:** a solo founder's fastest path to a revenue-generating agent is (a) wrap your agent's capability as an x402-paywalled HTTP endpoint (hours of work, zero payment ops), (b) use IMD as both an outsourced engineering/research swarm and a distribution surface, and (c) optionally anchor your agent's identity in ERC-8004 so its track record is portable. Each pattern below comes with copy-paste templates verified against the primary docs on the edition date.

**What this pack contains:** the landscape and how each rail works (pages 2–6), seven orchestration patterns (pages 7–8), copy-paste templates for selling and buying over x402 and IMD (pages 9–12), a cost-optimization checklist with current model pricing (page 13), a 5-day shipping plan and the weekly-update subscription mechanism (page 14), and the full facts/uncertainty ledger and sources (page 15).

---

# Page 2 — Why now: the agent-payments stack, in plain terms

**The problem crypto rails solve for agents [INFERENCE from the facts below]:** agents cannot pass KYC, hold credit cards, or click through Stripe Checkout. Traditional payment rails assume a human at signup. Machine-to-machine commerce needs payments that are (1) request-scoped, (2) programmatic end-to-end, and (3) chargeback-free.

**What changed:**

- **HTTP 402 went live.** The HTTP spec reserved status code `402 Payment Required` decades ago; x402 finally standardized its use: server replies 402 with machine-readable payment requirements, client signs a stablecoin payment, retries, gets the resource. No account, no API key, no prepaid credits. **[FACT]** — [Coinbase x402 docs: How x402 works](https://docs.cdp.coinbase.com/x402/core-concepts/http-402), [x402.org](https://www.x402.org/).
- **Gasless stablecoin transfers.** x402's default EVM scheme builds on EIP-3009 (`transferWithAuthorization`) / Permit2-style signatures, so a *facilitator* can submit the transaction and pay gas; the buyer only signs. USDC is the default asset; the protocol itself charges zero fees. **[FACT]** — [Coinbase x402 FAQ](https://docs.cdp.coinbase.com/x402/support/faq), [x402.org](https://www.x402.org/).
- **Agent identity became an ERC.** ERC-8004 (draft, first proposed August 2025) defines three singleton registries per chain — Identity (ERC-721 pointing to an agent metadata file), Reputation (bounded feedback attestations), Validation (independent re-verification records) — so an agent's history follows it across platforms. **[FACT, draft]** — [Ethereum Magicians](https://ethereum-magicians.org/t/erc-8004-trustless-agents/25098), [Monad's ERC-8004 guide](https://docs.monad.xyz/guides/erc-8004).
- **A working agent labor market appeared.** IdentityMD routes paid jobs to ERC-8004-registered agent seats, meters every attempt, independently re-runs results before accepting them, and records reviews on-chain. **[FACT]** — [imd.fun/docs](https://imd.fun/docs/); agent descriptions on the [ERC-8004 registry](https://8004agents.ai/ethereum/agent/52100). Bankless reported ~380 of 2,000 seats enrolled and 43,800+ accepted jobs as of late September 2026. **[REPORTED, time-sensitive]** — [Bankless](https://www.bankless.com/read/inside-imd-ethereum-s-new-ai-swarm-experiment).

**What did *not* change [INFERENCE]:** you still need a capability someone will pay for. These rails collapse payment and distribution friction; they do not create demand. The patterns in this pack assume you already know what your agent does; they tell you how to charge for it, how to buy inputs for it, and how to run it unattended.

---

# Page 3 — Rail 1: x402 in depth

## The flow **[FACT]** — [docs.cdp.coinbase.com/x402](https://docs.cdp.coinbase.com/x402/core-concepts/http-402)

1. Client requests a protected endpoint with no payment attached.
2. Server responds `402 Payment Required` with a `PAYMENT-REQUIRED` header: base64-encoded JSON listing one or more `accepts` options (scheme, network, asset, amount, payTo).
3. Client picks an option, signs the payment payload (EIP-3009/Permit2 typed data for EVM; an SVM scheme exists for Solana), and retries the same request with a `PAYMENT-SIGNATURE` header.
4. Server passes the payload to a **facilitator** (e.g., the Coinbase CDP Facilitator) to verify and settle; on success it serves the resource. The facilitator submits the on-chain transfer and absorbs gas.

Key properties, all **[FACT]** per the sources above and [x402.org](https://www.x402.org/):

- **Zero protocol fees**; only network fees apply (and facilitators may price their service — see uncertainty #4, page 15).
- **Network-agnostic:** `eip155:*` chains use the EVM scheme, `solana:*` the SVM scheme; the standard is extensible to other rails.
- **Instant, final settlement:** no chargebacks.
- **Any EIP-3009 token works; USDC is the default.** Dollar-denominated prices like `"$0.01"` auto-resolve to the network's default USDC.

## The packages **[FACT]** — [Seller quickstart](https://docs.cdp.coinbase.com/x402/quickstart-for-sellers)

- **Server (TypeScript, Node 22+):** `@x402/express` (+ `@x402/core`, `@x402/evm`, `@x402/svm`, `@coinbase/cdp-sdk`). Hono and Next.js examples live in the `coinbase/cdp-sdk` repo.
- **Server (Python 3.10+):** `x402[evm,svm,fastapi]` + `cdp-sdk`, with `PaymentMiddlewareASGI` for FastAPI.
- **Buyer:** `@x402/core/client` with `ExactEvmScheme` (used verbatim in the IMD template on page 10); Coinbase also documents an `@x402/axios` wrapper and an MCP-server bridge so Claude Desktop tools can pay per call — [MCP server guide](https://docs.cdp.coinbase.com/x402/mcp-server). **[FACT]**
- **Agent wallets with spend controls:** CDP's `CdpX402Client` supports `maxAmountPerPayment`, `maxCumulativeSpend` over rolling windows, and allowlists of networks/assets/payees. **[FACT]** — [Coinbase x402 docs]. Use these — an autonomous buyer without spend caps is an unbounded liability. **[INFERENCE]**

## Discovery

Coinbase operates "the Bazaar," a catalog of x402-payable HTTP routes and MCP tools keyed by server URL and tool name. **[FACT]** — [Coinbase x402 docs](https://docs.cdp.coinbase.com/x402/mcp-server). Listing there is free distribution for a paid endpoint. **[INFERENCE]** How much buyer traffic the Bazaar actually drives is unknown — see page 15.

---

# Page 4 — Rail 2: IMD / IdentityMD in depth

## What it is

IdentityMD is a community-owned agent network: 2,000 `identity.md` NFTs each control one "seat." A holder activates a seat by registering the NFT as an ERC-8004 agent, installing the open-source worker client (tarball from `Identity-md/worker` GitHub releases, SHA256-verified, exposing an `imd` CLI), and plugging in their own Claude or Codex subscription. Work never reaches agents directly: the **control plane** plans each paid request and offers parts to seats; every attempt is metered and results are independently re-run before they count. **[FACT]** — [imd.fun/docs](https://imd.fun/docs/), [8004agents.ai registry entries](https://8004agents.ai/ethereum/agent/52100). The project's history (Fren Pet on Base in 2023 → $FP → $VIBE → $IMD rebrand in May 2026) is **[REPORTED]** — [KuCoin](https://www.kucoin.com/blog/ph-imd-token-community-owned-ai-agents), [Bankless](https://www.bankless.com/read/inside-imd-ethereum-s-new-ai-swarm-experiment).

## The economics a buyer sees **[FACT]** — [imd.fun/docs](https://imd.fun/docs/)

- Payment token: **IMD** on Ethereum mainnet, `0xd34a99bc0f67ae1bbd63c660e6d0b0dd03e263b7`.
- Every paid action costs a flat **0.5 IMD** (`500000000000000000` atomic units): `job.open`, `job.continue`, `launch.open`, `workflow.open`, `oracle.request`, and `schedule.create`/`schedule.topup` (per run).
- Payments ride **x402 with Permit2**; the server pays gas. Quotes last 600 seconds. Wallet must be an EOA or EIP-7702 account — contract wallets (Safe) are rejected.
- Rate limits: 300 requests and 30 quotes per minute, per IP and per token.
- `GET /requests/capabilities` returns the live price, supported chains, and limits — **always read it at runtime instead of hardcoding this page. [INFERENCE from the route's existence]**

## What 0.5 IMD buys **[FACT]** — [imd.fun/docs](https://imd.fun/docs/)

| Action | You get |
|---|---|
| `job.open` | A planned, executed, reviewed job: code into a GitHub repo, research reports, audits (public at `GET /jobs/:id/report.md`), sites pinned to IPFS under an ENS name |
| `job.continue` | The next version of a project your wallet paid for, delivered as a fast-forward PR |
| `launch.open` | A job ending in a contract launch (Sepolia default; Ethereum mainnet and Robinhood Chain supported) |
| `workflow.open` | Contracts → adversarial review → attested deployment → website built against the live addresses |
| `oracle.request` | A typed on-chain question answered by a panel (2–100 agents, exact-match quorum), returning an EIP-712 attestation |
| `schedule.create` | A cadence (ISO duration or cron) that re-opens a job or oracle question automatically — 0.5 IMD per run |

Launch economics: launched tokens route **10% to the swarm** (2% to accepted workers, 8% across connected seats via Merkle distributor) and **90% to the requester** (pool seed + remainder); trading carries a **1.25% fee — 1% to the paying wallet, 0.25% to the network**. **[FACT]** — [imd.fun/docs](https://imd.fun/docs/). That 1%-of-volume kickback to the requester is itself a revenue primitive for founders who launch products with tokens attached. **[INFERENCE]**

## Scale signals

The explorer ([explorer.imd.fun](https://explorer.imd.fun/)) showed ~5,500 jobs, ~1,100 agents, and ~8,700 oracle heartbeats around the edition date; Bankless reported an ~86% acceptance rate on submissions. **[REPORTED, time-sensitive]**. Treat throughput and quality as variable — see page 15.

---

# Page 5 — Rail 3: ERC-8004, and how the rails compose

## ERC-8004 in one page

Three minimal singleton registries per chain **[FACT, draft]** — [Ethereum Magicians](https://ethereum-magicians.org/t/erc-8004-trustless-agents/25098):

1. **Identity Registry** — mints an ERC-721 whose token URI resolves to the agent's metadata file (capabilities, endpoints, keys). Anchor of the design.
2. **Reputation Registry** — bounded feedback attestations referencing an identity token.
3. **Validation Registry** — records of independent re-verification requests and results.

It builds on ERC-721, EIP-155 chain identifiers, and EIP-712/ERC-1271 signatures, and extends Google's A2A protocol with an on-chain trust layer. Reference contracts are deployed on multiple chains (e.g., Monad, Avalanche C-Chain have guides). **[FACT, draft]** — sources above plus [Monad docs](https://docs.monad.xyz/guides/erc-8004). **Status caveat [UNCERTAIN]:** the ERC is a *Draft*; interfaces may still change, and an [arXiv empirical study](https://arxiv.org/pdf/2606.26028) questions how much trust the current ecosystem's reputation data actually carries. Do not build load-bearing trust decisions on raw 8004 reputation scores yet.

## How the three rails compose **[INFERENCE, with the composition points themselves FACTs]**

```
            ┌────────────────────────────────────────────────┐
            │ YOUR AGENT (the capability you sell)           │
            └────────┬───────────────────────┬───────────────┘
            sells via│                       │buys via
                     ▼                       ▼
      x402 paywall on your API      IMD paid actions (0.5 IMD each)
      (USDC per request,            — jobs, launches, workflows,
       zero protocol fees)            oracle answers, schedules
                     │                       │
                     └──────────┬────────────┘
                                ▼
                  ERC-8004 identity + reputation
             (portable track record for your agent;
              IMD seats are already 8004-registered)
```

- IMD *is already* an x402 seller: its paid routes answer 402 challenges you settle with `@x402/core` + `ExactEvmScheme`. **[FACT]** — [imd.fun/docs](https://imd.fun/docs/). So one buyer-side payment stack covers both IMD and any other x402 API.
- IMD seats register under ERC-8004, so the standard already has a production consumer. **[FACT]** — [8004agents.ai](https://8004agents.ai/ethereum/agent/52100).
- Your own paid endpoint and IMD purchases can share one EOA — but give an autonomous buyer a *separate, capped* wallet. **[INFERENCE; see spend controls, page 3.]**

---

# Page 6 — The IMD payment flow, demystified (read before the templates)

IMD's x402 integration has one sharp edge that stock x402 clients miss: **two signatures, not one**. **[FACT]** — [imd.fun/docs](https://imd.fun/docs/):

1. **The Permit2 payment signature** — what any x402 client produces (`createPaymentPayload`).
2. **A second EIP-712 `QuoteApproval` signature** over the quote *and the SHA-256 hash of the exact payment payload bytes*, binding your payment to one specific quoted action (domain `IdentityMD Paid Action`, version `1`).

The full paid flow:

```
POST /requests/quote            → get an order id + quote (600 s validity)
POST /requests/:id/submit       → first call returns 402 challenge
   (sign Permit2 payment + QuoteApproval, resend with PAYMENT-SIGNATURE header)
GET  /requests/:id              → poll: quoted → payment_pending →
                                  admission_pending → admitted
```

Hard-won rules, all **[FACT]** from the docs:

- The payment payload is parsed **strictly**: any unknown key at any depth fails `invalid_payment_shape`. The SDK-attached `extensions` field is the usual culprit — strip it (the template on page 10 does).
- `paymentHash` = SHA-256 of **canonical JSON** (sorted keys, no whitespace) of the exact header payload. `invalid_quote_approval` almost always means a one-byte canonicalization mismatch.
- Auth is a **self-generated bearer token** (`openssl rand -hex 32`) — no signup. Keep it: it reads your orders later.
- Retries are safe: resubmitting the same bytes reuses the order and **never double-charges**; reuse your `requestKey` to retry the same quote. `410 quote_expired` → re-quote with a fresh `requestKey`.
- `POST /requests/check` is a **free dry-run** returning `blockers` and the `plan`. Always call it before paying — especially before the on-chain intake path, where a refused body is a spent payment.
- Docs pin `@x402/core` / `@x402/evm` at **2.28.0**; newer majors may change interfaces. **[FACT, time-sensitive]**

**No-API path [FACT]:** the `Intakev2` contract (`0xa43e6f75ee006411f79ac1c84120606c2330de82` on Ethereum, Robinhood Chain, Sepolia) sells the same actions fully on-chain — your contract calls `request(action, body, callback, asset, amount)` and receives results via callback (IPFS URI + keccak-256 hash for jobs; EIP-712 attestation for oracles). No refunds; the payer address gets owner roles and continuation rights. Template on page 12.

---

# Page 7 — Orchestration patterns I: structuring agent work

These patterns are substrate-agnostic; each is mapped to its concrete IMD/x402 expression. The IMD mappings are **[FACT]** (its API encodes them); the general pattern guidance is **[INFERENCE]** from standard agent-engineering practice.

## Pattern 1: Single skill, single shot
One capability, one request, one deliverable. *IMD mapping:* `job.open` with `skill` or `template: "single"`. *Use when:* the task fits in one reviewed unit (a report, one contract, a logo). *Avoid when:* acceptance depends on multiple distinct competencies — reviewers judge the whole, and one weak part sinks it.

## Pattern 2: Pipeline (chain)
Steps run in sequence; each consumes the prior's output. *IMD mapping:* `steps` (1–6) with `shape: "chain"`; or the built-in templates `impl_tests`, `impl_tests_review`. *Use when:* later steps genuinely need earlier outputs (implement → test → review). *Cost note:* on IMD a 6-step chain still costs 0.5 IMD total per job — the flat price makes richer plans free at the margin. **[FACT]**

## Pattern 3: Fan-out / join (parallel map-reduce)
Independent branches run concurrently, then a join step merges. *IMD mapping:* `shape: "fan_out_join"`; or `template: "multi_contract"`. The oracle is the purest form: `panelSize` 2–100 agents answer independently, `quorum` is an **exact-match count, not a majority** — a disagreeing panel resolves nothing and the fee is spent. **[FACT]** Size quorum accordingly: for a volatile metric, pin `definitions` and set `toleranceBps` rather than demanding exact agreement. **[INFERENCE]**

## Pattern 4: DAG with convergence
Arbitrary dependencies, branches converging to one final step (IMD requires convergence). *IMD mapping:* `shape: "dag"` with `key`/`dependsOn` per step. *Use when:* two workstreams (e.g., contracts + content) must merge into one deliverable. IMD's `workflow.open` is a productized DAG: contracts → independent `adversarial-review` that all contract branches reach → attested deployment → frontend built against live addresses → IPFS + ENS. **[FACT]**

## Pattern 5: Evaluator–optimizer (generate → verify → repair)
A producer's output is checked by an independent verifier; failures loop back. IMD builds this in: every submission is independently re-run before acceptance, steps-planned launches automatically get a 4-auditor + judge panel (never name those steps yourself — the plane adds them), and audit reports go public at `/jobs/:id/report.md`. **[FACT]** *Your own stack:* run the verifier as a separate agent with its own context — self-review by the producing agent catches far less. **[INFERENCE]**

---

# Page 8 — Orchestration patterns II: autonomy over time

## Pattern 6: Versioned continuation (long-lived project memory)
Iterate on a deliverable across sessions without re-sending context. *IMD mapping:* `job.continue` with `parentJobId` (= `project.head`). The plane hands workers the project history as `.imd/reads/project.md` plus live launch addresses; delivery is a fast-forward PR. Only the original paying wallet may continue (`403 payer_not_owner`), the parent must be the newest completed version, and `repoUrl`/`onchain`/`economics` are refused — the plane picks the starting point and nothing redeploys. **[FACT]** *General lesson [INFERENCE]:* keep project memory in the artifact (repo + reads file), not in your orchestrator's conversation history — it survives restarts and model swaps.

## Pattern 7: Scheduled autonomy (the standing order)
A frozen request re-executed on a cadence — the closest thing to an employee you can buy for 0.5 IMD a run. *IMD mapping:* `schedule.create`: `action` (`job.open` or `oracle.request`), frozen `input`, `cadence` (`{every:"P7D"}` ISO duration ≤ 1 year, or `{cron, tz}`), `runs` (1–1,000,000), optional `continue: true` so each job chains off the prior run. Floors: ≥ 10 min between oracle questions, ≥ 30 min between jobs. Only runs that actually open work spend a run; unused runs are **not refunded**. Anyone can `schedule.topup` a paused schedule. **[FACT]** This is the engine behind the weekly-update subscription on page 14.

## Choosing a pattern — decision table **[INFERENCE]**

| Situation | Pattern | IMD expression |
|---|---|---|
| One deliverable, one competency | 1 | `job.open` + `skill` |
| Build + test + review | 2 | `template: "impl_tests_review"` |
| Need consensus on a fact | 3 | `oracle.request`, tuned `panelSize`/`quorum` |
| Contracts and site must ship together | 4 | `workflow.open` |
| High-stakes code | 5 | launch audit panel (automatic) / `template: "audit"` |
| Product that evolves weekly | 6 + 7 | `schedule.create` with `continue: true` |

**Anti-patterns [INFERENCE]:** (1) orchestrating in your head — if the cadence lives in your calendar, it isn't autonomous; (2) paying before `POST /requests/check` passes; (3) exact-match quorums on noisy metrics; (4) one mega-objective instead of steps — IMD refuses an objective with no `skill`/`template`/`steps`/`contracts` anyway. **[FACT for the refusal]**

---

# Page 9 — Template 1: Sell your agent's output over x402 (the revenue side)

The fastest revenue loop: your agent already produces something (reports, signals, images, structured data). Put it behind a paywalled endpoint. ~30 lines, verified against the [seller quickstart](https://docs.cdp.coinbase.com/x402/quickstart-for-sellers) on 2026-10-21. **[FACT for the code shape; adjust versions at install time]**

```bash
npm install express @coinbase/cdp-sdk @x402/core @x402/evm @x402/extensions @x402/express
export CDP_API_KEY_ID="..."        # authenticates verify/settle with the CDP Facilitator
export CDP_API_KEY_SECRET="..."    # (does NOT control where funds go)
export X402_PAY_TO="0xYourReceivingAddress"   # where USDC lands — yours
```

```typescript
// server.ts — an agent-generated report, $0.05 per request, Base
import { createX402Server } from "@coinbase/cdp-sdk/x402";
import { paymentMiddlewareFromHTTPServer } from "@x402/express";
import express from "express";

const app = express();
const payTo = process.env.X402_PAY_TO as `0x${string}`;

const server = await createX402Server({
  environment: "development",            // "production" when you flip to mainnet
  payToConfig: { type: "address", evm: payTo },
  routes: {
    "GET /report": {
      price: "$0.05",                    // auto-resolves to the network's USDC
      networks: ["eip155:84532"],        // Base Sepolia; 8453 = Base mainnet
      description: "Daily agent-generated market structure report",
    },
  },
});

app.use(paymentMiddlewareFromHTTPServer(server));
app.get("/report", async (_req, res) => {
  res.json({ report: await generateReport() });  // your agent's work
});
app.listen(8402);
```

**Verify:** `curl -i http://localhost:8402/report` with no payment must return `402` with a `PAYMENT-REQUIRED` header. **[FACT]**

**Checklist before charging real money [INFERENCE unless noted]:**
- [ ] One EVM `payTo` covers all EVM networks; Solana needs its own address via `payToConfig.solana` **[FACT]**
- [ ] Switch `environment: "production"` and re-verify `payTo` works on mainnet **[FACT]**
- [ ] Price ≥ your marginal inference cost × 3 (page 13 shows how to compute it)
- [ ] Idempotency: a paid retry must not bill twice on your side — key work by request
- [ ] List the endpoint in the Bazaar for discovery **[FACT that it exists; traffic value UNCERTAIN]**
- Python version (FastAPI + `PaymentMiddlewareASGI`) in the quickstart if your stack is Python. **[FACT]**

---

# Page 10 — Template 2: Buy from IMD programmatically (the two-signature client)

This is the copy-paste that stock x402 examples get wrong. Verbatim-faithful to [imd.fun/docs](https://imd.fun/docs/) (edition date). Pin `@x402/core` and `@x402/evm` **2.28.0** per the docs. **[FACT]**

```bash
export IMD_API="https://api.imd.fun"
export IMD_PAID_TOKEN=$(openssl rand -hex 32)   # self-made auth; KEEP IT — it reads your orders
# 0) FREE dry-run first — a refused body costs nothing here:
curl --fail-with-body -X POST "$IMD_API/requests/check" \
  -H 'Content-Type: application/json' --data-binary @quote.json
# 1) Quote (order id comes back; quotes last 600 s):
export REQUEST_KEY=$(uuidgen | tr 'A-F' 'a-f')
curl --fail-with-body -X POST "$IMD_API/requests/quote" \
  -H "Authorization: Bearer $IMD_PAID_TOKEN" -H 'Content-Type: application/json' \
  --data-binary @quote.json
```

```js
// pay.js — settle the quote: Permit2 payment + QuoteApproval (the IMD-specific second signature)
import { x402Client } from '@x402/core/client';
import { encodePaymentSignatureHeader } from '@x402/core/http';
import { ExactEvmScheme } from '@x402/evm/exact/client';
import { sha256, stringToBytes } from 'viem';

// canonical JSON: sorted keys, no whitespace — paymentHash depends on these exact bytes
const canon = (v) => v === null ? 'null' : Array.isArray(v) ? `[${v.map(canon).join(',')}]`
  : typeof v === 'object' ? `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canon(v[k])}`).join(',')}}`
  : JSON.stringify(v);

const url = `${IMD_API}/requests/${orderId}/submit`;
const auth = { Authorization: `Bearer ${token}` };

// 1. bare submit returns the 402 challenge (quote, requesterScopeHash, resourceUrl)
const ch = await (await fetch(url, { method: 'POST', headers: auth })).json();
const req = ch.accepts[0];

// 2. the Permit2 payment — and STRIP `extensions`, or you get invalid_payment_shape
const client = x402Client.fromConfig({ schemes: [{ network: req.network, client: new ExactEvmScheme(signer) }] });
const { extensions, ...generated } = await client.createPaymentPayload({ x402Version: 2, resource: ch.resource, accepts: [req] });
const payment = JSON.parse(JSON.stringify({ ...generated, accepted: req }));

// 3. QuoteApproval binds this exact payment to this exact quote
const q = ch.quote;
const quoteSignature = await signer.signTypedData({
  domain: { name: 'IdentityMD Paid Action', version: '1', chainId: Number(q.payment.network.slice(7)) },
  primaryType: 'QuoteApproval',
  types: { QuoteApproval: [
    { name: 'resource', type: 'string' }, { name: 'requesterScopeHash', type: 'bytes32' },
    { name: 'quoteId', type: 'string' }, { name: 'quoteHash', type: 'bytes32' },
    { name: 'paymentHash', type: 'bytes32' }, { name: 'action', type: 'string' },
    { name: 'asset', type: 'address' }, { name: 'amount', type: 'uint256' },
    { name: 'payTo', type: 'address' }, { name: 'expiresAt', type: 'uint256' },
  ] },
  message: {
    resource: ch.resourceUrl, requesterScopeHash: `0x${ch.requesterScopeHash}`,
    quoteId: q.id, quoteHash: `0x${q.quoteHash}`,
    paymentHash: sha256(stringToBytes(canon(payment))),
    action: q.action, asset: q.payment.asset, amount: BigInt(q.payment.amount),
    payTo: q.payment.payTo, expiresAt: BigInt(q.expiresAt),
  },
});

// 4. submit; lost response? send the SAME bytes again — never double-charges
await fetch(url, { method: 'POST',
  headers: { ...auth, 'Content-Type': 'application/json', 'PAYMENT-SIGNATURE': encodePaymentSignatureHeader(payment) },
  body: JSON.stringify({ quoteSignature }) });
// then poll GET /requests/:id until status === 'admitted'  (reading never charges)
```

**Prerequisites [FACT]:** wallet holds IMD (`0xd34a…63b7`, Ethereum mainnet) with a Permit2 allowance; EOA or EIP-7702 only. **Debug map [FACT]:** `invalid_payment_shape` → unknown key (usually `extensions`); `invalid_quote_approval` → canonicalization byte mismatch; `410` → re-quote with new `requestKey`; `422` → body invalid, nothing charged.

---

# Page 11 — Templates 3–5: job bodies that get accepted

All field rules **[FACT]** — [imd.fun/docs](https://imd.fun/docs/). Objectives are 1–8,000 chars (4,000 for research); an objective **alone is refused** — add `skill`, `template`, `steps`, or `contracts`. Named outputs must land under `artifacts/`.

### Template 3 — Research report (`job.open`, the product you are reading was commissioned this way)

```json
{
  "action": "job.open",
  "requestKey": "<uuid>",
  "body": {
    "template": "research",
    "objective": "Research <question>. Use primary sources for technical claims, distinguish facts from inference and uncertainty, link every claim to a source.",
    "outputs": [
      { "name": "report", "path": "artifacts/report.md", "mediaType": "text/markdown" }
    ],
    "github": true
  }
}
```

### Template 4 — Implement + test + review a contract, then continue it

```json
{
  "action": "job.open",
  "requestKey": "<uuid>",
  "body": {
    "template": "impl_tests_review",
    "objective": "An ERC-20 vesting vault: linear vesting, cliff, owner-revocable grants. Solidity ^0.8.24, Foundry tests for cliff boundaries and revocation.",
    "github": true
  }
}
```

Next week's iteration — `job.continue` (same paying wallet only; `parentJobId` = `project.head` from `GET /jobs/:id`):

```json
{
  "action": "job.continue",
  "requestKey": "<uuid>",
  "body": {
    "parentJobId": "<project.head>",
    "template": "impl_tests_review",
    "objective": "Add per-grant pausability; keep storage layout; extend the test suite."
  }
}
```

(`repoUrl`, `onchain`, `economics` are **refused** on continuations — the plane picks the starting point.)

### Template 5 — Oracle question with sane consensus settings

```json
{
  "action": "oracle.request",
  "requestKey": "<uuid>",
  "body": {
    "v": 1,
    "question": "Did contract 0x… emit at least one Transfer event in the window?",
    "chainId": 1,
    "window": { "fromBlock": 23500000, "toBlock": 23507000 },
    "answerType": "bool",
    "panelSize": 5,
    "quorum": 4,
    "validForSeconds": 86400
  }
}
```

Tuning rules **[FACT]**: `quorum` is an exact-match count; `toBlock` must be ≥ 5 behind head; absolute block windows make the `questionHash` pre-computable (needed for the on-chain consumer, page 12); use `toleranceBps` + pinned `definitions` for numeric answers; `evidence: "chain"` is the default. Payment buys the question and panel, **not a guaranteed answer** — a disagreeing panel resolves nothing. Budget for occasional `disagreed`. **[FACT + INFERENCE]**

---

# Page 12 — Template 6: Fully on-chain consumer (contract pays, contract receives)

For an agent product that is *itself a contract* — no API token, no server. All addresses/interfaces **[FACT]** — [imd.fun/docs](https://imd.fun/docs/).

- `Intakev2`: `0xa43e6f75ee006411f79ac1c84120606c2330de82` (Ethereum, Robinhood Chain, Sepolia — Sepolia sells oracle questions only, in imdTEST `0x56bcf2a5f47710649a4091219ef0b56e2d1b58bf`).
- Action ids are right-padded `bytes32` strings: `job.open@job-1`, `oracle.request@oracle-1`, etc.
- Fixed callback selectors: `onResult 0x4374622e`, `onOracleResult 0x510379c7`, `onFailure 0x5a0df71e`.

```solidity
// Sketch of the docs' IntakeClient pattern (MIT-licensed in the docs) — key security moves:
contract MyOracleConsumer {
    address public immutable INTAKE; // Intakev2: 0xa43e6f75ee006411f79ac1c84120606c2330de82
    mapping(bytes32 => bytes32) public pendingQuestionHash; // requestId => keccak256(canonical question JSON)

    constructor(address intake) { INTAKE = intake; }

    function ask(bytes calldata body, bytes32 questionHash) external {
        // 1) off-chain: POST /requests/check FIRST — a refused body on-chain is a SPENT payment, no refunds
        // 2) one-time ERC-20 approve of IMD to the intake (IMD has no permit)
        bytes32 id = IIntake(INTAKE).requestWithFailure(
            "oracle.request@oracle-1", body,
            Callback(address(this), 0x510379c7), 0x5a0df71e,
            IMD_TOKEN, 0.5 ether);
        pendingQuestionHash[id] = questionHash;
    }

    function onOracleResult(bytes32 id, Attestation calldata a, bytes calldata sig) external {
        require(msg.sender == INTAKE, "only intake");          // 1. only the intake may call
        require(pendingQuestionHash[id] != 0, "unknown id");   // 2. only my own unsettled request
        require(a.questionHash == pendingQuestionHash[id]);    // 3. bind answer to MY question
        delete pendingQuestionHash[id];
        // ... act on the attested answer
    }
}
```

Non-negotiables from the docs **[FACT]**: the payer is the **calling contract** (`msg.sender`, not `tx.origin`) and receives owner roles / continuation rights; an oracle signature proves an answer was signed *for your contract*, **not that you asked the question** — hence the `questionHash` binding (keccak-256 of compact key-sorted JSON of `answerType, chainId, definitions, evidence(panel only), head, question, v, window`); callback gas is 200,000 (1M on Sepolia) and a reverting callback never blocks the result (readable via `GET /intake/:chainId/:txHash`); intake reads 3 blocks behind head on Ethereum. Cross-chain delivery exists via `deliver:{chainId,target,selector}` and `IntakeDeliveryv1` (`0xce0e…ccb`) — verify `msg.sender` there too. And the docs' own words: **"It is not a price feed."**

---

# Page 13 — Cost optimization checklist

An autonomous agent's unit economics = inference cost + rail cost. Both are controllable.

## Inference costs (your biggest line item)

Current Claude API pricing (checked 2026-10-21 — **[FACT, time-sensitive]**, [platform.claude.com pricing](https://platform.claude.com/docs/en/about-claude/pricing)):

| Model | Input /MTok | Output /MTok | Cache hit /MTok |
|---|---|---|---|
| Claude Opus 5.5 | $4 | $20 | $0.20 (0.05×) |
| Claude Sonnet 5.5 | $2 | $10 | $0.10 (0.05×) |
| Claude Haiku 5.5 (≤100K prompt) | $0.10 | $0.50 | $0.01 |

- [ ] **Tier your models [INFERENCE]:** route classification/extraction/formatting to Haiku 5.5 (40× cheaper than Opus on input), reasoning-heavy planning to Opus/Sonnet. Most agent loops are >80% cheap steps.
- [ ] **Prompt caching [FACT]:** cache hits cost 0.05× base input on Opus 5.5/Sonnet 5.5 (0.1× on older models); 5-min cache writes cost 1.25× base. A stable system prompt + tool definitions block is nearly free after the first call.
- [ ] **Batch API [FACT]:** 50% off input *and* output for async workloads — your nightly/weekly regeneration jobs (page 14) should all be batch.
- [ ] **Multipliers stack [FACT]:** batch + cache discounts combine.
- [ ] **Watch the tokenizer [FACT]:** Claude 4.7+ models tokenize ~30% more tokens for the same text than Sonnet 4.6-and-earlier — compare *dollars per task*, not tokens.

## Rail costs

- [ ] **x402 selling:** protocol fee is zero **[FACT]**; your costs are facilitator terms (verify current CDP Facilitator pricing — **[UNCERTAIN]**, see page 15) and nothing else. No chargebacks means no reserve.
- [ ] **IMD buying [all FACT]:** `POST /requests/check` is free — never pay to discover a validation error. HTTP intake: `422` charges nothing; on-chain intake: a refused body **is a spent payment** — always `check` first. Retries reuse orders and never double-charge. Reading (`GET /requests/:id`, `/jobs/:id/result`) never charges. A 6-step DAG costs the same 0.5 IMD as a one-liner — pack plans, not jobs. Schedules: runs that open no work are consumed without refund — set cadence floors ≥ the real change rate of what you're watching.
- [ ] **Oracle sizing [INFERENCE from FACT quorum semantics]:** `panelSize: 5, quorum: 4` tolerates one dissenter; `quorum == panelSize` on a noisy metric is a donation.
- [ ] **IMD token exposure [INFERENCE]:** your cost per action is 0.5 IMD × IMD's dollar price, which floats (the token hit a reported $39M market-cap ATH in Sept 2026 — **[REPORTED]**, [KuCoin](https://www.kucoin.com/blog/ph-imd-token-community-owned-ai-agents)). Hold a small working balance, not a treasury, unless you *want* the exposure.

## Operational

- [ ] Spend-capped wallet for any autonomous buyer (`maxAmountPerPayment`, `maxCumulativeSpend`, payee allowlists via CDP's client). **[FACT that the controls exist]**
- [ ] Log every quote → payment → result triple; reconcile weekly against `GET /requests/paid-by/:address`. **[FACT the route exists]**
- [ ] Alert on `payment_failed` / `expired` / `disagreed` rates, not just errors.

---

# Page 14 — Ship in 5 days + the weekly-update subscription

## The 5-day plan **[INFERENCE — a sequencing of FACT-based steps]**

- **Day 1 — capability.** Pick one output someone already pays humans for (a report, a feed, an audit summary). Write the agent that produces it once, locally. Tier models per page 13.
- **Day 2 — revenue rail.** Template 1: x402-paywall the endpoint on Base Sepolia at a test price. Verify the bare `402`. Flip `environment: "production"` only after a full paid round-trip.
- **Day 3 — supply rail.** Fund an EOA with ~5 IMD + Permit2 allowance. Run Template 2 end-to-end with a cheap `job.open` (Template 3). You now buy work and sell work programmatically.
- **Day 4 — autonomy.** Wrap the loop: schedule (IMD `schedule.create`, or your own cron) → generate → verify (Pattern 5) → publish behind the paywall. Add spend caps and the reconciliation log.
- **Day 5 — distribution + identity.** List your endpoint in the Bazaar; consider an ERC-8004 identity mint so the agent's record is portable **[draft-status caveat, page 5]**. Announce; watch `paid-by` and iterate with `job.continue`.

## The weekly-update subscription (for readers of this pack)

This pack ages. The subscription mechanism *is Template 7* — you run it yourself, on-rails, no email list required:

```json
{
  "action": "schedule.create",
  "requestKey": "<uuid>",
  "body": {
    "action": "job.open",
    "label": "agent-rails-weekly",
    "cadence": { "cron": "0 9 * * MON", "tz": "UTC" },
    "runs": 12,
    "continue": true,
    "input": {
      "template": "research",
      "objective": "Weekly delta report on agent payment rails: changes to x402 (docs.cdp.coinbase.com, x402.org), IMD routes/pricing (imd.fun/docs, read /requests/capabilities), ERC-8004 status, and Claude API pricing. Only report diffs from the prior edition with sources; flag breaking changes to the two-signature IMD payment flow first.",
      "outputs": [{ "name": "report", "path": "artifacts/report.md", "mediaType": "text/markdown" }],
      "github": true
    }
  }
}
```

Mechanics **[FACT]**: 0.5 IMD per run (12 weekly runs ≈ 6 IMD upfront), `continue: true` chains each edition off the last so the researcher sees prior editions, jobs respect the ≥ 30-min floor trivially at weekly cadence, and anyone — including a reader who isn't the original payer — can extend a lapsed schedule with `schedule.topup`. Delivery lands in the schedule's GitHub repo each Monday. If you'd rather not touch IMD, the degraded alternative is your own cron + the Batch API (50% off) regenerating the diff — you lose independent re-running and on-chain receipts. **[INFERENCE]**

---

# Page 15 — The ledger: facts, inferences, uncertainties, open questions

## Core facts this pack rests on (each cited where used)
x402 flow/fees/packages ([Coinbase docs](https://docs.cdp.coinbase.com/x402/quickstart-for-sellers), [x402.org](https://www.x402.org/)); IMD pricing, routes, two-signature flow, intake contracts, schedules, launch economics ([imd.fun/docs](https://imd.fun/docs/)); ERC-8004 registry design ([Ethereum Magicians](https://ethereum-magicians.org/t/erc-8004-trustless-agents/25098)); Claude pricing/caching/batch ([platform.claude.com](https://platform.claude.com/docs/en/about-claude/pricing)).

## Main inferences (ours, check the reasoning)
The composition thesis (page 5); model-tiering and pricing-floor heuristics (pages 9, 13); the pattern decision table (page 8); "hold working balance, not treasury" (page 13); the 5-day sequencing (page 14).

## Known uncertainties
1. **ERC-8004 is a Draft.** Interfaces and registry addresses may change; reputation data quality is questioned by an [empirical study](https://arxiv.org/pdf/2606.26028). **[UNCERTAIN]**
2. **All volume/adoption statistics are snapshots** (x402's 30-day counters; IMD explorer counts; Bankless's 380 seats / 43,800 jobs; the $39M IMD ATH) and were already moving at press time. **[REPORTED/time-sensitive]**
3. **SDK versions drift.** IMD pins `@x402/core`/`@x402/evm` 2.28.0; Coinbase's packages evolve. Re-read both quickstarts before `npm install`. **[FACT that pins exist; future compatibility UNCERTAIN]**
4. **Facilitator pricing.** The x402 *protocol* charges zero fees, but whether and how the CDP Facilitator (or alternatives) bills for verify/settle at your scale was not confirmed from the pages reviewed. Check [CDP docs](https://docs.cdp.coinbase.com/x402/support/faq) before projecting margins. **[UNCERTAIN]**
5. **IMD output quality variance.** The ~86% acceptance rate is reported, aggregate, and seat-dependent (seats run on heterogeneous holder subscriptions). Your jobs' acceptance and quality may differ; audits at `/jobs/:id/report.md` are the public evidence trail. **[REPORTED + INFERENCE]**
6. **IMD token price risk** directly scales your per-action cost. **[FACT that price floats; magnitude UNCERTAIN]**

## Questions this research could not answer
- How much organic buyer traffic the Bazaar actually routes to a newly listed x402 endpoint (no public per-listing data found).
- Median wall-clock latency from `job.open` to `admitted`-and-delivered on IMD under current load (the explorer shows throughput, not per-job latency distributions).
- Legal/tax treatment of per-request stablecoin micro-revenue for a solo founder in any given jurisdiction — out of scope; get professional advice.
- The x402 Foundation's roadmap for non-crypto rails ("extensible to traditional payment rails" is stated, but no shipped non-crypto scheme was found).

## Sources
- x402: [x402.org](https://www.x402.org/) · [How x402 works](https://docs.cdp.coinbase.com/x402/core-concepts/http-402) · [Seller quickstart](https://docs.cdp.coinbase.com/x402/quickstart-for-sellers) · [FAQ](https://docs.cdp.coinbase.com/x402/support/faq) · [MCP server](https://docs.cdp.coinbase.com/x402/mcp-server) · [Launch post](https://www.coinbase.com/developer-platform/discover/launches/x402) · [Wikipedia](https://en.wikipedia.org/wiki/X402)
- IMD: [imd.fun/docs](https://imd.fun/docs/) · [explorer.imd.fun](https://explorer.imd.fun/) · [8004agents.ai #202](https://8004agents.ai/ethereum/agent/52100) · [Bankless](https://www.bankless.com/read/inside-imd-ethereum-s-new-ai-swarm-experiment) · [KuCoin](https://www.kucoin.com/blog/ph-imd-token-community-owned-ai-agents) · [TokenPost](https://www.tokenpost.com/news/technology/24260)
- ERC-8004: [Ethereum Magicians](https://ethereum-magicians.org/t/erc-8004-trustless-agents/25098) · [Monad guide](https://docs.monad.xyz/guides/erc-8004) · [Allium](https://www.allium.so/blog/onchain-ai-identity-what-erc-8004-unlocks-for-agent-infrastructure/) · [Eco explainer](https://eco.com/support/en/articles/13221214-what-is-erc-8004-the-ethereum-standard-enabling-trustless-ai-agents) · [arXiv study](https://arxiv.org/pdf/2606.26028)
- Inference pricing: [Claude API pricing](https://platform.claude.com/docs/en/about-claude/pricing)

*Nothing in this pack is financial, legal, or tax advice. Code templates are provided as-is; test on testnets (Base Sepolia, Sepolia) with small amounts before mainnet.*
