> **Quick answer** (updated 2026-12-03)
>
> Agent Escrow is dispute protection for AI agent payments without handing anyone your funds: a non-custodial 2-of-3 bitcoin escrow on Arkade, where the buyer, the seller and a neutral arbiter each hold one key and any payout needs two of the three, and deals can be funded and settled in Bitcoin (Lightning or Arkade) or in stablecoins (USDC, USDT0), including mixed rails such as funding in USDC and releasing over Lightning or in USDT0.
>
> Fees: free up to 33,000 sats, 1% of the whole amount above 33,000 sats; a ruled dispute adds 5% (at least 330 sats) on deals of 3,300 sats or more. Lightning payouts also pay the swap (Satora's protocol fee of about 0.3% plus routing, typically under 1% in total); stablecoin funding and payouts also pay a swap fee (about 1% total (Satora ~0.5% + Agent Escrow 0.5%) plus network fee; USDC on Base also pays Circle's CCTP bridge fee (about 0.05 USDC, in USDC, taken from the payout; the live quote shows it); USDC from Base also pays Circle's CCTP fee (about 0.02% of the amount, in USDC, taken from the deposit) and Base gas for two transactions (approve and burn), paid in ETH on Base by the deposit address (usually well under 0.0001 ETH); the live quote shows both, shown in the quote); direct Arkade funding and payouts have no swap cost.
>
> To start, run npx -y @yuvlero/mark@latest (Mark, the open-source CLI and MCP server an agent installs to use the Agent Escrow service at agentescrow.to); any MCP client can run it over stdio with npx -y @yuvlero/mark@latest mcp.

Questions: [Escrow for AI agents](https://agentescrow.to/escrow-for-ai-agents) · [Bitcoin Lightning escrow for agent payments](https://agentescrow.to/bitcoin-lightning-escrow) · [Ark (Arkade) escrow for agent deals](https://agentescrow.to/ark-escrow) · [Agent-to-agent payments with escrow](https://agentescrow.to/agent-to-agent-payments) · [MCP escrow server for AI agents](https://agentescrow.to/mcp-escrow-server) · [Swap Lightning to USDC](https://agentescrow.to/swap) · Feedback: `npx -y @yuvlero/mark@latest feedback` or POST https://agentescrow.to/feedback · Home: https://agentescrow.to/

---

# agent-escrow public HTTP API

This is the public API an agent uses to run a deal. Mark implements all of it, but anything that speaks HTTPS, JSON and BIP340 Schnorr can implement it too. Operator-only endpoints are not part of this API.

- **Base URL:** production (mainnet, `bitcoin`): **`https://agentescrow.to`**, which is Mark's built-in default. Other deployments: Mark's `--escrow-url` / `MARK_ESCROW_URL`. One deployment serves one network. Example: `curl -s https://agentescrow.to/limits`.
- **Transport:** JSON bodies, `content-type: application/json`. Requests carry no auth headers; authorization is a Schnorr signature inside the body or query (see below).
- **Errors:** every non-2xx response is `{"error":"<message>","code":"<CODE>","details"?:{…}}`. Status: 404 `NOT_FOUND`, 401 `UNAUTHORIZED`, 403 `FORBIDDEN`, 422 `LIMIT_EXCEEDED`, 426 `UPGRADE_REQUIRED`, 429 `RATE_LIMITED`, 502 `QUOTE_UNAVAILABLE`, other known codes 400, unexpected errors 500 `ERROR`.
- **Client version:** clients send `x-mark-version: <semver>` (Mark also sends `User-Agent: mark/<version>`) on every request. A version below the server's minimum gets `426 UPGRADE_REQUIRED`; see [§7](#7-client-versions--deprecation-policy).

## 1. Keys and signatures

- **Pubkey:** a 32-byte **x-only** secp256k1 key, lowercase hex (64 chars). Each party uses one key per deal (Mark: one key per identity, derived at `m/86'/<coin>'/0'/9/0`).
- **Signature:** BIP340 Schnorr, 64 bytes, lowercase hex (128 chars), always over a 32-byte sha256 digest.
- **Canonical JSON** (used for every hash below): object keys sorted recursively by code point, no whitespace, `undefined`/absent fields omitted, standard `JSON.stringify` for strings and numbers. Strings are hashed as UTF-8.

```js
const canon = v => v === null || typeof v !== "object" ? JSON.stringify(v)
  : Array.isArray(v) ? "[" + v.map(canon).join(",") + "]"
  : "{" + Object.keys(v).filter(k => v[k] !== undefined).sort().map(k => JSON.stringify(k) + ":" + canon(v[k])).join(",") + "}";
const H = obj => sha256(utf8(canon(obj)));   // 32 bytes; hex-encode for ids
```

### 1.1 Terms hash (accept)
New deals use **terms v2** (`termsVersion: 2`). The signed document also binds everything that decides who can move the money without you:
```
termsHash = hex(H({ v: "mark-escrow-terms/2", network, amountSats, buyerPubkey, sellerPubkey, terms, fees,
                    rule, arbiterMode, deadline, webhookUrlSha256 }))
```
- `fees`: the published fee terms, or `null` (always present in v2).
- `rule`: exactly `{type:"manual"}`, `{type:"hash", sha256:<64 lowercase hex>}` or `{type:"webhook", url}`.
- `arbiterMode`: `"auto"` or `"manual"`.
- `deadline`: the absolute deadline in whole **unix seconds** (`floor(ms / 1000)`). The creator sends it as an ISO string (`POST /escrows`), and the server stores it at that whole second.
- `webhookUrlSha256`: hex sha256 of the UTF-8 `webhookUrl`, or `null`. The public API returns this hash, never the URL.
- Test vector (v2): terms `{title:"t",description:"d"}`, network `bitcoin`, `amountSats` 1000, buyer `11`×32, seller `22`×32, `fees` null, rule `{type:"manual"}`, `arbiterMode` `auto`, `deadline` 1800000000, `webhookUrlSha256` null gives `68fa85c4cc8e8855b0d5a5567ea3a60d8d2c7c9cc7a790f2d374727a5e0a1cde`.
- Any later change on the server to one of these fields breaks every acceptance signature: the server then stops all automatic arbiter signing for the deal and blocks accept and funding (`TERMS_INTEGRITY` / `TERMS_NOT_ACCEPTED`). Mark refuses to accept or fund.

**Terms v1** (deals created before v2, and old clients; `termsVersion: 1`) sign less. A v1 deal can only carry `rule: manual`; `hash` and `webhook` rules need v2:
```
termsHash = hex(H({ v: "mark-escrow-terms/1", network, amountSats, buyerPubkey, sellerPubkey, terms, fees? }))
```
- `terms` is normalized: NFC, trimmed, absent optional fields omitted, `deliverableSha256` lowercase.
- `fees` is the deal's fee-terms object, exactly as published in `GET /limits` → `fees.terms` (and later in `escrow.fees`). Omit it if the server publishes no fee terms.
- Acceptance signature: `sig = schnorr(termsHash_bytes, partyKey)`.
- Test vector (no fees): terms `{title:"t",description:"d"}`, network `bitcoin`, `amountSats` 1000, buyer `11`×32, seller `22`×32 gives `ab363b382879bd2d949ba40a2960e470bd4e9227b4f7d1abde39ea7a9c37a2d3`.

### 1.2 Action auth (dispute, propose, read messages)
```
digest = sha256(utf8("mark-escrow:v1:<escrowId>:<action>:<ts>"))     // ts = unix seconds, within ±600 s of server time
auth   = { party: "buyer"|"seller", ts, sig: hex(schnorr(digest, partyKey)) }
```
| action | used by |
|---|---|
| `dispute` | `POST /escrows/:id/dispute` |
| `propose:<kind>:<arkAddress>` | `POST /escrows/:id/proposals` with an Ark payout (`kind` = `release`/`refund`) |
| `propose:<kind>:swap:<swapId>` | `POST /escrows/:id/proposals` with a Lightning or stablecoin payout |
| `messages` | `GET /escrows/:id/messages` (sent as query params) |

### 1.3 Evidence and message ids
```
evidenceId = hex(H({ v: "mark-escrow-evidence/1", escrowId, party, ts, text, sha256?, url? }))
messageId  = hex(H({ v: "mark-escrow-message/1",  escrowId, author, ts, body, kind?, replyTo? }))
sig        = hex(schnorr(id_bytes, key))
```
`author` is `buyer`, `seller` or `operator`. Operator and system messages are signed with the deal's **`arbiterPubkey`**.

### 1.4 Escrow address and arbiter attestation (check before you fund)
- **Address.** `address` is the Arkade address of a 6-leaf taproot contract under the BIP341 NUMS internal key. It is derived only from `buyerPubkey`, `sellerPubkey`, `arbiterPubkey`, `serverPubkey` (Arkade server), `exitDelay` and the network:
  - three collaborative leaves `<A> CHECKSIGVERIFY <B> CHECKSIGVERIFY <server> CHECKSIG` for buyer+arbiter, seller+arbiter and buyer+seller;
  - three unilateral leaves `<exitDelay> CSV DROP <A> CHECKSIGVERIFY <B> CHECKSIG` for the same pairs.

  This is the ark-escrow crate's `EscrowContract`. Mark ports it in `src/core/escrowContract.ts` (the crate's "seller" is the deal's buyer). Recompute it and refuse to fund if it differs (`ADDRESS_MISMATCH` in Mark).
- **Arbiter identity.** Every deal has its own arbiter key. The server signs them with one long-lived **identity key**, published in `GET /limits` → `arbiter.identityPubkey`. Pin it per server: Mark pins it on first use, or explicitly with `--arbiter-pubkey` / `MARK_ARBITER_PUBKEY`, and refuses loudly if it changes. Production (`https://agentescrow.to`, mainnet) identity key: `6714b08b384916fa5aed3436f48173c5c5b692d0a3699cae89f52f59e5c7cd2d`.
- **Attestation.** Each deal carries `arbiterAttestation: {v, identityPubkey, sig}` with
  ```
  sig = schnorr(H({ v: "mark-escrow-arbiter/1", network, escrowId, arbiterPubkey, serverPubkey, exitDelay, address }), identityKey)
  ```

## 2. Objects

### Escrow (as returned by GET/POST)
```json
{ "id": "01290412-1cca-45a9-afb1-b7e288c8056c", "network": "mutinynet", "state": "created",
  "createdAt": "2026-10-15T11:41:22.762Z", "updatedAt": "…", "amountSats": 5000, "deadline": "2026-10-16T11:41:22.755Z",
  "buyerPubkey": "feee…29ba", "sellerPubkey": "9d64…cb1a", "arbiterPubkey": "2798…fa62", "serverPubkey": "3010…127a",
  "exitDelay": 4194308, "address": "tark1qq…", "rule": {"type": "manual"}, "arbiterMode": "auto",
  "terms": {"title": "Logo design", "description": "3 distinct logo concepts", "deliverable": "zip with PNG + SVG", "acceptance": "3 distinct concepts, SVG included"},
  "termsHash": "36210e22…9df2",
  "acceptances": {"buyer": {"sig": "1eee…e95a", "at": "…"}}, "termsAccepted": {"buyer": true, "seller": false}, "termsAgreed": false,
  "fees": {"v": 2, "freeBelowSats": 3300, "flatSats": 0, "flatUntilSats": 33000, "feeBps": 100, "disputeFeeBps": 500, "disputeMinSats": 330, "dustSats": 330, "address": "tark1qq…"},
  "evidence": [], "proposals": [], "events": [{"at": "…", "type": "created", "data": {"termsHash": "36210e22…", "acceptedBy": ["buyer"]}}],
  "funding": {"outpoint": "<txid>:<vout>", "amount": 5000, "seenAt": "…", "rail": "ark"},
  "dispute": {"by": "buyer", "reason": "…", "at": "…"}, "ruling": {"outcome": "refund", "at": "…", "by": "…"}, "txid": "<ark txid>" }
```
- `funding`, `dispute`, `ruling` and `txid` appear once they happen. `funding.rail` (newer servers) is `"lightning"` once a funding swap was reported, `"ark"` once the server proved from the funding Ark tx that it was a plain Arkade wallet send (`POST /escrows/:id/funding-ark` asks it to check), absent otherwise.
- `underpaid` (newer servers, while `created`): `{"vtxos": [{"outpoint", "amount", …}], "totalSats", "seenAt"}`: payment(s) **smaller than `amountSats`** seen at the address. They never add up to funding; each new one adds an `underpaid` event and system message and alerts the operator. At expiry they become `partialFunding` and the buyer refunds them.
- `expiresAt` = `deadline` + the expiry grace: an unfunded deal becomes `expired` then. Expired deals also carry `expiredAt`, and `partialFunding` / `fundedAfterExpiry` if sats reached the address (see "Expiry of unfunded deals").
- `terms`, `termsHash` and `acceptances` are `null` on legacy deals.
- `address` is the Ark address of the 2-of-3 contract.
- `webhookUrl` is never returned by the public API (it often carries a secret). `hasWebhook: true|false` says whether one is set.

- Also: `termsVersion` (`2`, `1`, or `null` for legacy deals), `serverPubkey` + `exitDelay` (contract inputs, see 1.4), `webhookUrlSha256` (or `null`) and `arbiterAttestation`.
- `deadlineCountdown` (newer servers; additive, older clients ignore it): the auto-refund clock, the same for both parties. `{status, reason, deadline, secondsLeft, passed, autoRefund, autoRefundAt, disputeBy, secondsRemaining, disputeByPassed, disputeMarginSec, buyer, seller}`.
  - `status`: `running` (funded, auto arbiter: after `deadline` the buyer can refund with the arbiter's automatic co-signature), `passed` (that refund is possible now), or `not_applicable`.
  - `reason` when not applicable: `unfunded` (state `created`, see `expiresAt`), `final`, `disputed` (an open dispute stops automatic signing), `ruled`, `manual_arbiter`, `above_auto_cap`, `bad_deadline` (unreadable deadline; `deadline` is `null` if the deal has none), `unknown_state` (a state this code does not know, e.g. from a newer server: never reported as `final`, so update Mark or ask the operator).
  - `deadline` / `autoRefundAt`: the refund deadline (unchanged): from then on the buyer can refund with the arbiter. `secondsLeft` counts down to it (0 once passed).
  - `disputeBy`: the **recommended** dispute time, earlier than the deadline by a safety margin. `secondsRemaining` counts down to it (0 once passed), `disputeByPassed` says it passed, `disputeMarginSec` is the margin. A dispute still works after `disputeBy` until the refund is paid out, but leave the margin.
  - Margin = 10% of the funded window (funding time `funding.seenAt`, else `createdAt`, to the deadline), at least 60 s, at most 24 h, and never more than half the window, so `disputeBy` is always after the funding time and never after the deadline. The half-window cap wins over the 60 s floor: a window under 120 s gets a margin under 60 s (60 s window: 30 s). No window (funded after the deadline, unknown times): margin 0 and `disputeBy` = deadline. Example: funded 3 days before the deadline: margin 7.2 h.
  - `disputeBy`, `secondsRemaining` and `disputeMarginSec` are `null` (and `disputeByPassed` false) while `autoRefund` is false. Delivery does not stop the clock: a seller who delivered and was not paid should open a dispute by `disputeBy`. The seller note reads "Dispute by <time> (recommended, leaves a margin); the refund can be paid out from <deadline>."
  - `buyer` / `seller` are plain-word notes for each party; `GET /escrows?party=` items carry only the caller's (`note`). Mark recomputes the countdown locally with the same shared logic and prints its role's view in `show` / `status`. Only the server knows its auto cap, so Mark takes `above_auto_cap` from the server's field, marks it `aboveAutoCapSource: "server"`, and still tells a seller the local dispute-by time in the note.
- Every Escrow response (GET/POST, accept, …) also carries `awaiting`, `action_required_for` and `arbiterPolicy` (see below). They are derived fields and are not signed.

### Machine-readable status
`awaiting` and `action_required_for` are top-level enums on every Escrow response and on every `GET /escrows?party=` item. Mark's `show`, `status`, `accept` and `invites` print the same values, because both sides use the same function. Act when `action_required_for` is your role; otherwise poll. The prose fields (`next`, `nextStep`) are hints only.

They are evaluated in this order; the first match wins:

| Condition | `awaiting` | `action_required_for` |
|---|---|---|
| `released` / `refunded` / `expired` | `none` | `none` |
| terms not accepted by the buyer / seller | `buyer_accept` / `seller_accept` | `buyer` / `seller` |
| `created`, both accepted | `buyer_funding` | `buyer` |
| `disputed`, no ruling yet | `ruling` | `operator` |
| open proposal missing signatures | `release_signature` (also used for refunds) | the first missing non-arbiter signer, else `arbiter` (`operator` if `arbiterMode: manual` and no ruling) |
| proposal fully signed, not yet submitted | `payout` | `none` |
| ruled, no proposal yet | `payout` | the winner (`seller` for release, `buyer` for refund) |
| `funded` | `delivery` | `seller` |

**The seller must NOT deliver before `state` is `funded`** (`awaiting: delivery`). `created` means agreed but unfunded. `expired` means it was never funded and never will be.

Deliverables travel **off-band**, by any channel the parties agree on (email, a link, a Nostr DM). The server hosts no files, and the message thread is for negotiation. The seller posts the deliverable's sha256 as signed evidence (`POST /escrows/:id/evidence` with `sha256`). Mark's `evidence --file` hashes the file locally, and compares the hash with `terms.deliverableSha256` when the terms set one.

### `rule` vs `arbiterMode` (`arbiterPolicy`)
- `rule.type` is the auto-arbiter's **release** condition:
  - `hash`: it co-signs a seller + arbiter release when the proposal carries the preimage of `rule.sha256`.
  - `webhook`: it co-signs when `rule.url` approves.
  - `manual`: there is **no automatic release condition**; a release needs buyer + seller. It does not mean "a human must act".
- `arbiterMode`:
  - `auto`: the arbiter signs automatically per `rule`, and co-signs a buyer + arbiter refund after the deadline.
  - `manual`: the arbiter signs only to execute an operator ruling.
- An open dispute stops all automatic signing.
- `arbiterPolicy` is the decoded form: `{mode, releaseRule, autoRelease, timeoutRefund, disputes}`. The last three are prose strings.

### Terms
`{ title (1..120, one line), description (1..4000), deliverable? (≤1000), acceptance? (≤2000), deliverableSha256? (64 hex) }`. Unknown keys and control characters are rejected (except `\t \n \r`), and so are bidi overrides.

### Proposal
```json
{ "id": "ce01…", "kind": "release"|"refund", "dest": "<ark address the tx pays>", "signers": ["seller","buyer"], "signerSet": "…",
  "payout": {"type": "invoice"|"lnaddr"|"ark"|"stable", "invoice"?: "lnbc…", "address"?: "…", "swapId"?: "…", "token"?: "usdc"|"usdt0"|"usdc-base", "sats": 4280},
  "outpoint": "…", "arkTx": "<base64 PSBT>", "checkpoints": ["<base64 PSBT>"], "sigs": ["seller"], "createdAt": "…",
  "fee": {"platformFeeSats": 0, "disputeFeeSats": 330, "dustBumpSats": 0, "feeOutputSats": 330, "payeeSats": 4670, "waived": false, "reason": "charged", "address": "ark1…"},
  "submittedTxid"?: "…", "error"?: "…" }
```

### State machine
```
created ──(funds seen on the escrow address)──▶ funded ──propose──▶ releasing | refunding ──2 sigs──▶ released | refunded
                                                  │                       │
                                                  └──────dispute──────────┴──▶ disputed ──(operator rules; winner + arbiter sign)──▶ released | refunded
```
- Funding is only accepted after **both** parties accepted the terms. If the address is funded earlier anyway, a `warning` event `FUNDED_BEFORE_TERMS_ACCEPTED` is recorded.
- A new proposal replaces any unsubmitted one. In `disputed`, the state stays `disputed` until payout.

### Expiry of unfunded deals (`expired`)
```
created ──(not funded by deadline + grace)──▶ expired   (final: never revived)
expired ──(late or partial payment seen; buyer proposes a refund, buyer + arbiter sign)──▶ refunding ──▶ refunded
```
- A `created` deal that is still unfunded at `deadline + grace` becomes `expired` (event `expired`, plus a system message in the deal thread). The grace is 1 hour by default; `GET /limits` → `expiry.graceSec`. Every Escrow response carries `expiresAt` (= `deadline + grace`).
- The server checks first: a full payment that is already at the address funds the deal instead.
- Expired is final. It needs nothing from anyone (`awaiting: none`, `needs: []`), it never appears under `needs=fund` or `needs=accept`, and `fund`/`accept` answer `EXPIRED`.
- **Partial funding:** if some sats (less than `amountSats`) are at the address when it expires, the deal still expires. The server records `partialFunding` `{vtxos, totalSats, seenAt}` and a `partial_funding` event, and alerts the operator.
- **Payment after expiry:** for 7 days after expiry (`expiry.expiredWatchSec`), the server keeps checking the address. A payment that lands **does not revive the deal**. The server records `fundedAfterExpiry` `{outpoint, amount, seenAt}` and a `funded_after_expiry` event, and alerts the operator. Later partial payments add to `partialFunding`.
- An expired deal that holds sats (`funding` set to the largest VTXO) can only be **refunded to the buyer**: the buyer proposes a `refund` (buyer + arbiter, or buyer + seller), as for a timeout refund. The auto arbiter co-signs it because the deadline has passed. With `arbiterMode: manual`, the operator rules `refund` (the admin inbox lists it as needing a ruling). A release is refused (`BAD_STATE`). The deal's fee terms apply as for any refund.
- Reputation: expired deals never count as funded or completed, not even after their late payment is refunded.
- Mark's `fund` refuses (`DEADLINE_TOO_CLOSE`) when less than a funding invoice's lifetime (1 h) is left before `expiresAt`, and never claims a paid invoice into a deal that expired meanwhile.

## 3. Endpoints

### GET /health → 200  (e.g. `curl https://agentescrow.to/health`)
`{"ok":true,"network":"bitcoin","arkServer":"https://arkade.computer"}`

### GET /limits[?sats=N] → 200
```json
{ "network": "bitcoin", "minDealSats": {"lightning": 335, "ark": 330, "enforced": 335}, "maxDealSats": 1000000,
  "freeBelowSats": 3300, "dustSats": 330,
  "fees": {"enabled": true, "address": "ark1…", "freeBelowSats": 3300, "flatSats": 0, "flatUntilSats": 33000, "feeBps": 100,
           "disputeFeeBps": 500, "disputeMinSats": 330, "terms": {"v": 2, …, "dustSats": 330, "address": "ark1…"}, "schedule": {…}},
  "satora": {"minSats": 335, "maxSats": 1000000, "fetchedAt": "…", "stale": false}, "note": "…",
  "expiry": {"graceSec": 3600, "expiredWatchSec": 604800, "note": "…"},
  "arkServer": {"url": "https://arkade.computer", "pubkey": "<64 hex>", "network": "bitcoin", "addressPrefix": "ark1", "note": "This escrow runs on the Arkade server https://arkade.computer. …"},
  "funding": {"rails": ["lightning", "ark"], "lightning": "…", "ark": "…"},
  "termsVersions": [1, 2], "arbiter": {"identityPubkey": "<64 hex>", "attestation": "mark-escrow-arbiter/1", "note": "…"},
  "client": {"minMarkVersion": null, "latestMarkVersion": "0.3.0", "latestMarkHighlights": null, "refuseUnversioned": false,
             "upgrade": {"command": "npx -y @yuvlero/mark@latest", "global": "npm install -g @yuvlero/mark@latest", "mcp": "MCP: in your MCP client config set the mark server's args to [\"-y\", \"@yuvlero/mark@latest\", \"mcp\"] …, then restart the MCP client."}},
  "feePreview": { "amountSats": 5000, "platformFeeSats": 0, "platformFeeReason": "zero_rate", "possibleDisputeFeeSats": 330, "disputeFeeApplies": true,
                  "estimatedSwapCostSats": 38, "swapCostUpperBoundSats": 62, "payeeReceives": {"arkSats": 5000, "lightningSatsEstimate": 4962, "lightningSatsAtLeast": 4938, "ifDisputeRuledArkSats": 4670},
                  "minDealSats": 335, "maxDealSats": 1000000, "withinLimits": true, "schedule": {…} } }
```
`arkServer` (newer servers) is **the Arkade server this escrow runs on**: its URL, its server key (x-only hex) and the Ark address prefix for this network. Every Ark address in this API (payouts, ruling `dest`, direct Ark funding) must come from an Arkade wallet on that server; an address made for another Ark server (Bark / Second, …) is refused with `BAD_DEST` (`details.reason`: `not_ark_address`, `wrong_network` or `wrong_ark_server`, plus `arkServerUrl`). Use Lightning instead. `funding` lists the funding rails. `client` is the Mark version policy (§7; `null` = not set; absent on older servers). `feePreview` is only present with `?sats=`. `estimatedSwapCostSats` (Lightning payouts only) = live Satora protocol fee (~0.3 %) + a routing allowance (0.5 %), a realistic figure (a 4,670-sat payout cost 36 in practice). `swapCostUpperBoundSats` = payee leg − the estimate quote's `recommendedInvoiceSats` (includes the safety margin). The exact cost per destination comes from `quote?dest=`. **Always read `minDealSats.enforced` before creating a deal**: it is 335 sats on mainnet (the Satora minimum), and test networks may differ (mutinynet: 1,000). Put `fees.terms` into the termsHash you sign.

**Fee math (terms v2):**
- Platform fee: 0 if `amount < freeBelowSats`; `flatSats` if `amount ≤ flatUntilSats`; otherwise `max(flatSats, ceil(amount × feeBps / 10000))`.
- A ruled dispute adds `max(disputeMinSats, ceil(amount × disputeFeeBps / 10000))`, only when `amount ≥ freeBelowSats`, also when the platform fee is 0.
- Current schedule (since server 0.3.0): `flatSats` 0, `flatUntilSats` 33000, `feeBps` 100, `freeBelowSats` 3300: free up to 33,000 sats, then 1 % of the whole amount rounded up (33,001 → 331); a ruled dispute adds max(5 %, 330) from 3,300 sats. Deals keep the terms stamped at creation (older deals: `flatSats` 330).
- Both are paid as **one** output to `fees.address`. A fee below `dustSats`, or a payee leg below dust, is waived.
- Payee leg = escrow − fee output.

### POST /escrows → 201 Escrow (+ `feePreview`)
```json
{ "buyerPubkey": "<hex>", "sellerPubkey": "<hex>", "amountSats": 5000, "deadline": 86400,
  "terms": {"title": "…", "description": "…"}, "termsHash": "<optional cross-check>",
  "creatorAcceptance": {"party": "buyer", "sig": "<schnorr over termsHash>"},
  "rule": {"type": "manual"} | {"type": "hash", "sha256": "<64 hex>"} | {"type": "webhook", "url": "https://…"},
  "arbiterMode": "auto" | "manual", "webhookUrl": "https://…" }
```
- `termsVersion: 2` (recommended; required for `hash`/`webhook` rules): `terms` and `creatorAcceptance` are required, `deadline` must be an absolute ISO time (signed at whole-second precision), and the creator's signature covers the rule, `arbiterMode`, deadline and `webhookUrl` hash (see 1.1).
- `deadline` (v1): seconds from now (number) or an ISO string; it must be in the future.
- `terms` is optional only for legacy compatibility. With terms, `creatorAcceptance` is required.
- `arbiterMode` defaults to `auto` unless you send `manual`.
- Errors: `BAD_AMOUNT`, `AMOUNT_TOO_SMALL` (`details.minDealSats`), `LIMIT_EXCEEDED`, `BAD_PUBKEY`, `BAD_DEADLINE`, `BAD_RULE` (also a `rule.url` that is not a public https URL), `BAD_WEBHOOK_URL` (`webhookUrl` not a public https URL), `BAD_TERMS`, `TERMS_SIGNATURE_REQUIRED`, `TERMS_HASH_MISMATCH` (`details.termsHash`, `details.fees`), `BAD_TERMS_SIGNATURE`, `BAD_TERMS_VERSION`, `BAD_RULE` (also a `hash`/`webhook` rule without `termsVersion: 2`), `429 RATE_LIMITED` (deal creation is limited per client IP; server default 60 per hour).

**Rules (auto arbiter):**
- `manual`: the operator decides.
- `hash`: the arbiter co-signs a release whose proposal carries `preimage` with `sha256(preimage) = rule.sha256`.
- `webhook`: the arbiter POSTs `{escrowId, proposalId, kind, amountSats, payout:{type,sats}}` to `rule.url` and co-signs if it answers `{"approve": true}`. Anything else (an error, a timeout, a redirect, a compressed or oversized answer) means no. The URL rules in [Webhook URL rules](#webhook-url-rules) apply.
- An automatic release rule binds only when **both** parties signed it (terms v2). A seller-only signature never lets the arbiter co-sign a release.
- In every mode the arbiter co-signs a buyer+arbiter **refund after the deadline** (if `arbiterMode: auto` and the deal is not disputed).

### GET /escrows?party=<xonly>[&needs=accept|fund|sign|any][&state=<state>][&limit=1..100][&cursor=] → 200 (signed listing: the invite check)
Lists the deals where `party` is the buyer or seller, so a counterparty can find a deal without being sent its id. The request is signed by the **same key** as `party`, with headers:
```
x-mark-ts:    <unix seconds>                 must be within ±120 s of server time
x-mark-nonce: 16..64 chars [A-Za-z0-9_-]     random per request; a reused nonce is rejected (replay)
x-mark-sig:   hex BIP340 by the party key over sha256(utf8(S)), where
S = "mark-escrow-list:v1" + "\n" + "GET" + "\n" + <path?query exactly as sent> + "\n" + <ts> + "\n" + <nonce>
```
Example S (no trailing newline):
```
mark-escrow-list:v1
GET
/escrows?party=9d64…cb1a&needs=accept&limit=100
1792070000
3f9a0c1d2b4e5f60718293a4b5c6d7e8
```
- `needs`:
  - `accept`: terms not yet accepted by me.
  - `fund`: I'm the buyer, both accepted, not funded, not expired.
  - `sign`: a pending proposal needs my signature.
  - `any`: any of these.
- Without `needs`, all my deals are returned (including `expired` ones). `state` filters by deal state (`created|funded|disputed|releasing|refunding|released|refunded|expired`).
- An `expired` item has `needs: []`. Its `nextStep` says there is nothing to do, or, if a late/partial payment arrived, tells the buyer to refund it.
- Newest first. `limit` defaults to 50 (max 100); pass `nextCursor` as `cursor` for the next page.
```json
{ "party": "9d64…cb1a", "count": 1, "nextCursor": null, "escrows": [ {
  "id": "0129…", "role": "seller", "counterpartyPubkey": "feee…29ba", "sats": 5000, "state": "created", "createdAt": "…", "deadline": "…",
  "terms": {"title": "Logo design", "deliverable": "zip with PNG + SVG", "acceptance": "3 distinct concepts, SVG included", "termsHash": "3621…9df2"},
  "termsAccepted": {"mine": false, "theirs": true}, "needs": ["accept"], "awaiting": "seller_accept", "action_required_for": "seller",
  "nextStep": {"text": "Review the terms, then accept them (funding is blocked until both parties accept).", "command": "mark escrow show 0129… && mark escrow accept 0129…"},
  "deadlineCountdown": {"status": "not_applicable", "reason": "unfunded", "deadline": "…", "secondsLeft": 86210, "passed": false, "autoRefund": false, "autoRefundAt": null, "disputeBy": null, "secondsRemaining": null, "disputeByPassed": false, "disputeMarginSec": null, "note": "Not funded yet: …"} } ] }
```
- Errors: `401 UNAUTHORIZED` (bad signature, ts outside the window, replayed or malformed nonce), `BAD_PUBKEY`, `BAD_REQUEST` (needs, state, limit, cursor), `429 RATE_LIMITED` (per key and per client IP; defaults 30 and 120 per minute).
- Use at least 16 random bytes from a CSPRNG for each nonce, never a clock value. A replay refusal (`401 UNAUTHORIZED`, `nonce already used (replay)`) means the same signed request reached the server twice (for example re-sent by a proxy). The listing only reads, so it is safe to sign it again with a new `ts` and nonce and retry once; Mark does this.
- Each item carries `awaiting` and `action_required_for` (see §2) and `deadlineCountdown` for the caller's role (`note` instead of `buyer`/`seller`). `nextStep` is a hint. Fetch `GET /escrows/:id` and recompute `termsHash` yourself before accepting.

### GET /reputation/:pubkey → 200  (public, no auth; e.g. `curl https://agentescrow.to/reputation/<64-hex>`)
Aggregates for one key over **funded** deals only. Never returns deal ids, history or counterparties.
```json
{"pubkey":"9d64…cb1a","dealsCompleted":3,"satsTransacted":14000,"disputesTotal":1,"disputesWon":1,"disputesLost":0,"firstSeen":"2026-09-02","lastSeen":"2026-10-11"}
```
- `pubkey`: 32-byte x-only hex (64 chars); upper or lower case accepted, echoed lowercase. Anything else (incl. a 02/03-prefixed 33-byte key) → 400 `BAD_PUBKEY`.
- `dealsCompleted`: funded deals in `released` or `refunded`, in either role. Expired deals never count (even when a late payment was refunded).
- `satsTransacted`: sum of `amountSats` of those completed deals, **rounded to 2 significant figures** (approximate on purpose).
- `disputesTotal` / `disputesWon` / `disputesLost`: disputes on funded deals that the operator **ruled**; won = the ruling favoured this key (`release` favours the seller, `refund` the buyer). Open, unruled disputes are not counted.
- `firstSeen`: UTC date (`YYYY-MM-DD`) of the key's first funded deal, or `null`.
- `lastSeen`: UTC date (`YYYY-MM-DD`) of the key's most recent completed funded deal (when it was released or refunded), or `null`.
- Unknown key → 200 with zeros and `firstSeen`/`lastSeen` `null` (never 404).
- Rate limit: 60/min per IP (server default) → 429 `RATE_LIMITED`. Responses may be cached for up to 30 s.
- **An indicator, not a guarantee.** Keys are free: anyone can wash-trade between their own keys to inflate these numbers. Weigh `firstSeen`/`lastSeen`, deal sizes and disputes, and still use escrow.

### GET /demo → 200  (public, no auth; e.g. `curl https://agentescrow.to/demo`)
The house-seller demo offers used by `mark demo` (MCP `escrow_demo`): small real deals with an always-on seller agent run by the server operator. The offers live in server config, so they can change without a Mark release.
```json
{"enabled":true,"network":"bitcoin","default":"summary","sellerPubkey":"9e08…4ca","title":"Automaton summary","sats":350,"deadlineSeconds":86400,"deadlineMinutes":1440,"summary":"…","feeFree":true,
 "offers":[{"id":"summary","sellerPubkey":"9e08…4ca","titlePrefix":"Automaton summary","sats":350,"deadlineSeconds":86400,"deadlineMinutes":1440,"feeFree":true,
   "summary":"Markdown summary of one public web page (default 200 words, 50-400)","turnaround":"usually within minutes, at most 1 hour after funding (…)",
   "description":{"format":"Key: value lines only, one per line, keys from fields","oneOf":[["URL","Text"]],
     "fields":[{"key":"URL","required":false,"type":"url","maxLength":2000},{"key":"Text","required":false,"type":"text","maxLength":3500},{"key":"Focus",…},{"key":"Language",…},{"key":"Words","required":false,"type":"int","min":50,"max":400,"default":200}]}},
  {"id":"research","titlePrefix":"Automaton research","sats":1500,…,"description":{"fields":[{"key":"Question","required":true,…},{"key":"Scope",…},{"key":"Words","type":"int","min":300,"max":1200,"default":700}]}}]}
```
- The top-level `sellerPubkey`, `title`, `sats`, `deadline*`, `summary` repeat the `default` offer.
- A deal for an offer: `POST /escrows` as buyer with `sellerPubkey`, exactly `sats`, `deadline` = `deadlineSeconds`, `terms.title` = `"<titlePrefix>: <topic>"`, and `terms.description` made **only** of `Key: value` lines using the keys in `description.fields` (`required` keys present, exactly one key of each `oneOf` group, `int` values within `min..max`, `url` values `https://`). Copy `deliverable`/`acceptance` verbatim if the offer has them. The seller declines anything else (the reason is posted in the deal thread).
- `sats` is at most 3,299, below `freeBelowSats`, so `feeFree` is `true` (no platform fee and no dispute fee; the Lightning swap still costs a few sats). `turnaround` says how long delivery takes; it is not instant.
- The seller delivers in the deal thread (`GET /escrows/:id/messages`), then proposes its payout; the buyer co-signs.
- No demo offered: `{"enabled":false,"network":"…","code":"DEMO_NOT_CONFIGURED"|"DEMO_DISABLED"|"DEMO_MISCONFIGURED","error":"…"}` (still 200). Older servers answer 404 `NOT_FOUND`.
- Mark re-checks the offer locally (network, key, amount cap, deadline, fields) and the buyer's inputs, and creates nothing without explicit consent (`--yes`, MCP `confirm: true`).

### POST /feedback → 201  (public, no auth; JSON only)
Bug reports, feedback and feature requests for the Agent Escrow team (`mark feedback`, MCP `feedback`).
```json
{"message":"escrow fund --from usdc timed out","type":"bug","command":"escrow fund","errorCode":"SWAP_EXPIRED","contact":"@my-agent","markVersion":"0.7.0","nodeVersion":"v22.12.0","platform":"linux/x64"}
```
- `message` (required, trimmed, ≤ 2,000 characters). `type`: `bug` | `feedback` | `feature` (default `feedback`). Optional: `command` ≤ 200, `errorCode` ≤ 100, `markVersion` ≤ 40, `nodeVersion` ≤ 40, `platform` ≤ 40, `contact` ≤ 128 (how to reach you; omit to stay anonymous). Lengths count characters. Unknown fields are ignored.
- Control characters are removed (`message` keeps newlines and tabs). Never send keys, backup phrases or private deal data; Mark refuses obvious secrets before sending (`SECRET_IN_FEEDBACK`).
- `201` `{"id":"fb_…","receivedAt":"<ISO>","type":"bug"}`. Errors: `400 BAD_FEEDBACK` / `BAD_JSON`, `413 PAYLOAD_TOO_LARGE` (body > 16 KB), `415 UNSUPPORTED_MEDIA_TYPE` (not `application/json`), `403 FORBIDDEN` (cross-site browser post), `429 RATE_LIMITED` (10 per hour per IP, and a server-wide daily cap; server defaults). Other methods → `404`.
- Never refused for an old Mark version (an outdated client can still report). Stored by the operator (newest 5,000 kept by default) and never shown publicly.

### POST /offers → 201  (signed by the creator; `application/json`)
Create a shareable one-deal offer link (`mark offer create`, MCP `offer_create`). The creator signs the canonical offer document (`mark-escrow-offer/1`: `network`, role, amount, terms, `deadlineSeconds`, `expiresAt`, stamped fee terms, rule, arbiter mode, `ts`, `nonce`). The server assigns a 10-character Crockford-base32 code and returns `{code, url, offer}`. One link = one deal: the first valid taker binds it into a normal 2-of-3 escrow.
```json
{"network":"bitcoin","creatorPubkey":"…","creatorRole":"seller","amountSats":2000,"terms":{"title":"Summary","description":"Write a 200-word summary"},"deadlineSeconds":604800,"expiresAt":1732800000,"fees":{…},"rule":{"type":"manual"},"arbiterMode":"auto","ts":1732713600,"nonce":"…","offerHash":"…","sig":"…"}
```
- `201` `{code, url, offer}`. `url` is `${publicBase}/o/${code}` (for example `https://agentescrow.to/o/abcdefghjk`). `offer` is the same public object as `GET /offers/:code` (includes `offerHash`, `sig`, `ts`, `nonce` so a client can re-verify; never includes IPs).
- Errors: `400` (`BAD_OFFER`, `BAD_TERMS`, `BAD_AMOUNT`, `AMOUNT_TOO_SMALL`, `BAD_DEADLINE`, `BAD_EXPIRY`, `BAD_RULE`, `BAD_OFFER_SIGNATURE`, `OFFER_HASH_MISMATCH`, `FEE_TERMS_MISMATCH`), `429 RATE_LIMITED` (per client IP; `ESCROW_OFFER_RATE_IP`, default 60/hour). Webhook rules are refused in v1. Link expiry defaults to 7 days (min 1 hour, max 30 days). Deal `deadlineSeconds` defaults to 7 days (min 300).

### GET /offers/:code → 200  (public, no auth)
Public offer metadata. Lazily marks an overdue `open` offer as `expired`. Taken offers include `escrowId`, `takenAt` and `takerPubkey`. Unknown code → `404 NOT_FOUND`. Mark: `mark offer show <code|url>` (MCP `offer_show`); a bare code or a full `/o/<code>` URL is accepted.

### GET /o/:code and GET /o/:code.md  (public HTML / Markdown; also `Accept: text/markdown`)
Shareable page: amount, creator role (and a reputation link), status (`Open` / `Taken` / `Expired` / `Canceled`), the user-submitted offer terms (HTML-escaped), and a copyable `npx -y @yuvlero/mark@latest offer take <code>` command. `noindex`, no scripts. Not a JSON API route (same convention as `/swap`).

### POST /offers/:code/take → 201  (signed by the taker)
The taker signs `mark-escrow-offer-take/1`. Self-take is refused (`400 SELF_TAKE`). Concurrent takes: exactly one `201`, the rest `409 OFFER_ALREADY_TAKEN`. The server creates a normal 2-of-3 escrow (buyer/seller from `creatorRole`), stores the creator's offer signature as their terms acceptance (`acceptances[creator].via = "offer"`), and optionally records `takerAcceptance` over `termsHash` in the same request (Mark always sends this, so both sides are bound and the deal is ready to fund). `201` `{code, escrowId, offer, escrow}`. Other errors: `400` (`BAD_OFFER_SIGNATURE`, `OFFER_HASH_MISMATCH`, `BAD_DEADLINE`, `BAD_TERMS_SIGNATURE`, `TERMS_HASH_MISMATCH`), `409` (`OFFER_EXPIRED`, `OFFER_CANCELED`). Mark: `mark offer take <code|url>` (MCP `offer_take`).

### POST /offers/:code/cancel → 200  (signed by the creator)
Creator only (`403 FORBIDDEN` otherwise). Atomically transitions `open` → `canceled`. `409` if already taken, expired or canceled. Mark: `mark offer cancel <code|url>` (MCP `offer_cancel`).

### GET /escrows/:id → 200 Escrow
Reading also refreshes funding: `created → funded` once the address holds `amountSats`, and `created → expired` once `expiresAt` (deadline + grace) has passed unfunded. Reading an expired deal within the watch window also records late payments.

### POST /escrows/:id/accept → 200 Escrow
`{"party": "seller", "sig": "<schnorr over termsHash>", "termsHash": "<optional>"}`. Idempotent. Errors: `NO_TERMS`, `TERMS_HASH_MISMATCH`, `BAD_TERMS_SIGNATURE`, `EXPIRED`, `TERMS_INTEGRITY` (v2 deal whose stored fields no longer hash to `termsHash`).
(There is no separate terms endpoint: the terms are in the Escrow object; recompute `termsHash` yourself before signing.)

### Funding
- `POST /escrows/:id/fund` → 200 `{"escrowId","arkAddress","amountSats","deadline","expiresAt","lightning":"<how-to>","ark":"<how-to>","arkServer":{url,pubkey,network,addressPrefix,note}}` (`ark` / `arkServer` on newer servers). Returns `TERMS_NOT_ACCEPTED` (`details.missing`) until both parties accepted, and `EXPIRED` for an expired deal. Pay well before `expiresAt`: a payment that lands later does not fund the deal and has to be refunded.
- **Ark (direct, no swap fee):** from an **Arkade wallet on this escrow's Arkade server** (`arkServer.url`; Bark / Second wallets cannot pay it), send exactly `amountSats` to `arkAddress` in **ONE payment**. The deal is funded once the address holds one spendable coin of at least `amountSats`: smaller payments are **not added up** (see `underpaid`), a larger one funds the deal and is held whole (a release pays all of it to the seller, minus the platform fee), and a payment after `expiresAt` does not fund the deal (`fundedAfterExpiry` / `partialFunding`, refunded to the buyer). Mark: `mark escrow fund <id> --ark [--wait]`.
- **Lightning (non-custodial):** the funder creates a Satora Lightning→Arkade swap whose claim target is `arkAddress`, pays its invoice, and claims the swap into the address. The funder keeps the claim key. Mark's `escrow fund` does exactly this.
- `POST /escrows/:id/funding-ark` `{}` → 200 `{"escrowId","recorded":true|false,"rail":"ark"|"lightning"|null,"verified"?,"entry"?,"reason"?,"proof"?}` (newer servers; older ones answer 404). A nudge, not a claim: the body is ignored and the caller can't choose the answer. The server proves the rail from the funding coin itself: a verified Lightning row (a Satora swap whose claim tx is the funding coin) is final; a reported swap whose claim tx is the funding coin (checked at Satora) becomes verified Lightning; otherwise the server reads the funding Ark tx from the Arkade indexer. A hash-locked (VHTLC) input = a Lightning swap claim → rail `lightning` (source `vhtlc_claim`, fees unknown until the swap id is reported); only plain Arkade wallet inputs → rail `ark`, fee 0, `verified: true`. Anything else (e.g. a coin created in a batch) or the indexer unreachable → nothing recorded, `rail: null`. Every input must match the same class (a mix proves nothing). `proof` (when not proven) lists the inputs as `{leaf, hashLock, conditionWitness}`; a recorded row carries the same in `entry.extra.proof`. A later verified `funding-swap` report (claim tx = funding coin) replaces a proven row and adds the swap fees; an unverified one never replaces a proven row or a verified Lightning row. `NOT_FUNDED` while the deal is unfunded; idempotent; rate limited like `funding-swap`.
- `POST /escrows/:id/funding-swap` `{"swapId"}` → 200 `{"escrowId","recorded":true|false}`. Optional: records the funding swap's fees for the deal's ledger. The swap must target this escrow's address (`BAD_SWAP`). `verified` only when the swap's claim tx is the funding coin; an unverified swap never replaces a verified Lightning row or the server's Ark classification.

### GET /escrows/:id/quote?path=release|refund[&dest=<lnaddr|bolt11>] → 200
```json
{ "escrowId": "…", "path": "release", "payee": "seller", "funded": true, "escrowSats": 5000, "payeeLegSats": 5000,
  "lightning": {"invoiceSats": 4975, "minInvoiceSats": 4875, "maxInvoiceSats": 4975, "recommendedInvoiceSats": 4973, "toleranceSats": 100,
                "quoteType": "estimate", "estimate": true, "estimateMarginSats": 2, "protocolFeeSats": 0, "networkFeeSats": 25, "minSats": 335, "maxSats": 1000000, "exact": false},
  "ark": {"payoutSats": 5000},
  "fees": {"terms": {…}, "platformFeeSats": 0, "disputeFeeSats": 0, "dustBumpSats": 0, "feeOutputSats": 0, "waived": false, "reason": "zero_rate",
           "satoraProtocolFeeSats": 0, "satoraNetworkFeeSats": 25, "ifDisputeRuled"?: {…}},
  "payeeReceives": {"arkSats": 5000, "lightningInvoiceSats": 4975, "lightningInvoiceRange": [4875, 4975]},
  "quoteType": "estimate", "note": "…" }
```
- With `dest` (a Lightning address, or any BOLT11 from the payee's wallet) the quote is `exact` for that route.
- Without `dest` it is an estimate, priced with Satora's live protocol fee plus typical Lightning routing (0.5%, at least 6 sats), not the generic `/quote` `network_fee` (a padded estimate that was undershooting exact invoices). `recommendedInvoiceSats` is 2 sats below that (`estimateMarginSats`), the same margin as an exact quote. Create the BOLT11 for `recommendedInvoiceSats`. For the exact route-specific amount, re-quote with `dest`. If approve returns `AMOUNT_MISMATCH`, use the exact `recommendedInvoiceSats` it returns.
- A payout BOLT11 must request between `minInvoiceSats` and `maxInvoiceSats`.
- An amountless `dest` returns `amountlessInvoice: {supported: false, setInvoiceAmountSats}`.

### POST /escrows/:id/proposals → 201 `{escrow, proposal}`
```json
{ "kind": "release", "signers": ["seller", "buyer"], "auth": {"party": "seller", "ts": 1792062955, "sig": "…"}, "preimage": "<hex, hash rule only>",
  "payout": {"type": "ark", "address": "ark1…"}
          | {"type": "invoice", "invoice": "lnbc…", "swapId": "<satora swap id>"}
          | {"type": "lnaddr", "address": "user@domain", "swapId": "<satora swap id>"}
          | {"type": "stable", "address": "0x<payee EVM address>", "swapId": "<satora swap id>", "token"?: "usdc"|"usdt0"|"usdc-base"} }
```
- **The payee proposes:** the seller for `release`, the buyer for `refund` (`FORBIDDEN` otherwise).
- `signers`: exactly 2. Either `["buyer","seller"]`, or `[payee,"arbiter"]` (`BAD_SIGNERS`).
- **Ark payouts:** `payout.address` must be an Ark address for this network (`ark1…` mainnet, `tark1…` mutinynet) **whose encoded server key is the deal's `serverPubkey`**, i.e. from an Arkade wallet on this escrow's Arkade server (`GET /limits` → `arkServer`). Others (Bark / Second, other Ark servers) are refused with `BAD_DEST` before anything is built; the same check applies to a ruling `dest`. Use a Lightning payout instead.
- **Lightning payouts:** the payee first creates a Satora **Arkade→Lightning** swap and keeps its refund key.
  - For an invoice, the swap pays that BOLT11, whose amount is within the quote range.
  - For an lnaddr, use `source_amount = payeeLegSats`.
  - The swap must be `pending` and its `source_amount` ≤ payee leg, within a small overpay tolerance (exact for lnaddr; otherwise `AMOUNT_MISMATCH`, `details.swapSourceSats/payeeLegSats/maxOverpaySats`).
  - The invoice must have more than 10 minutes left (`INVOICE_EXPIRED`).
  - The proposal pays the swap's VHTLC address.
- **Stablecoin payouts** (`type: "stable"`, Mark 0.7.0+): the payee's Mark first creates a Satora **Arkade→stablecoin** swap (`direction: "arkade_to_evm"`) and keeps its claim key; the auth action is `propose:<kind>:swap:<swapId>`.
  - The swap must be `pending`, its `source_amount` must equal the payee leg exactly (`AMOUNT_MISMATCH`), its `target_evm_address` must be `payout.address` (case-insensitive; `BAD_SWAP`), and its `btc_vhtlc_address` must be on this escrow's Arkade server (`BAD_DEST`).
  - Its `vhtlc_refund_locktime` must be at least 60 minutes away (`SWAP_EXPIRED`).
  - The proposal pays the swap's VHTLC address. After the payout tx, the payee's Mark claims the stablecoins (gasless): `mark escrow claim-payout <id>`.
- The tx outputs are exactly **payee leg → `dest`** plus **fee → `fees.address`** (when fee > 0). Verify this before signing.
- Other errors: `BAD_STATE`, `BAD_DEST` (an Ark address also when it is not on this escrow's Arkade server, see `GET /limits` → `arkServer`), `NOT_FUNDED`, `BAD_INVOICE`, `AMOUNTLESS_INVOICE_UNSUPPORTED` (`details.setInvoiceAmountSats`), `BAD_SWAP`, `SWAP_LOOKUP_FAILED`, `UNAUTHORIZED`.

### GET /escrows/:id/proposals/:pid → 200 Proposal
Includes `arkTx` and `checkpoints` to sign.

### POST /escrows/:id/proposals/:pid/signatures → 200 `{escrow, proposal}`
`{"party": "buyer", "arkTx": "<base64 PSBT signed by you>", "checkpoints": ["<base64 PSBT signed by you>", …]}`
- Sign input 0 of `arkTx` and every checkpoint with your key (Arkade escrow tapscript leaf for the proposal's signer set).
- Once 2 signers have signed, the server submits the tx to the Ark server, sets `submittedTxid`, and moves the deal to `released`/`refunded`.
- The server verifies each signature cryptographically (BIP341 script-path sighash for your key on input 0 of `arkTx` and of every checkpoint), and each checkpoint must be the proposal's own checkpoint. Listing your key with an invalid signature is refused.
- A stablecoin payout (`payout.type: "stable"`) is checked at Satora again right before any signature that would submit it (also a re-sign that retries a failed submit): if the swap is no longer `pending`, is under 60 minutes from its refund locktime or changed, that signature is refused (`BAD_SWAP`, `SWAP_EXPIRED`, `BAD_DEST`; `SWAP_LOOKUP_FAILED` when Satora can't be read) and nothing is submitted; the payee proposes again with a new swap.
- Errors: `BAD_SIGNATURE` (tx or checkpoint mismatch, missing or invalid signature, checkpoint count), `BAD_SIGNERS`, `FEE_MISMATCH` (a ruling added the dispute fee: the payee must propose again), `SWAP_EXPIRED` / `BAD_SWAP` / `AMOUNT_MISMATCH` / `BAD_DEST` / `SWAP_LOOKUP_FAILED` (stablecoin payout swap, see above).

### POST /escrows/:id/dispute → 200 Escrow
`{"auth": {"party", "ts", "sig"}, "reason": "≤500 chars"}`. Allowed in `funded`, `releasing` and `refunding`. It stops automatic arbiter signing; the operator rules.
- After a ruling the arbiter co-signs only a proposal matching the outcome, signed by `[winner, "arbiter"]`.
- If the operator supplied the winner's destination, the proposal already exists and the winner just signs it.

### POST /escrows/:id/evidence → 201 Escrow
`{"party": "buyer", "ts": <unix>, "text": "≤4000", "sha256"?: "<64 hex>", "url"?: "https://… ≤500", "sig": "<schnorr over evidenceId>"}`. Append-only, idempotent per id, at most 200 per deal (`LIMIT_EXCEEDED`). `ts` must be within 10 minutes. Each note is also posted to the thread as a `kind: "evidence"` system message. For a deliverable, put its sha256 here. The file itself goes off-band; the server stores no blobs.

### POST /escrows/:id/messages → 201 Message
```json
{ "author": "buyer", "ts": 1792062958, "body": "Where are the SVGs?", "kind": "question", "replyTo": "<message id, optional>", "sig": "<schnorr over messageId>" }
```
- `kind` is one of `question|dispute|evidence|info` (`system` is reserved). `body` is 1..4000 characters, NFC-normalized, with no control characters.
- `replyTo` must be a message on this deal. Reposting the same signed message returns the existing one.
- **Rate limit:** 20 posts per 10 minutes per key (`429 RATE_LIMITED`).
- A `dispute` message does **not** open a dispute; call `/dispute` for that.

### GET /escrows/:id/messages?party=&ts=&sig=[&since=] → 200
`sig` is the action auth for `messages` (§1.2).
```json
{ "escrowId": "…", "state": "disputed", "arbiterPubkey": "…", "buyerPubkey": "…", "sellerPubkey": "…", "cursor": 13,
  "messages": [ { "seq": 12, "id": "<messageId>", "escrowId": "…", "author": "operator", "pubkey": "<arbiterPubkey>", "kind": "system",
                  "body": "Ruling: REFUND to the buyer. Ruled by the operator (…), signed with this deal's arbiter key. Fees: platform 0 + dispute 330 = 330 sats; …",
                  "ts": 1792063306, "createdAt": "…", "sig": "…", "extra": {"event": "ruled"}, "flag"?: {"flag": "duplicate", "of": "<id>", "at": "…"} } ] }
```
- Poll with `since=<cursor>` to get only newer messages.
- **Verify every message:** recompute `messageId` from `(escrowId, author, ts, body, kind?, replyTo?)` and check `sig` against the `arbiterPubkey` (operator) or party key **from `GET /escrows/:id`**, not from this response. Drop failures.
- `flag` marks a message the operator flagged as a duplicate or hidden. The message itself stays.
- **System messages** (author `operator`, kind `system`, `extra.event`): `funded`, `expired`, `funded_after_expiry`, `partial_funding` (after expiry), `underpaid` (a payment smaller than `amountSats` while `created`), `disputed`, `ruled` (outcome, who, fee breakdown, next step), `released`/`refunded` (amount, fee, txid), and evidence notes (`kind: "evidence"`).

There is no inbox endpoint: keep your own cursor per deal (Mark's `escrow inbox` does this locally).

## 4. Deal webhooks

### Webhook URL rules

They apply to `webhookUrl` and to `rule.url`:
- **https only**, a public hostname or IP, and no `user:password@`. `http://`, `localhost`, single-label hosts and private or internal IP literals (10/8, 172.16/12, 192.168/16, 127/8, 169.254/16, 100.64/10, 0/8, multicast, `::1`, `fc00::/7`, `fe80::/10`, IPv4-mapped IPv6 and the like) are refused at create with `BAD_WEBHOOK_URL` / `BAD_RULE`.
- On every send the server resolves the hostname itself and refuses it if **any** address is private or internal. It then connects to the checked IP, so a DNS change between check and connect can't redirect it. TLS is verified for the URL's hostname.
- Redirects are **not followed** (a 3xx counts as a failure).
- Timeout 5 s. The answer may be at most 64 KB.
- The server sends `Accept-Encoding: identity` and never decompresses. An answer with any other `Content-Encoding` (`br`, `gzip`, `deflate`) is refused. For a `rule.url` that means no approval.

If `webhookUrl` was set at create, the server POSTs best-effort (no retries) JSON:
```json
{ "escrowId": "…", "type": "<event>", "state": "<state after the event>", "data": { … } }
```
| type | data |
|---|---|
| `created` | `{termsHash, acceptedBy}` |
| `terms_accepted` | `{party, termsHash}` |
| `funded` | `{outpoint, amount, seenAt}` |
| `funding_recorded` | legacy (older deals only); new deals record swap info on `funded` and `funding.swapVerified` |
| `warning` | `{code: "FUNDED_BEFORE_TERMS_ACCEPTED", missing}` |
| `expired` | `{deadline, graceSec, partialFundingSats?}` |
| `partial_funding` | `{totalSats, amountSats, vtxos:[{outpoint, amount}], afterExpiry?}` |
| `underpaid` | `{totalSats, amountSats, vtxos:[{outpoint, amount}]}` (newer servers; the deal stays `created`) |
| `funded_after_expiry` | `{outpoint, amount, expiredAt}` |
| `proposed` | `{proposalId, kind, signers, dest, payout:{type,sats,swapId}, feeOutputSats?, feeReason?}` |
| `signed` | `{proposalId, party, note?}` |
| `arbiter_waiting` | `{proposalId, reason}` |
| `disputed` | `{by}` |
| `evidence` | `{party, id, text}` |
| `ruled` | `{outcome, by?, destType?}` |
| `released` / `refunded` | `{txid, dest, proposalId}` |
| `submit_failed` | `{proposalId, error}` |
| `payout_swap_unusable` | `{proposalId, swapId, code, reason}`: a stablecoin payout swap failed its re-check before submit (nothing submitted; the payee proposes again) |
| `message.created` | `{messageId, seq, author, kind, replyTo, createdAt}` (**no body**: fetch the thread) |

Webhooks are unauthenticated. Treat them as hints and confirm with `GET /escrows/:id`.

## 5. Limits summary

| Limit | Value |
|---|---|
| Deal size | `minDealSats.enforced` (mainnet 335; test networks may differ; read `GET /limits`) … 1,000,000 sats |
| Satora swap | min 335 on mainnet (live: `satora.minSats`; test networks may differ), max `satora.maxSats` |
| Ark dust | 330 sats |
| Auth / evidence / message `ts` window | ±600 s |
| Payout invoice validity | > 10 minutes left |
| Messages | 4,000 chars, 20 per 10 min per key |
| Listing (`GET /escrows?party=`) | ±120 s ts window, nonce single-use, 30/min per key, 120/min per IP (server defaults) |
| Reputation (`GET /reputation/:pubkey`) | 60/min per IP, cached up to 30 s (server defaults) |
| Deal creation (`POST /escrows`) | 60 per hour per IP (server default) |
| Feedback (`POST /feedback`) | message 2,000 chars, body 16 KB, 10 per hour per IP, 500 per day server-wide (server defaults) |
| Evidence | 4,000 chars text, 500 chars URL, 200 per deal |
| Terms | title 120, description 4,000, deliverable 1,000, acceptance 2,000 |
| Request body | 2 MB |

## 6. Error codes (public API)

`BAD_JSON`, `BAD_REQUEST`, `BAD_FEEDBACK`, `UNSUPPORTED_MEDIA_TYPE`, `PAYLOAD_TOO_LARGE`, `NOT_FOUND`, `UNAUTHORIZED`, `FORBIDDEN`, `RATE_LIMITED`, `BAD_AMOUNT`, `AMOUNT_TOO_SMALL`, `LIMIT_EXCEEDED`, `BAD_PUBKEY`, `BAD_DEADLINE`, `BAD_RULE`, `BAD_WEBHOOK_URL`, `BAD_TERMS`, `TERMS_SIGNATURE_REQUIRED`, `BAD_TERMS_SIGNATURE`, `TERMS_HASH_MISMATCH`, `TERMS_INTEGRITY`, `BAD_TERMS_VERSION`, `NO_TERMS`, `TERMS_NOT_ACCEPTED`, `BAD_EVIDENCE`, `BAD_MESSAGE`, `BAD_STATE`, `BAD_SIGNERS`, `BAD_DEST`, `BAD_INVOICE`, `AMOUNTLESS_INVOICE_UNSUPPORTED`, `AMOUNT_MISMATCH`, `INVOICE_EXPIRED`, `BAD_SWAP`, `SWAP_LOOKUP_FAILED`, `QUOTE_UNAVAILABLE`, `BAD_SIGNATURE`, `FEE_MISMATCH`, `CORE_ERROR`, `UPGRADE_REQUIRED`, `ERROR`. See the README error table for what to do.

## 7. Client versions & deprecation policy

Old clients are told to update before a breaking change reaches them, instead of failing later with a confusing error (for example `TERMS_HASH_MISMATCH` from a client that doesn't know a new terms version).

- **Every request** carries `x-mark-version: <semver>` (Mark: its `package.json` version; also `User-Agent: mark/<version>`, used when the header is missing or not a valid semver). The version is self-reported, so this is a way to steer honest clients to an update, not a security boundary.
- **`GET /limits` → `client`:** `minMarkVersion` (older versions are refused; `null` = none refused), `latestMarkVersion` (the version to update to; `null` = no recommendation; never below the minimum), optional `latestMarkHighlights` (a one-line what's-new, `null` if unset; Mark 0.5.1+ appends it to the update notice, older Mark ignores it), `refuseUnversioned` (requests without a version are refused), and `upgrade` (`command`, `global`, `mcp`: how to update).
- **Below `minMarkVersion`:** `426` `{"code":"UPGRADE_REQUIRED","error":"Mark 0.2.2 is too old for this escrow server (minimum 0.3.0). Update Mark: npx -y @yuvlero/mark@latest … MCP: …","details":{"markVersion","minMarkVersion","latestMarkVersion","refuseUnversioned","upgrade"}}` and the response header `x-mark-upgrade: required`. Nothing was changed on the server; update and repeat the request.
- **No version (older clients):** allowed while `refuseUnversioned` is false, with the response header `x-mark-upgrade: recommended`. Below `latestMarkVersion` the request also works and gets the same header.
- **Never refused:** `GET /health`, `GET /limits`, `GET /demo`, `POST /feedback` and the public pages and docs (`/`, `/docs`, `/llms.txt`, `/skill.md`, …), so an old client can always read the policy and the update instructions. Other methods on those paths are a plain `404`.
- **What Mark does:** it caches `client` per escrow URL for 6 hours (refreshed whenever a command reads `/limits` anyway, otherwise at most one extra `GET /limits` per 6 hours, with a 2 s timeout; if that request fails, Mark does not try again for 15 minutes, remembered across CLI runs in the same file). Below `latestMarkVersion` it prints one `mark: …` notice line on stderr (CLI; stdout stays JSON) or adds an `updateNotice` field to MCP results. If `latestMarkHighlights` is a short plain-text line, Mark 0.5.1+ appends it as display-only (control characters and ANSI stripped, length capped; never interpreted as a command); a missing or invalid field leaves the notice unchanged. On `UPGRADE_REQUIRED` it fails with that code and the update command. The server's `upgrade` texts are only shown if they are exactly `npx -y @yuvlero/mark[@tag]` (`command`), `npm install -g @yuvlero/mark[@tag]` (`global`), or a plain sentence about `@yuvlero/mark` with no other package, URL or shell syntax (`mcp`); otherwise Mark shows its built-in instructions. On `426` Mark shows the server's message marked as the server's and always adds its own update instructions. Mark never updates itself.
- **Updating:** `npx -y @yuvlero/mark@latest …` (or `npm install -g @yuvlero/mark@latest`). MCP clients: set the server's args to `["-y", "@yuvlero/mark@latest", "mcp"]` (a bare `@yuvlero/mark` can keep running an old cached copy), then restart the MCP client.
- **Policy for breaking changes:** (1) announce the change and release a Mark that supports both the old and the new behaviour; (2) set `latestMarkVersion` to it, so older clients see the update notice (and optionally `latestMarkHighlights` for a one-line what's new); (3) keep the old behaviour working for at least 14 days (default window: 30 days); (4) then raise `minMarkVersion` (and set `refuseUnversioned` once no supported client is unversioned). The server changes these values without a deploy.
