Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(x402): report an unconfirmed Solana settle as settlement_pending and reconcile it on a cron instead of failing it

nirholas3e8dd089b954
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4c440554e..7458ddd73 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,12 +7,16 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-09-17
- **Agent Wallet Agreement** (`/legal/agent-wallet`): The agreement governing every agent wallet: experimental custodial software, deposits by anyone at their own risk, no insurance, no guaranteed withdrawal or recovery, and no liability for lost funds.
+- **Docs · Doc freshness, keeping docs true to the code** (`/docs/doc-freshness`): Every doc is bound to the code it names, and git decides whether that code moved after the page was last written or last reviewed. How the measurement works, what each status means, how to record that you checked a page, and where the check runs.
- **Docs · Smart glasses, agents on your lens** (`/docs/glasses`): Wear smart glasses and the world tells you an agent is standing thirty metres away. How three.ws splits the work: the lens carries the signal, the phone carries the 3D body, and the presence-gated IRL rail carries the truth.
+- **Pending settlement: the third answer an x402 settle can give** (`/docs/x402-settlement-pending`): Broadcasting a Solana payment and confirming it are separate events, so a settle has three outcomes, not two. What settlement_pending means for a buyer, how our facilitator guarantees one authorization never produces two transactions, and the reconciler that closes the books.
- **Real-Funds Agreements** (`/legal/agreements`): Sign, and review your signatures on, the Terms of Service, Risk Disclosure, and Agent Wallet Agreement required before any real-funds action.
+- **A payment that is still confirming no longer reads as a failed payment**: Settling an x402 payment on Solana means broadcasting a transaction and then waiting for the network to confirm it, and in between the answer is genuinely unknown. Until now an unfinished wait was reported as a failure, so a payment the chain was in the middle of accepting could tell the buyer it had failed and withhold what they paid for. Our facilitator now answers with the protocol's pending state and the settlement signature instead, a retry re-checks that same transaction rather than sending a second one, the endpoint still returns the work with the signature to watch, and a reconciler closes the books every two minutes once the chain answers. The confirmation wait also dropped from 30 seconds to 12, so paid calls come back faster. (`/docs/x402-settlement-pending`) `[fix, improvement, infra]`
- **A plan for meeting agents through smart glasses**: three.ws already lets you pin a 3D agent at a real place and walk up to it, and /irl can already mirror the nearest-agent cue to Brilliant Labs Frame and Even Realities G1 lenses over Bluetooth. New documentation maps the whole glasses lane: how the work splits between the lens (who is near, which way, how far) and the phone (the 3D body in AR), a full build plan for Meta Ray-Ban Display glasses and the Neural Band, and an honest survey of every platform, repository and package involved, including which ones have shut down and should not be built on. (`/docs/glasses`) `[docs, feature]`
- **Agent wallets that cannot sign no longer look tradeable**: A small number of agent wallets hold a balance that three.ws cannot currently sign for. Their Portfolio tab used to show a live net worth with Trade buttons, and the Trade tab showed a working form, so the first sign of trouble was a failed withdrawal. Portfolio and Trade now say up front that trading and withdrawals are paused for that wallet, hide the actions that cannot work, and link straight to support. The explanation is also clearer: the balance has not moved, it is still on chain at the same address, and you should not create a replacement wallet while access is being restored. (`/agents`) `[fix]`
- **Ask your AI assistant to show the picture inside a Solana transaction**: Some Solana transactions carry a small image written straight into their memo, which explorers show as thousands of characters of unreadable text. A new free MCP server, @three-ws/solana-memo-media-mcp, lets Claude, Cursor or any other MCP client fetch a transaction by its signature and show you the image directly, alongside who signed it and a fingerprint of the exact bytes. It can also scan an account's recent history and pick out only the transactions that carry images. It needs no account, key or wallet, never writes anything, and only shows PNG, JPEG, WebP and GIF files whose contents match their label. The Onchain Viewer at /onchain was also fixed: it only recognised the newest memo program, so memos written through the standard Solana memo program were reported as missing. It now reads all three. (`/docs/mcp-solana-memo-media`) `[feature, fix]`
- **Coin pages show the numbers, not a score**: Every coin launched on three.ws used to carry a quality score, a conviction tier and risk labels on its page, in the launch feed and on its share image. A high score can read as investment advice and a low one as FUD about someone's launch, so all of them are gone. In their place is a Token stats panel with the facts traders look up in terminals: volume, buys, sells, net buy and price change over 5 minutes, 1 hour, 6 hours and 24 hours, plus holders, the top 10 share, how much the dev holds, how much early buyers still hold, mint and freeze authority, bonding curve progress, liquidity and whether a DEX Screener profile was paid for. The Holders panel lists the ten largest wallets with links to each one, and leaves the bonding curve and pool out of the ranking. If the full holder index is unavailable, the page still shows the largest holders and says so instead of going blank. (`/launches`) `[improvement]`
+- **Documentation that tells you whether to trust it**: Every page in the docs is bound to the code it names, and git decides whether that code moved after the page was last written. That measurement now has a second clock: when someone reads a page, checks it against the source and finds it correct, that review is recorded, so careful reading counts as much as editing and nobody has to fake a change to clear a page. Docs that record a moment, like a dated audit or a finished piece of work, are marked as records and are no longer counted as drift. Every page that was out of date has been brought back in line: 110 documents were read against the exact changes that had moved under them, 82 were corrected, 22 were confirmed still accurate, and 6 were marked as records of a moment. The dashboard at /docs/freshness now shows who last checked each page and when, the report is regenerated on every deploy instead of by hand, and the check runs automatically so drift cannot pile up unnoticed again. (`/docs/freshness`) `[docs, improvement]`
- **Pick your chart on every coin page, and click an agent's coin to open it**: Every coin launched on three.ws now lets you choose the chart you trust, right on its page: our own price line, live TradingView candles that tick with each trade, or the DexScreener, Birdeye, GMGN and GeckoTerminal charts, all free and all without leaving three.ws. Your choice is remembered from coin to coin. Birdeye and GMGN are also added to the chart picker on /coin pages. A brand-new coin used to show "no price history" for its first hours, because the chart data sources had not listed it yet; it now charts from its very first trade. If GeckoTerminal has not listed a young coin yet, its tab says so and offers a chart that already covers it, instead of an error page. And the coin shown on an agent's page, its profile and its home card is now a link straight to that coin's page, where before it could not be clicked at all. (`/launches`) `[feature, fix]`
- **Sign the real-funds agreements once before using real money**: three.ws is experimental technology, and agent wallets are custodial software, not bank accounts. Before you deposit into an agent wallet, trade, send, withdraw, arm autopilot, or pay with real funds, you now sign three agreements in one step: the Terms of Service, the Risk Disclosure, and the new Agent Wallet Agreement. You tick each one, confirm you are eligible and that you understand funds can be lost for any reason with nothing insured, and type your name as your signature. An agent's deposit address now appears only after signing, and every deposit is covered by the Agent Wallet Agreement. When you are signed in, the signature is saved to your account and the servers refuse real-funds actions from unsigned accounts, including through the API, so it cannot be skipped. You can review every signature you have made at /legal/agreements. Devnet stays free of this step. (`/legal/agreements`) `[security, feature]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 8d46c5f5d..d31a3f718 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -224,7 +224,8 @@ bottom.
| Agent Skills pack | [.agents/skills/](.agents/skills) (canonical) → manifest [.agents/skills/SKILLS.md](.agents/skills/SKILLS.md), [.agents/skills/skills-pack.json](.agents/skills/skills-pack.json); published 3D subset [public/skills/3d-studio/](public/skills/3d-studio) `→ /skills/3d-studio/` | In-repo; bundled in the `three-ws-core` [plugin](.claude-plugin/marketplace.json); 3D subset live on the site | 43 portable `SKILL.md` folders (Agent Skills open standard) for any Claude surface: 3d/creative (cross-platform-safe), wallet/payments, intel/trading. The 3d/creative ones are also published as a public, downloadable bundle at `/skills/3d-studio/` (`three-ws-3d-skills.zip`), which is what an OpenAI Plugin Directory submission uploads on its Skills tab; a skill referencing a tool [api/_mcp-studio/](api/_mcp-studio) does not declare is dropped rather than shipped as a dead path. Regenerate manifest: `node scripts/build-skills-pack.mjs`; regenerate the published bundle: `npm run build:openai-skills` (drift gate `npm run check:openai-skills`, wired into `npm run gate`). Docs: [docs/agent-skills.md](docs/agent-skills.md) |
| Claude Code plugin marketplace | [marketplace/](marketplace) → plugins [three-ws-3d](marketplace/plugins/three-ws-3d), [three-ws-developer](marketplace/plugins/three-ws-developer) | In-repo · installable via `/plugin marketplace add nirholas/three.ws` | 3D generation + rigged avatars inside Claude Code (free lane + paid x402 tools) and developer tooling for building on three.ws. Index: [marketplace/README.md](marketplace/README.md) |
| SNS naming + pay-by-name | [api/sns.js](api/sns.js), [api/sns-subdomain.js](api/sns-subdomain.js), [api/threews/subdomain.js](api/threews/subdomain.js), [api/x402/pay-by-name.js](api/x402/pay-by-name.js), [src/solana/sns-subdomain.js](src/solana/sns-subdomain.js), [pages/threews-claim.html](pages/threews-claim.html) | In-repo | `*.threews.sol` subdomain mint, x402 payments addressed by name. Env: `THREEWS_SOL_PARENT_SECRET_BASE58` |
-| Self-hosted x402 facilitator + ring economy | [api/x402-facilitator/[action].js](api/x402-facilitator/[action].js), [api/_lib/x402/self-facilitator.js](api/_lib/x402/self-facilitator.js), [api/x402/ring-settle.js](api/x402/ring-settle.js), [api/_lib/x402/pipelines/ring-rebalance.js](api/_lib/x402/pipelines/ring-rebalance.js), [api/x402-ring.js](api/x402-ring.js), [scripts/x402-ring-setup.mjs](scripts/x402-ring-setup.mjs) | In-repo (off by default) | Closed-loop agent-to-agent x402: platform wallets pay platform endpoints, settled in-house (no external facilitator). Fee-minimized, SOL-floor guarded, internal-labeled. Env: `X402_SELF_FACILITATOR_ENABLED`, `X402_FEE_PAYER_SECRET_BASE58`, `X402_TREASURY_SECRET_BASE58`. See [docs/x402-ring-economy.md](docs/x402-ring-economy.md) |
+| Self-hosted x402 facilitator + ring economy | [api/x402-facilitator/[action].js](api/x402-facilitator/[action].js), [api/_lib/x402/self-facilitator.js](api/_lib/x402/self-facilitator.js), [api/x402/ring-settle.js](api/x402/ring-settle.js), [api/_lib/x402/pipelines/ring-rebalance.js](api/_lib/x402/pipelines/ring-rebalance.js), [api/x402-ring.js](api/x402-ring.js), [scripts/x402-ring-setup.mjs](scripts/x402-ring-setup.mjs) | In-repo (off by default) | Closed-loop agent-to-agent x402: platform wallets pay platform endpoints, settled in-house (no external facilitator). Fee-minimized, SOL-floor guarded, internal-labeled. Env: `X402_SELF_FACILITATOR_ENABLED`, `X402_FEE_PAYER_SECRET_BASE58`, `X402_TREASURY_SECRET_BASE58`. See [docs/x402-ring-economy.md](docs/x402-ring-economy.md), [docs/x402-settlement-pending.md](docs/x402-settlement-pending.md) |
+| Pending x402 settlement (`settlement_pending`) | [api/_lib/x402/pending-settlements.js](api/_lib/x402/pending-settlements.js), [api/cron/x402-settlement-reconcile.js](api/cron/x402-settlement-reconcile.js), settle path [api/_lib/x402-spec.js](api/_lib/x402-spec.js) + [api/_lib/x402/self-facilitator.js](api/_lib/x402/self-facilitator.js), migration [api/_lib/migrations/20260917200000_x402_pending_settlements.sql](api/_lib/migrations/20260917200000_x402_pending_settlements.sql) | Live | The third settle outcome: a transaction that is broadcast but not yet confirmed answers `settlement_pending` with its signature instead of a failure the buyer's own wallet contradicts. A retry reconciles against the recorded signature rather than broadcasting a second transaction (the x402 `PendingSettlementStore` contract, Postgres-backed so it survives Cloud Run replica hopping), the endpoint still delivers with `status:'pending'`, and the reconcile cron claims the settle credit and closes the books once the chain answers. Tunable: `X402_SETTLE_CONFIRM_TIMEOUT_MS` (12s default). Docs: [docs/x402-settlement-pending.md](docs/x402-settlement-pending.md). Tests: [tests/x402-settlement-pending.test.js](tests/x402-settlement-pending.test.js), [tests/x402-settlement-pending-resource.test.js](tests/x402-settlement-pending-resource.test.js), [tests/api/x402-settlement-reconcile.test.js](tests/api/x402-settlement-reconcile.test.js) |
| Ring payer pool (many distinct payers) | [api/_lib/x402/pool.js](api/_lib/x402/pool.js), [api/_lib/x402/pipelines/ring-pool-fund.js](api/_lib/x402/pipelines/ring-pool-fund.js), [scripts/x402-ring-pool-setup.mjs](scripts/x402-ring-pool-setup.mjs), migration [api/_lib/migrations/2026-07-17-x402-ring-pool.sql](api/_lib/migrations/2026-07-17-x402-ring-pool.sql) | In-repo (off by default) | Reused rotating payer wallets (500–1,000) the ring tick cycles through so the closed loop shows many distinct, attributed payers at 1 tx/settle. Keys secret-box-encrypted in `x402_ring_pool`; pubkeys mirrored into `x402_ring_wallets(role='pool')` so they join the controlled set automatically; NOT in solana-signers.js so sweepback never touches them. LRU rotation (`claimNextPayer`), batched threshold funding (`ring-pool-fund`). Env: `X402_RING_POOL_ENABLED`, `X402_RING_POOL_SIZE`. See [docs/x402-ring-economy.md](docs/x402-ring-economy.md#payer-pool--many-distinct-payers-one-reused-set-of-wallets) |
| $THREE micro-buy loop (x402 buy pressure) | Endpoint [api/x402/three-buy.js](api/x402/three-buy.js) `→ /api/x402/three-buy`, driver [api/cron/three-buy-loop.js](api/cron/three-buy-loop.js), engine [api/_lib/token/microbuy.js](api/_lib/token/microbuy.js), shared Jupiter client [api/_lib/token/jupiter.js](api/_lib/token/jupiter.js), ledger [migration 20260717233000_three_microbuy.sql](api/_lib/migrations/20260717233000_three_microbuy.sql) | In-repo (off by default) | Many tiny, real USDC→$THREE market buys per minute (target ~60/min), each triggered by (and paid through) a settled x402 call: the x402 toll routes to the ring treasury like every other endpoint, and the paid good is one on-chain buy on Jupiter. BUY-ONLY, never sells; accrued $THREE swept to the treasury. High-frequency sibling of the daily buyback ([api/_lib/token/buyback.js](api/_lib/token/buyback.js)). Real spend hard-bounded by a UTC-daily USD ceiling enforced atomically (Redis reserve-before-buy). `autobuy:false` in [ring-catalog.js](api/_lib/x402/ring-catalog.js) so the generic ring never fires it. Env: `THREE_MICROBUY_ENABLED`, `THREE_MICROBUY_SECRET_KEY_B64` (or reuses the buyback wallet), `THREE_MICROBUY_PER_TICK`, `THREE_MICROBUY_DAILY_CAP_USD`. See [docs/three-microbuy.md](docs/three-microbuy.md). |
| Money flow map | [pages/flow.html](pages/flow.html) `→ /flow`, pure graph math + force layout [src/flow-map-core.js](src/flow-map-core.js), canvas/DOM layer [src/flow-map.js](src/flow-map.js), styles [src/flow-map.css](src/flow-map.css), backend view [api/pulse.js](api/pulse.js) `→ GET /api/pulse?view=graph` | Live | The TOPOLOGY of the agent economy, which every other economy surface here misses because a leaderboard cannot show shape. A force-directed canvas map of who paid whom, for which skill, and how much, built from two already-public on-chain sources: agent-to-agent x402 skill payments (`meta.to` payee wallet + `meta.service`) and tips (`meta.from` payer wallet). Every edge is a settled transfer with an explorer-verifiable signature; no inferred or estimated edges exist. Nodes are classified `source` / `hub` / `relay` / `sink` / `quiet` from flow asymmetry, which makes capital dispersion (value entering agent wallets and never circulating out) visible at a glance and puts a number on it as "stuck capital". Counterparty privacy matches the live feed: a wallet is NAMED only when it resolves to a public, non-opted-out agent, otherwise it stays an address-only dashed node. Keyboard and screen-reader parity is structural, not a bolt-on: the table below the canvas renders from the same filtered data and selecting a row selects the node. Docs: [docs/money-flow-map.md](docs/money-flow-map.md). Tests: [tests/flow-map-core.test.js](tests/flow-map-core.test.js) |
diff --git a/api/_lib/migrations/20260917200000_x402_pending_settlements.sql b/api/_lib/migrations/20260917200000_x402_pending_settlements.sql
new file mode 100644
index 000000000..27afcacbe
--- /dev/null
+++ b/api/_lib/migrations/20260917200000_x402_pending_settlements.sql
@@ -0,0 +1,69 @@
+-- 20260917200000_x402_pending_settlements.sql
+--
+-- Non-binary x402 settlement: the durable record of a payment whose transaction
+-- is broadcast but whose confirmation is not yet known.
+--
+-- Before this table a settle had exactly two outcomes. A confirmation wait that
+-- ran out returned `not_confirmed:confirm_timeout`, which the resource server
+-- mapped to a 502, so a transaction that landed a second after the wait gave up
+-- was reported to the buyer as a failed payment while the chain said they had
+-- paid. Solana's x402 rail now carries a third outcome, `settlement_pending`
+-- (Coinbase facilitator, 2026-09-17): broadcast, outcome unknown, retry rather
+-- than fail. Holding that state requires somewhere durable to hold it.
+--
+-- Two scopes share the table because both sides of our rail need the same record
+-- for different reasons:
+--
+-- scope='facilitator': keyed by the payment payload, so a settle retry for the
+-- SAME payload reconciles against the signature already
+-- broadcast instead of verifying and broadcasting a second
+-- transaction. This is the x402 PendingSettlementStore
+-- contract (@x402/core/facilitator). Cloud Run runs several
+-- replicas with no session affinity, so the SDK's in-memory
+-- default store would miss every retry that lands on another
+-- instance; Postgres is the shared implementation the
+-- interface exists to allow.
+-- scope='resource': keyed by the settle idempotency key, so the reconcile cron
+-- (/api/cron/x402-settlement-reconcile) can finish the job
+-- after the response has already been sent: confirm the
+-- signature, claim the settle credit exactly once, and meter
+-- the SOL burn. Without this row a pending settle would be
+-- delivered and then forgotten, which is worse than the 502
+-- it replaces.
+--
+-- `state` is the reconciliation outcome, never a guess: 'pending' until the chain
+-- answers, then 'confirmed' (signature landed, no error), 'failed' (landed with an
+-- on-chain error), or 'abandoned' (never observable within the reconcile horizon,
+-- i.e. the blockhash expired and the transaction was dropped without landing).
+
+CREATE TABLE IF NOT EXISTS x402_pending_settlements (
+ scope text NOT NULL, -- 'facilitator' | 'resource'
+ key text NOT NULL, -- deterministic key derived from the payment payload
+ tx_sig text NOT NULL, -- the broadcast signature whose fate is unknown
+ network text,
+ payer text,
+ pay_to text,
+ mint text,
+ amount_atomic bigint,
+ fee_lamports bigint, -- estimated SOL burn, metered on confirmation
+ fee_payer text, -- wallet that pays the network fee (sponsor or self-pay buyer)
+ resource_url text, -- the paid resource, for the ops trail
+ idempotency_key text,
+ state text NOT NULL DEFAULT 'pending', -- 'pending' | 'confirmed' | 'failed' | 'abandoned'
+ attempts integer NOT NULL DEFAULT 0, -- reconcile passes that have looked at this row
+ last_error text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ resolved_at timestamptz,
+ PRIMARY KEY (scope, key)
+);
+
+-- The reconcile cron's only query shape: oldest unresolved rows first.
+CREATE INDEX IF NOT EXISTS x402_pending_settlements_open
+ ON x402_pending_settlements (state, created_at)
+ WHERE state = 'pending';
+
+-- Signature lookups: "did this payment ever resolve?" from an ops dashboard or a
+-- buyer support question.
+CREATE INDEX IF NOT EXISTS x402_pending_settlements_sig
+ ON x402_pending_settlements (tx_sig);
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index d4c625370..0d100abd1 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -1200,7 +1200,15 @@ export function paidEndpoint(spec) {
// Success telemetry for a settled payment — logged once the good has been
// delivered (after res.end in the buffered path, after the handler streamed
// in the streaming path).
+ //
+ // A `status:'pending'` settlement is recorded as PENDING, not success. The
+ // good ships either way (the transaction is broadcast and the buyer holds
+ // its hash), but the books are not closed until
+ // /api/cron/x402-settlement-reconcile confirms the signature, and telemetry
+ // that called it settled would overstate revenue by exactly the payments
+ // still in flight.
function recordSettledSuccess(settled) {
+ const pending = settled.status === 'pending';
logPaymentEvent({
eventType: 'payment_settled',
route,
@@ -1210,7 +1218,7 @@ export function paidEndpoint(spec) {
amountAtomics: verified.requirement?.amount || null,
asset: verified.requirement?.asset || null,
txHash: settled.transaction || null,
- settlementStatus: 'success',
+ settlementStatus: pending ? 'pending' : 'success',
facilitatorResponse: settled,
durationMs: Date.now() - requestStartTime,
ipAddress: clientIp(req),
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index 0e171cef4..8a94a1afc 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -30,6 +30,13 @@
// 4. If isValid, do the work.
// 5. Server POSTs facilitator /settle (same body) → { success, transaction, network, payer }
// Server attaches a base64 settlement object as `X-PAYMENT-RESPONSE` on the success reply.
+//
+// Settle has THREE outcomes, not two (Solana facilitators, 2026-09-17): success,
+// failure, and `{ success:false, errorReason:'settlement_pending', transaction }`
+// (broadcast, outcome not yet known). settlePayment retries a pending settle once
+// and, if it is still unresolved, records it for the reconcile cron and returns
+// `status:'pending'` so the buyer gets the good they paid for and the settlement
+// hash to watch, instead of a 502 their own wallet history contradicts.
import { createHash } from 'crypto';
@@ -74,6 +81,10 @@ import {
selfFacilitatorEnabled,
selfFacilitatorUrl,
} from './x402/ring-config.js';
+import {
+ SETTLEMENT_PENDING_REASON,
+ recordResourcePending,
+} from './x402/pending-settlements.js';
// Safe to import here: self-facilitator.js pulls in env + the Solana connection
// only, never this module, so there is no cycle.
import { sponsorKnownBelowFloor } from './x402/self-facilitator.js';
@@ -85,6 +96,9 @@ export { X402Error };
// present, and the public surface should match.
export { declareEip2612GasSponsoringExtension, declareErc20ApprovalGasSponsoringExtension };
export { BUILDER_CODE, declareBuilderCodeExtension };
+// Protocol constant, re-exported so a caller handling a pending settle does not
+// have to reach into the storage module for the wire string.
+export { SETTLEMENT_PENDING_REASON };
export const X402_VERSION = 2;
@@ -1129,6 +1143,22 @@ export async function verifyPayment({ paymentHeader, requirements, builderCode }
// ← legacy. Payer-binding cannot be enforced (no `verified.payer`
// anchor). Kept so external/older callers don't break, but new code
// should pass `verified`.
+// Is this settle response the non-terminal `settlement_pending` outcome?
+//
+// Both halves are required. The reason alone is not enough: without a broadcast
+// signature there is nothing for a retry to reconcile against, so a bare
+// `settlement_pending` with no transaction is treated as an ordinary failure
+// rather than something to wait on. Matches @x402/core's
+// isRetryableSettlementPendingResult.
+export function isSettlementPending(result) {
+ return (
+ !!result &&
+ result.success === false &&
+ result.errorReason === SETTLEMENT_PENDING_REASON &&
+ !!result.transaction
+ );
+}
+
export async function settlePayment(args) {
const verified = args?.verified || null;
const paymentPayload = verified?.paymentPayload || args?.paymentPayload;
@@ -1167,16 +1197,70 @@ export async function settlePayment(args) {
return settleOkxXLayerPayment({ verified: okxVerified, requirement, paymentPayload });
}
const idempotencyKey = buildIdempotencyKey({ paymentPayload, requirement });
- const result = await callFacilitator(
- requirement.network,
- '/settle',
- {
- x402Version: X402_VERSION,
- paymentPayload: config.cdp ? minimalPaymentPayloadForCdp(paymentPayload) : paymentPayload,
- paymentRequirements: requirement,
- },
- { idempotencyKey },
- );
+ const settleBody = {
+ x402Version: X402_VERSION,
+ paymentPayload: config.cdp ? minimalPaymentPayloadForCdp(paymentPayload) : paymentPayload,
+ paymentRequirements: requirement,
+ };
+ let result = await callFacilitator(requirement.network, '/settle', settleBody, {
+ idempotencyKey,
+ });
+
+ // `settlement_pending`: the facilitator broadcast a transaction and cannot yet
+ // say whether it landed. Retry EXACTLY ONCE with the identical body and the
+ // same idempotency key, which is what lets the facilitator recognize the retry
+ // and reconcile against the signature it already broadcast instead of sending
+ // a second transaction. One retry, never a loop: bounded waiting belongs to
+ // the facilitator's own confirmation window, and this call is inside a buyer's
+ // open HTTP request. Mirrors @x402/core's settleWithPendingRetry.
+ if (isSettlementPending(result)) {
+ result = await callFacilitator(requirement.network, '/settle', settleBody, {
+ idempotencyKey,
+ });
+ }
+
+ // Still unresolved after the retry. Reporting failure here is the exact bug
+ // the pending state exists to remove: the buyer's transaction is on the wire
+ // and very likely lands, so a 502 would tell someone who IS being charged
+ // that they were not, and leave the work they paid for undelivered.
+ //
+ // Instead: record the signature, answer pending, and let the caller deliver.
+ // The reconcile cron (/api/cron/x402-settlement-reconcile) confirms the
+ // signature afterwards and closes the books. The record is the precondition,
+ // not a nicety: delivering against a pending settlement we cannot reconcile
+ // later would be an unaccountable giveaway, so an unrecordable pending stays
+ // a hard failure.
+ if (isSettlementPending(result)) {
+ const recorded = await recordResourcePending({
+ key: idempotencyKey,
+ signature: result.transaction,
+ meta: {
+ network: requirement.network,
+ payer: result.payer || verifiedPayer || null,
+ payTo: requirement.payTo,
+ mint: requirement.asset,
+ amountAtomic: requirement.amount ? Number(requirement.amount) : null,
+ resourceUrl: requirement.resource || null,
+ idempotencyKey,
+ },
+ });
+ if (!recorded) {
+ throw new X402Error(
+ 'settle_failed',
+ `settle unresolved: the facilitator broadcast ${result.transaction} but its outcome is unknown and the pending record could not be stored, so it cannot be reconciled later. Retry the payment.`,
+ 502,
+ );
+ }
+ return {
+ success: true,
+ status: 'pending',
+ pending: true,
+ transaction: result.transaction,
+ network: result.network || requirement.network,
+ payer: result.payer || verifiedPayer || null,
+ };
+ }
+
if (!result.success) {
const reason = result.errorReason || 'unknown reason';
// A sponsor/fee wallet under its SOL floor is transient operator capacity,
diff --git a/api/_lib/x402/audit-log.js b/api/_lib/x402/audit-log.js
index ba1ae081e..055b3868a 100644
--- a/api/_lib/x402/audit-log.js
+++ b/api/_lib/x402/audit-log.js
@@ -457,3 +457,44 @@ export async function countRecentPayments(withinMinutes = 60) {
return -1;
}
}
+
+/**
+ * Promote a settled-payment audit row from `pending` to its final status once
+ * the chain has answered.
+ *
+ * A payment that settled through the `settlement_pending` path is recorded with
+ * `settlement_status = 'pending'`, because at response time nobody knew whether
+ * it had landed. Revenue queries count `settlement_status = 'success'`, so a row
+ * left pending forever is a payment that silently never appears in the books.
+ * The reconcile cron (api/cron/x402-settlement-reconcile.js) calls this with the
+ * chain's verdict.
+ *
+ * Scoped to rows still marked pending, so it can never rewrite a status that was
+ * already decided, and keyed on the settlement signature, which is unique per
+ * settled payment (settle-credit.js enforces that invariant).
+ *
+ * @param {object} args
+ * @param {string} args.txHash settlement signature
+ * @param {'success'|'failed'} args.status the chain's verdict
+ * @returns {Promise<number>} rows promoted (0 when the payment was never pending)
+ */
+export async function promotePendingSettlementStatus({ txHash, status }) {
+ if (!txHash || !status) return 0;
+ try {
+ const rows = await sql`
+ UPDATE x402_audit_log
+ SET settlement_status = ${status}
+ WHERE tx_hash = ${txHash}
+ AND event_type = 'payment_settled'
+ AND settlement_status = 'pending'
+ RETURNING id
+ `;
+ return rows?.length || 0;
+ } catch (err) {
+ // The books are reconcilable from x402_pending_settlements and the
+ // facilitator log either way; a failed cosmetic promotion must not fail the
+ // reconcile pass that already recorded the real verdict.
+ console.warn('[x402-audit] settlement status promotion failed', err?.message || err);
+ return 0;
+ }
+}
diff --git a/api/_lib/x402/pending-settlements.js b/api/_lib/x402/pending-settlements.js
new file mode 100644
index 000000000..e2beb909f
--- /dev/null
+++ b/api/_lib/x402/pending-settlements.js
@@ -0,0 +1,256 @@
+// api/_lib/x402/pending-settlements.js
+//
+// `settlement_pending`: the third settle outcome.
+//
+// An x402 settle used to answer success or failure and nothing else. That is a
+// lie whenever a transaction has been broadcast and the confirmation wait runs
+// out: the payment may have landed a slot later, and reporting failure charges
+// the buyer while telling them they were not charged. The Solana x402
+// facilitators adopted a third answer on 2026-09-17,
+// `{ success: false, errorReason: 'settlement_pending', transaction }`, meaning
+// "broadcast, outcome unknown, ask again rather than treating this as failed".
+// The canonical SDKs retry it automatically instead of surfacing an error
+// (`@x402/core`'s settleWithPendingRetry, `PendingSettlementStore`).
+//
+// This module is that contract on our own rail, backed by Postgres:
+//
+// 1. `SqlPendingSettlementStore` implements the x402 PendingSettlementStore
+// interface (get/set/delete) so the self-hosted facilitator can recognize a
+// retry of a payload it has ALREADY broadcast and re-await that signature
+// instead of signing and sending a second transaction. The SDK's default
+// store is a per-process Map, which only works when the retry happens to
+// land back on the same instance; our API runs several Cloud Run replicas
+// with no session affinity, so the store has to be shared. That is exactly
+// the case the interface is an interface for.
+//
+// 2. `recordPendingOrTerminal` is the decision the facilitator makes when a
+// confirmation wait fails: persist the signature and answer
+// `settlement_pending`, or (when the persist itself fails) answer a
+// terminal failure instead. Never answer pending without a record: a retry
+// with no record to reconcile against would re-verify and re-broadcast,
+// which is how an unknown outcome becomes a double-send.
+//
+// 3. `recordResourcePending` / `listOpenPendingSettlements` / `resolvePendingSettlement`
+// are the resource-server half. A pending settle still delivers the good
+// (the work is done and the payment is on the wire), so something has to
+// finish the accounting afterwards: /api/cron/x402-settlement-reconcile
+// confirms the signature, claims the settle credit exactly once, and meters
+// the SOL burn. The row is what makes that possible, which is why a pending
+// settle that cannot be recorded is downgraded to a hard failure.
+//
+// Every read and write here fails SOFT by design: a DB outage must never turn a
+// payment that is already on chain into an exception in the settle path. Callers
+// get `undefined`/`false` and decide (the facilitator downgrades pending to
+// terminal; the resource server refuses to deliver on an unrecordable pending).
+
+import { createHash } from 'node:crypto';
+
+import { sql } from '../db.js';
+
+// The wire value. Matches @x402/core's SETTLEMENT_PENDING_REASON exactly: an
+// external buyer SDK keys its automatic retry on this string, so it is a
+// protocol constant, not a label we are free to reword.
+export const SETTLEMENT_PENDING_REASON = 'settlement_pending';
+
+// Reason returned INSTEAD of pending when the store write fails. Terminal on
+// purpose, and distinct from a plain confirm timeout so the signature it carries
+// is recognizable in the log as one that needs manual reconciliation.
+export const SETTLEMENT_PENDING_UNRECORDABLE_REASON = 'settlement_pending_unrecordable';
+
+// How long a stored entry is treated as live. Past it, `get` reports absent, so
+// a much later retry of the same payload is verified and broadcast afresh rather
+// than reconciled against a signature whose blockhash expired long ago. Mirrors
+// the SDK's in-memory TTL scale (minutes, not hours): a Solana blockhash is dead
+// after ~60-90s, so a 10 minute window is already generous.
+export const PENDING_SETTLEMENT_TTL_MS = 10 * 60_000;
+
+export const PENDING_SCOPE_FACILITATOR = 'facilitator';
+export const PENDING_SCOPE_RESOURCE = 'resource';
+
+// Deterministic key for a payment payload: the same signed payload must produce
+// the same key on every replica and every retry, and two different payments must
+// never collide. The signed transaction bytes satisfy both (they carry the
+// payer's signature over a single-use authorization), so hash them rather than
+// reaching into the decoded shape.
+export function pendingSettlementKey(txBase64) {
+ if (!txBase64) return null;
+ return createHash('sha256').update(String(txBase64), 'utf8').digest('hex');
+}
+
+function logFailure(op, err) {
+ console.warn(`[x402-pending] ${op} failed: ${err?.message || err}`);
+}
+
+// The x402 PendingSettlementStore, over Postgres.
+//
+// `get` deliberately returns only rows still in the pending state and inside the
+// TTL: a row the reconcile cron has already resolved must not send a fresh settle
+// down the reconcile path, and an expired row must not either.
+export class SqlPendingSettlementStore {
+ constructor({ scope = PENDING_SCOPE_FACILITATOR, ttlMs = PENDING_SETTLEMENT_TTL_MS } = {}) {
+ this.scope = scope;
+ this.ttlMs = ttlMs;
+ }
+
+ async get(key) {
+ if (!key) return undefined;
+ const cutoff = new Date(Date.now() - this.ttlMs).toISOString();
+ try {
+ const rows = await sql`
+ SELECT tx_sig
+ FROM x402_pending_settlements
+ WHERE scope = ${this.scope}
+ AND key = ${key}
+ AND state = 'pending'
+ AND created_at > ${cutoff}
+ LIMIT 1
+ `;
+ return rows?.[0]?.tx_sig || undefined;
+ } catch (err) {
+ logFailure('get', err);
+ return undefined;
+ }
+ }
+
+ // Returns true only when the record is durable. The caller's answer to the
+ // buyer depends on that, so a swallowed failure must still be visible.
+ async set(key, txHash, meta = {}) {
+ if (!key || !txHash) return false;
+ try {
+ await sql`
+ INSERT INTO x402_pending_settlements
+ (scope, key, tx_sig, network, payer, pay_to, mint, amount_atomic,
+ fee_lamports, fee_payer, resource_url, idempotency_key, state, last_error)
+ VALUES
+ (${this.scope}, ${key}, ${txHash}, ${meta.network || null}, ${meta.payer || null},
+ ${meta.payTo || null}, ${meta.mint || null}, ${meta.amountAtomic ?? null},
+ ${meta.feeLamports ?? null}, ${meta.feePayer || null}, ${meta.resourceUrl || null},
+ ${meta.idempotencyKey || null}, 'pending', ${meta.lastError || null})
+ ON CONFLICT (scope, key) DO UPDATE SET
+ tx_sig = EXCLUDED.tx_sig,
+ state = 'pending',
+ last_error = EXCLUDED.last_error,
+ resolved_at = NULL,
+ updated_at = now()
+ `;
+ return true;
+ } catch (err) {
+ logFailure('set', err);
+ return false;
+ }
+ }
+
+ async delete(key) {
+ if (!key) return;
+ try {
+ await sql`
+ DELETE FROM x402_pending_settlements
+ WHERE scope = ${this.scope} AND key = ${key}
+ `;
+ } catch (err) {
+ logFailure('delete', err);
+ }
+ }
+}
+
+// Persist `signature` under `key` and return the `settlement_pending` settle
+// response, or (when the persist fails) a terminal failure carrying the same
+// signature for manual reconciliation.
+//
+// The asymmetry is the whole point: answering pending promises a retry can
+// reconcile, and without a record it cannot. Mirrors @x402/svm's
+// recordPendingOrTerminal.
+export async function recordPendingOrTerminal({
+ store,
+ key,
+ signature,
+ network,
+ payer,
+ meta = {},
+ pendingReason = SETTLEMENT_PENDING_REASON,
+ terminalReason = SETTLEMENT_PENDING_UNRECORDABLE_REASON,
+ cause,
+}) {
+ const detail = cause ? String(cause?.message || cause).slice(0, 200) : '';
+ const recorded = store
+ ? await store.set(key, signature, { ...meta, network, payer, lastError: detail })
+ : false;
+ if (!recorded) {
+ return {
+ success: false,
+ reason: detail ? `${terminalReason}:${detail}` : terminalReason,
+ transaction: signature,
+ network,
+ payer,
+ pending: false,
+ };
+ }
+ return {
+ success: false,
+ reason: pendingReason,
+ transaction: signature,
+ network,
+ payer,
+ pending: true,
+ pendingDetail: detail || null,
+ };
+}
+
+// Resource-server half: record a settle the facilitator answered `pending` so the
+// reconcile cron can finish the accounting after the response is sent. Returns
+// false when the row could not be written, which is the resource server's signal
+// to refuse delivery rather than hand out a good it can never account for.
+export async function recordResourcePending({ key, signature, meta = {} }) {
+ const store = new SqlPendingSettlementStore({ scope: PENDING_SCOPE_RESOURCE });
+ return store.set(key, signature, meta);
+}
+
+// Oldest-first page of rows still awaiting an answer. `minAgeMs` keeps the cron
+// off signatures the settle path may still be waiting on itself.
+export async function listOpenPendingSettlements({ limit = 100, minAgeMs = 5_000 } = {}) {
+ const cutoff = new Date(Date.now() - minAgeMs).toISOString();
+ const rows = await sql`
+ SELECT scope, key, tx_sig, network, payer, pay_to, mint, amount_atomic,
+ fee_lamports, fee_payer, resource_url, idempotency_key, attempts,
+ created_at
+ FROM x402_pending_settlements
+ WHERE state = 'pending' AND created_at <= ${cutoff}
+ ORDER BY created_at ASC
+ LIMIT ${limit}
+ `;
+ return rows || [];
+}
+
+// Record the chain's answer. `state` is one of confirmed | failed | abandoned |
+// pending; 'pending' only bumps the attempt counter (the chain still has not
+// answered), every other value resolves the row.
+export async function resolvePendingSettlement({ scope, key, state, error = null }) {
+ const resolved = state !== 'pending';
+ await sql`
+ UPDATE x402_pending_settlements
+ SET state = ${state},
+ attempts = attempts + 1,
+ last_error = ${error},
+ resolved_at = ${resolved ? new Date().toISOString() : null},
+ updated_at = now()
+ WHERE scope = ${scope} AND key = ${key}
+ `;
+}
+
+// Ops counters for /api/x402-status: how much of the rail is mid-flight, and how
+// the recent history resolved. Cheap enough for a status probe (one grouped scan
+// of a table that only holds live and recently-resolved settlements).
+export async function pendingSettlementStats({ windowHours = 24 } = {}) {
+ const since = new Date(Date.now() - windowHours * 3_600_000).toISOString();
+ const rows = await sql`
+ SELECT state, count(*)::int AS n
+ FROM x402_pending_settlements
+ WHERE created_at > ${since}
+ GROUP BY state
+ `;
+ const out = { window_hours: windowHours, pending: 0, confirmed: 0, failed: 0, abandoned: 0 };
+ for (const r of rows || []) {
+ if (r.state in out) out[r.state] = r.n;
+ }
+ return out;
+}
diff --git a/api/_lib/x402/self-facilitator.js b/api/_lib/x402/self-facilitator.js
index 56e7693a1..296cb6253 100644
--- a/api/_lib/x402/self-facilitator.js
+++ b/api/_lib/x402/self-facilitator.js
@@ -32,6 +32,14 @@ import {
import { env } from '../env.js';
import { solanaConnection } from '../solana/connection.js';
+// Pure DB/crypto helpers: no cycle back into this module.
+import {
+ SETTLEMENT_PENDING_REASON,
+ pendingSettlementKey,
+ recordPendingOrTerminal,
+} from './pending-settlements.js';
+
+export { SETTLEMENT_PENDING_REASON };
const COMPUTE_BUDGET_PROGRAM_ID = new PublicKey(
'ComputeBudget111111111111111111111111111111',
@@ -518,22 +526,125 @@ function bumpSolCache(pubkeyB58, deltaLamports) {
}
}
-async function confirmSignature(conn, signature, timeoutMs = 30_000) {
- const deadline = Date.now() + timeoutMs;
+// How long a settle blocks waiting for confirmation before it answers
+// `settlement_pending` and lets the reconcile cron finish the job. The old
+// 30-second wait was the only thing between a slow slot and a 502, so it had to
+// be long; now that an unresolved wait is a third outcome rather than a failure,
+// holding the buyer's connection open for half a minute buys nothing. 12s clears
+// the overwhelming majority of Solana confirmations inline and caps the settle
+// leg of a paid request at a latency a client library will sit through.
+// Read per call, not at import: the confirmation window is the one settle
+// tunable an operator reaches for DURING an incident (a degraded RPC wants a
+// shorter wait so more settles go pending and reconcile out of band), and a
+// module-load constant would need a redeploy to move.
+function settleConfirmTimeoutMs() {
+ const raw = Number(process.env.X402_SETTLE_CONFIRM_TIMEOUT_MS);
+ return Number.isFinite(raw) && raw > 0 ? raw : 12_000;
+}
+// Status poll cadence. Tightened with the timeout above: at 1200ms a transaction
+// that confirms in 500ms still paid up to a full extra second of latency.
+const CONFIRM_POLL_MS = 800;
+
+// Wait for a signature's fate.
+//
+// Three answers, not two, because "we do not know yet" is a real state and the
+// caller's response to it differs completely from a rejection:
+// { confirmed: true } landed, no error.
+// { confirmed: false, terminal: true } landed and FAILED on chain. It ran
+// and reverted, so there is nothing
+// to wait for; report the failure.
+// { confirmed: false, terminal: false } the wait ran out, or the RPC could
+// not answer. The transaction may
+// still land. NEVER report failure
+// here: this is `settlement_pending`.
+//
+// A transaction that was dropped without landing looks identical to the third
+// case from inside the wait, and it is the reconcile pass
+// (probeSettlementSignature) that later distinguishes the two, once the
+// blockhash can no longer be valid.
+async function confirmSignature(conn, signature, timeoutMs) {
+ const deadline = Date.now() + (timeoutMs ?? settleConfirmTimeoutMs());
+ let lastRpcError = null;
for (;;) {
- const { value } = await conn.getSignatureStatuses([signature]);
- const st = value?.[0];
- if (st) {
- if (st.err) return { confirmed: false, err: JSON.stringify(st.err) };
- if (st.confirmationStatus === 'confirmed' || st.confirmationStatus === 'finalized') {
- return { confirmed: true };
+ try {
+ const { value } = await conn.getSignatureStatuses([signature]);
+ const st = value?.[0];
+ if (st) {
+ if (st.err) {
+ // An on-chain error is definitive: this transaction ran and reverted.
+ return { confirmed: false, terminal: true, err: JSON.stringify(st.err) };
+ }
+ if (st.confirmationStatus === 'confirmed' || st.confirmationStatus === 'finalized') {
+ return { confirmed: true };
+ }
}
+ lastRpcError = null;
+ } catch (err) {
+ // An RPC that cannot answer tells us nothing about the transaction. Keep
+ // polling until the deadline, then report UNKNOWN, not failure.
+ lastRpcError = String(err?.message || err).slice(0, 160);
}
- if (Date.now() > deadline) return { confirmed: false, err: 'confirm_timeout' };
- await new Promise((r) => setTimeout(r, 1200));
+ if (Date.now() > deadline) {
+ return {
+ confirmed: false,
+ terminal: false,
+ err: lastRpcError ? `confirm_rpc_unavailable:${lastRpcError}` : 'confirm_timeout',
+ };
+ }
+ await new Promise((r) => setTimeout(r, CONFIRM_POLL_MS));
}
}
+// Finish a settle whose transaction is already on the wire: re-await THIS
+// signature instead of verifying, co-signing, and broadcasting a second
+// transaction.
+//
+// Reached from the pending-store hit at the top of settleRingPayment, i.e. a
+// retry of a payload we have already broadcast. Re-sending there is what the
+// pending state exists to prevent: the original may land at any moment, and a
+// second transfer of the same funds is a double charge. (The reconcile cron
+// answers the same question out of band, without a payload in hand, through
+// probeSettlementSignature.)
+async function awaitBroadcastSettlement({
+ connection,
+ signature,
+ network,
+ payer,
+ decoded,
+ pendingStore,
+ key,
+ meta,
+}) {
+ const conf = await confirmSignature(connection, signature);
+ if (conf.confirmed) {
+ if (pendingStore && key) await pendingStore.delete(key);
+ return {
+ success: true,
+ transaction: signature,
+ network,
+ payer,
+ feeLamports: decoded?.estFeeLamports ?? meta?.feeLamports ?? 0,
+ feePayer: decoded?.feePayer ?? meta?.feePayer ?? null,
+ selfPay: decoded?.selfPay ?? false,
+ reconciled: true,
+ };
+ }
+ if (conf.terminal) {
+ if (pendingStore && key) await pendingStore.delete(key);
+ return { success: false, reason: `not_confirmed:${conf.err}`, transaction: signature };
+ }
+ // Still unknown. Re-record (refreshing the row's error detail) and stay pending.
+ return recordPendingOrTerminal({
+ store: pendingStore,
+ key,
+ signature,
+ network,
+ payer,
+ meta,
+ cause: conf.err,
+ });
+}
+
// Settle a validated ring payment: co-sign with the sponsor, broadcast over our
// RPC, confirm. Returns the x402-wire settle shape { success, transaction,
// network, payer } plus feeLamports for the burn meter and feePayer/selfPay for
@@ -545,7 +656,22 @@ async function confirmSignature(conn, signature, timeoutMs = 30_000) {
// pay this transaction's fee. A { ok:false } verdict refuses the settle before
// any co-sign/broadcast; a hook error fails OPEN — the floor is the hard
// protection, the meter is pacing.
-export async function settleRingPayment({ paymentPayload, requirement, conn, feePayer, feeMeter }) {
+//
+// `pendingStore` is the x402 PendingSettlementStore (pending-settlements.js).
+// With one supplied, a confirmation wait that ends UNKNOWN records the broadcast
+// signature and answers `settlement_pending` instead of a failure the buyer's
+// payment contradicts, and a retry of the same payload reconciles against that
+// signature rather than broadcasting a second transaction. Without one the
+// behaviour is the old binary, which is why the endpoint always passes it.
+export async function settleRingPayment({
+ paymentPayload,
+ requirement,
+ conn,
+ feePayer,
+ feeMeter,
+ pendingStore,
+ idempotencyKey,
+}) {
const network = requirement.network;
const connection = conn || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
@@ -565,6 +691,44 @@ export async function settleRingPayment({ paymentPayload, requirement, conn, fee
const decoded = validation.decoded;
const { tx, payer, estFeeLamports, selfPay } = decoded;
+ // Metadata every pending record and reconcile pass needs, assembled once.
+ const pendingKey = pendingSettlementKey(txBase64);
+ const pendingMeta = {
+ network,
+ payer,
+ payTo: requirement.payTo,
+ mint: requirement.asset,
+ amountAtomic: decoded.amountAtomic,
+ feeLamports: estFeeLamports,
+ feePayer: decoded.feePayer,
+ // The caller's settle idempotency key, stored so the reconcile pass claims
+ // the settle credit under the SAME key the resource server used. Without it
+ // the credit gate reads the reconciled claim as a different payment reusing
+ // the signature and refuses it (settle-credit.js classify()).
+ idempotencyKey: idempotencyKey || null,
+ };
+
+ // A retry of a payload we ALREADY broadcast: re-await that signature. Placed
+ // before the balance reads, the fee meter, the co-sign, and the broadcast
+// because none of them should run twice. The first attempt already spent
+ // (or committed to spending) this transaction's fee, and a second broadcast
+ // of a different transaction for the same authorization is a double charge.
+ if (pendingStore && pendingKey) {
+ const cachedSignature = await pendingStore.get(pendingKey);
+ if (cachedSignature) {
+ return awaitBroadcastSettlement({
+ connection,
+ signature: cachedSignature,
+ network,
+ payer,
+ decoded,
+ pendingStore,
+ key: pendingKey,
+ meta: pendingMeta,
+ });
+ }
+ }
+
// Anti fee-burn: a sponsor-mode settle must move at least enough to cover the
// SOL fee we're about to burn co-signing it. Blocks the dust-transfer grief
// (1-atomic allowlisted transfers spammed to pump down sponsor SOL). Self-pay
@@ -808,9 +972,30 @@ export async function settleRingPayment({ paymentPayload, requirement, conn, fee
const conf = await confirmSignature(connection, signature);
if (!conf.confirmed) {
- return { success: false, reason: `not_confirmed:${conf.err}`, transaction: signature };
+ // Landed and reverted, or provably dropped: a real failure.
+ if (conf.terminal) {
+ if (pendingStore && pendingKey) await pendingStore.delete(pendingKey);
+ return { success: false, reason: `not_confirmed:${conf.err}`, transaction: signature };
+ }
+ // Outcome unknown. The transaction is broadcast and may land at any moment,
+ // so reporting failure here would tell a buyer who is about to be charged
+ // that they were not. Record the signature and answer `settlement_pending`;
+ // the caller's retry reconciles against it and the reconcile cron closes the
+ // books either way. The fee cache is deliberately NOT bumped: whether the
+ // fee was burned is exactly what we do not know yet, and the reconcile pass
+ // meters it once the chain answers.
+ return recordPendingOrTerminal({
+ store: pendingStore,
+ key: pendingKey,
+ signature,
+ network,
+ payer,
+ meta: pendingMeta,
+ cause: conf.err,
+ });
}
+ if (pendingStore && pendingKey) await pendingStore.delete(pendingKey);
bumpSolCache(feeWallet.toBase58(), estFeeLamports);
// Best-effort: read the real network fee for accurate burn accounting.
@@ -949,3 +1134,56 @@ export async function verifyRingPayment({ paymentPayload, requirement, feePayerP
payer: validation.decoded.payer,
};
}
+
+// A transaction can only be included while its blockhash is live (150 slots,
+// ~60-90s). Past that a signature the ledger has never seen can never appear, so
+// "not found" stops meaning "not yet" and starts meaning "dropped". Held well
+// clear of the real limit so a lagging history index is never mistaken for a
+// dropped payment.
+export const SETTLEMENT_DROP_HORIZON_MS = 180_000;
+
+// The reconcile pass's read: what does the chain say about a signature we
+// broadcast and never confirmed?
+//
+// Strictly read-only: it never signs, re-sends, or touches a wallet. Returns
+// the state the pending row should take:
+// 'confirmed': landed, no error. feeLamports carries the real fee when the
+// parsed transaction is available, so the burn meter records
+// what was actually spent rather than the estimate.
+// 'failed': landed with an on-chain error.
+// 'abandoned': no trace, and too old for its blockhash to still be valid.
+// 'pending': no trace yet, still inside the horizon, or the RPC could not
+// answer. Ask again next pass.
+export async function probeSettlementSignature({ conn, signature, broadcastAtMs }) {
+ const connection =
+ conn || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
+ let status;
+ try {
+ status = (
+ await connection.getSignatureStatuses([signature], { searchTransactionHistory: true })
+ )?.value?.[0];
+ } catch (err) {
+ return { state: 'pending', error: `probe_rpc_failed:${String(err?.message || err).slice(0, 160)}` };
+ }
+
+ if (status && status.err) {
+ return { state: 'failed', error: JSON.stringify(status.err).slice(0, 400) };
+ }
+ if (status && !status.err) {
+ let feeLamports = null;
+ try {
+ const parsed = await connection.getParsedTransaction(signature, {
+ maxSupportedTransactionVersion: 1,
+ commitment: 'confirmed',
+ });
+ if (parsed?.meta?.fee != null) feeLamports = parsed.meta.fee;
+ } catch { /* the stored estimate stands */ }
+ return { state: 'confirmed', feeLamports };
+ }
+
+ const ageMs = broadcastAtMs ? Date.now() - broadcastAtMs : 0;
+ if (ageMs > SETTLEMENT_DROP_HORIZON_MS) {
+ return { state: 'abandoned', error: `not_found_after_${Math.round(ageMs / 1000)}s` };
+ }
+ return { state: 'pending', error: 'not_found_yet' };
+}
diff --git a/api/cron/db-retention.js b/api/cron/db-retention.js
index 54e84303f..25680a707 100644
--- a/api/cron/db-retention.js
+++ b/api/cron/db-retention.js
@@ -365,6 +365,32 @@ async function pruneAuditLog(cutoffDays) {
return { deleted };
}
+// B2b. Pending-settlement rows (x402_pending_settlements).
+//
+// A row exists to carry ONE x402 settlement whose transaction was broadcast
+// before its outcome was known (api/_lib/x402/pending-settlements.js). Once
+// /api/cron/x402-settlement-reconcile has recorded the chain's verdict the row is
+// history: the money record itself lives in x402_self_facilitator_log and
+// x402_audit_log, which have their own, longer windows.
+//
+// Only RESOLVED rows are prunable, and the cutoff is deliberately not the shared
+// storage valve: an unresolved row is a payment nobody has accounted for yet, and
+// deleting it under storage pressure would lose the only handle on it. Those stay
+// until the chain answers, however long that takes.
+const PENDING_SETTLEMENT_KEEP_DAYS = 30;
+
+async function prunePendingSettlements() {
+ if (!(await tableExists('x402_pending_settlements'))) return { deleted: 0 };
+ const del = await sql`
+ DELETE FROM x402_pending_settlements
+ WHERE state <> 'pending'
+ AND resolved_at IS NOT NULL
+ AND resolved_at < now() - ${PENDING_SETTLEMENT_KEEP_DAYS} * interval '1 day'
+ RETURNING key
+ `;
+ return { deleted: del.length };
+}
+
// ── B. avatar_regen_jobs hygiene ──────────────────────────────────────────────
async function pruneRegenJobs() {
if (!(await tableExists('avatar_regen_jobs'))) return { stripped: 0, deleted: 0 };
@@ -558,6 +584,7 @@ export default wrapCron(async (req, res) => {
});
const runLogs = await pruneRunLogs(cutoffDays);
const audit = await pruneAuditLog(auditCutoffDays);
+ const pendingSettlements = await prunePendingSettlements();
const regen = await pruneRegenJobs();
// E. Per-home action-log retention. Best-effort: the home tables may not exist
// on a branch that has not run the Home migrations, and a failure here must
@@ -577,6 +604,7 @@ export default wrapCron(async (req, res) => {
for (const t of Object.keys(series)) if (!touched.includes(t)) touched.push(t);
for (const t of Object.keys(runLogs)) if (!touched.includes(t)) touched.push(t);
if (audit.deleted > 0) touched.push('x402_audit_log');
+ if (pendingSettlements.deleted > 0) touched.push('x402_pending_settlements');
if (regen.deleted > 0 || regen.stripped > 0) touched.push('avatar_regen_jobs');
if (homeActionLog.deleted > 0) touched.push('home_action_log');
await vacuumTables(touched);
@@ -633,6 +661,7 @@ export default wrapCron(async (req, res) => {
series,
run_logs: runLogs,
audit,
+ pending_settlements: pendingSettlements,
regen,
home_action_log: homeActionLog,
vacuumed: touched,
diff --git a/api/cron/x402-settlement-reconcile.js b/api/cron/x402-settlement-reconcile.js
new file mode 100644
index 000000000..6e58a1b17
--- /dev/null
+++ b/api/cron/x402-settlement-reconcile.js
@@ -0,0 +1,188 @@
+// @ts-check
+// GET /api/cron/x402-settlement-reconcile: closes the books on every x402
+// settlement that answered `settlement_pending`.
+//
+// A pending settle is a payment whose transaction is broadcast and whose outcome
+// was still unknown when the buyer's request had to return. The rail answers
+// `{ success:false, errorReason:'settlement_pending', transaction }` instead of a
+// failure the buyer's own wallet history contradicts, delivers the good, and
+// records the signature (api/_lib/x402/pending-settlements.js). That leaves
+// exactly one job outstanding: ask the chain what happened and finish the
+// accounting. This cron is that job.
+//
+// Per open row, every 2 minutes:
+// 1. probeSettlementSignature(): read-only signature status, searching
+// transaction history so a settlement that landed minutes ago is still
+// found. It never signs and never re-broadcasts; re-sending a transaction
+// whose fate is unknown is the double-charge this whole mechanism exists to
+// avoid.
+// 2. confirmed → claimSettleCredit() under the SAME idempotency key the settle
+// used, so the credit is granted at most once per signature (settle-credit.js
+// is the atomic arbiter) and the real network fee lands in the fee book.
+// 3. failed / abandoned → resolve the row and alert. A resource-scope row in
+// either state means a good was delivered against a payment that never
+// settled, which is the one loss this design can produce and must therefore
+// never be silent.
+// 4. still unknown → bump the attempt counter and look again next pass.
+//
+// Rows are keyed (scope, key) and resolved idempotently, so a run that overlaps
+// the previous one cannot double-credit: the credit gate, not this loop, is what
+// enforces "one signature settles at most one payment".
+
+import { json, method, wrapCron } from '../_lib/http.js';
+import { sql } from '../_lib/db.js';
+import { sendOpsAlert } from '../_lib/alerts.js';
+import { requireCron } from '../_lib/cron-auth.js';
+import { env } from '../_lib/env.js';
+import { solanaConnection } from '../_lib/solana/connection.js';
+import { claimSettleCredit } from '../_lib/x402/settle-credit.js';
+import { promotePendingSettlementStatus } from '../_lib/x402/audit-log.js';
+import { probeSettlementSignature } from '../_lib/x402/self-facilitator.js';
+import {
+ PENDING_SCOPE_RESOURCE,
+ listOpenPendingSettlements,
+ resolvePendingSettlement,
+} from '../_lib/x402/pending-settlements.js';
+
+// Rows per run. A pending settlement is rare by construction (the settle path
+// waits out the common case inline), so this is a generous ceiling that also
+// bounds RPC spend if a provider incident produces a burst of them.
+const MAX_ROWS_PER_RUN = 100;
+// Leave a settle that may still be inside its own confirmation window alone: the
+// request that created the row can still resolve it itself.
+const MIN_AGE_MS = 20_000;
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const rows = await listOpenPendingSettlements({
+ limit: MAX_ROWS_PER_RUN,
+ minAgeMs: MIN_AGE_MS,
+ });
+
+ if (rows.length === 0) {
+ return json(res, 200, { ok: true, scanned: 0, confirmed: 0, failed: 0, abandoned: 0, still_pending: 0 });
+ }
+
+ const conn = solanaConnection({
+ url: env.SOLANA_RPC_URL,
+ network: 'mainnet',
+ commitment: 'confirmed',
+ });
+
+ const counts = { confirmed: 0, failed: 0, abandoned: 0, still_pending: 0, credited: 0 };
+ const unsettledDeliveries = [];
+ const results = [];
+
+ for (const row of rows) {
+ const broadcastAtMs = row.created_at ? new Date(row.created_at).getTime() : Date.now();
+ let probe;
+ try {
+ probe = await probeSettlementSignature({
+ conn,
+ signature: row.tx_sig,
+ broadcastAtMs,
+ });
+ } catch (err) {
+ // A probe fault is not an answer. Leave the row open.
+ probe = { state: 'pending', error: `probe_failed:${String(err?.message || err).slice(0, 160)}` };
+ }
+
+ if (probe.state === 'confirmed') {
+ // The fee the chain actually charged, when the parsed transaction was
+ // readable; otherwise the estimate recorded at broadcast. Either way the
+ // credit row is what the daily fee book sums, so it must carry a number.
+ const feeLamports = probe.feeLamports ?? row.fee_lamports ?? null;
+ const credit = await claimSettleCredit({
+ sql,
+ row: {
+ network: row.network,
+ payer: row.payer,
+ payTo: row.pay_to,
+ mint: row.mint,
+ amountAtomic: row.amount_atomic == null ? null : Number(row.amount_atomic),
+ txSig: row.tx_sig,
+ feeLamports,
+ idempotencyKey: row.idempotency_key,
+ feePayer: row.fee_payer,
+ },
+ });
+ if (credit.granted) counts.credited += 1;
+ // The audit row was written with settlement_status='pending' while the
+ // outcome was unknown, and every revenue query counts 'success'. Promote
+ // it now, or this payment never reaches the books.
+ await promotePendingSettlementStatus({ txHash: row.tx_sig, status: 'success' });
+ // A refused claim that is NOT an idempotent replay means another payment
+ // already owns this signature, or the DB could not answer. Neither is a
+ // reason to keep re-probing a transaction the chain has already confirmed,
+ // so the row resolves and carries the refusal for the audit trail.
+ await resolvePendingSettlement({
+ scope: row.scope,
+ key: row.key,
+ state: 'confirmed',
+ error: credit.granted ? null : credit.reason || null,
+ });
+ counts.confirmed += 1;
+ results.push({ sig: row.tx_sig, state: 'confirmed', credit: credit.granted ? 'granted' : credit.reason });
+ continue;
+ }
+
+ if (probe.state === 'failed' || probe.state === 'abandoned') {
+ await resolvePendingSettlement({
+ scope: row.scope,
+ key: row.key,
+ state: probe.state,
+ error: probe.error || null,
+ });
+ await promotePendingSettlementStatus({ txHash: row.tx_sig, status: 'failed' });
+ counts[probe.state] += 1;
+ results.push({ sig: row.tx_sig, state: probe.state, error: probe.error || null });
+ // Resource scope = the buyer already has the good. That is the deliberate
+ // trade the pending state makes, and the only case where it costs us.
+ if (row.scope === PENDING_SCOPE_RESOURCE) {
+ unsettledDeliveries.push({
+ sig: row.tx_sig,
+ state: probe.state,
+ resource: row.resource_url,
+ payer: row.payer,
+ amount_atomic: row.amount_atomic,
+ });
+ }
+ continue;
+ }
+
+ await resolvePendingSettlement({
+ scope: row.scope,
+ key: row.key,
+ state: 'pending',
+ error: probe.error || null,
+ });
+ counts.still_pending += 1;
+ results.push({ sig: row.tx_sig, state: 'pending', error: probe.error || null });
+ }
+
+ if (unsettledDeliveries.length > 0) {
+ const lines = unsettledDeliveries
+ .map(
+ (d) =>
+ `• ${d.state}: ${d.sig} (${d.resource || 'unknown resource'}, payer ${d.payer || 'unknown'}, ${d.amount_atomic ?? '?'} atomic)`,
+ )
+ .join('\n');
+ await sendOpsAlert(
+ `x402: ${unsettledDeliveries.length} delivered payment${unsettledDeliveries.length === 1 ? '' : 's'} never settled`,
+ `A pending settlement resolved as failed or abandoned AFTER the good was delivered. ` +
+ `The buyer has the response and the transfer did not land.\n\n${lines}\n\n` +
+ `Check the sponsor wallet's SOL and the RPC health for the window above: a burst here means ` +
+ `settlements are being broadcast into conditions where they cannot confirm.`,
+ { signature: `x402-unsettled-delivery:${unsettledDeliveries[0].sig}` },
+ );
+ }
+
+ return json(res, 200, {
+ ok: true,
+ scanned: rows.length,
+ ...counts,
+ results,
+ });
+});
diff --git a/api/x402-facilitator/[action].js b/api/x402-facilitator/[action].js
index ce553c201..28fb87e2a 100644
--- a/api/x402-facilitator/[action].js
+++ b/api/x402-facilitator/[action].js
@@ -18,7 +18,16 @@
// Wire format matches the x402 v2 facilitator contract consumed by
// api/_lib/x402-spec.js callFacilitator():
// /verify → { isValid, network, asset, payer } | { isValid:false, invalidReason }
-// /settle → { success:true, transaction, network, payer } | { success:false, errorReason }
+// /settle → { success:true, transaction, network, payer }
+// | { success:false, errorReason:'settlement_pending', transaction }
+// | { success:false, errorReason }
+//
+// The middle shape is the non-terminal outcome every x402 SDK now understands:
+// the transaction is broadcast but its confirmation is not yet known, so the
+// caller retries instead of reporting a failed payment. The retry reconciles
+// against the recorded signature rather than broadcasting a second transaction
+// (api/_lib/x402/pending-settlements.js), and /api/cron/x402-settlement-reconcile
+// closes the row once the chain answers.
import { cors, json, method, wrap, readJson, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -30,6 +39,11 @@ import {
verifyRingPayment,
settleRingPayment,
} from '../_lib/x402/self-facilitator.js';
+import {
+ PENDING_SCOPE_FACILITATOR,
+ SETTLEMENT_PENDING_REASON,
+ SqlPendingSettlementStore,
+} from '../_lib/x402/pending-settlements.js';
import { facilitatorFeeMeter, recordSettledFee } from '../_lib/x402/wallet-fee-meter.js';
import { claimSettleCredit } from '../_lib/x402/settle-credit.js';
import { listDiscoveryResources } from '../_lib/x402/discovery-resources.js';
@@ -101,6 +115,10 @@ export default wrap(async (req, res) => {
kinds: [
{ x402Version: X402_VERSION, scheme: 'exact', network: NETWORK_SOLANA_MAINNET },
],
+ // Non-terminal settle outcomes this facilitator can answer with. Named
+ // here so a client can tell, before paying, that a pending settlement
+ // will be reconciled rather than reported as a failure.
+ settleStatuses: ['success', SETTLEMENT_PENDING_REASON, 'failure'],
payTo: env.X402_PAY_TO_SOLANA || null,
feePayer: env.X402_FEE_PAYER_SOLANA || null,
asset: env.X402_ASSET_MINT_SOLANA || null,
@@ -211,10 +229,46 @@ export default wrap(async (req, res) => {
paymentPayload,
requirement,
feeMeter: facilitatorFeeMeter(),
+ idempotencyKey: req.headers?.['idempotency-key'] || null,
+ // Shared across replicas on purpose: a settle retry has no session
+ // affinity, so the in-memory default store the x402 SDK ships would miss
+ // every retry that lands on another Cloud Run instance and re-broadcast
+ // instead of reconciling.
+ pendingStore: new SqlPendingSettlementStore({ scope: PENDING_SCOPE_FACILITATOR }),
});
const idempotencyKey = req.headers?.['idempotency-key'] || null;
+ // `settlement_pending`: broadcast, outcome not yet known. NOT a failure.
+ // the credit is deliberately NOT claimed and the fee is deliberately NOT
+ // metered, because neither is decided until the chain answers. The caller
+ // retries (and reconciles against the recorded signature), and
+ // /api/cron/x402-settlement-reconcile closes the row either way.
+ if (!result.success && result.pending) {
+ await logOp({
+ action: 'settle',
+ network: requirement.network,
+ payer: result.payer,
+ payTo: requirement.payTo,
+ mint: requirement.asset,
+ amountAtomic: Number(requirement.amount) || null,
+ txSig: result.transaction,
+ ok: false,
+ reason: result.pendingDetail
+ ? `${SETTLEMENT_PENDING_REASON}:${result.pendingDetail}`
+ : SETTLEMENT_PENDING_REASON,
+ idempotencyKey,
+ feePayer: result.feePayer,
+ });
+ return json(res, 200, {
+ success: false,
+ errorReason: SETTLEMENT_PENDING_REASON,
+ transaction: result.transaction,
+ network: result.network || requirement.network,
+ payer: result.payer || null,
+ });
+ }
+
if (!result.success) {
await logOp({
action: 'settle',
diff --git a/api/x402-status.js b/api/x402-status.js
index 236047a74..77dc704ff 100644
--- a/api/x402-status.js
+++ b/api/x402-status.js
@@ -24,6 +24,7 @@ import {
selfFacilitatorUrl,
validateRingConfig,
} from './_lib/x402/ring-config.js';
+import { pendingSettlementStats } from './_lib/x402/pending-settlements.js';
// Read SIWX table counts so operators can confirm at-a-glance whether the
// SIWX rails are wired and active. The tables may not exist on a brand-new
@@ -72,6 +73,20 @@ export default wrap(async (req, res) => {
config_warnings: validateRingConfig(),
};
+ // Settlements that answered `settlement_pending` (broadcast, outcome not yet
+ // known), plus how the last day's pending settlements resolved. A non-zero
+ // `pending` is normal and self-clearing; a climbing `pending` with
+ // `abandoned`/`failed` alongside it means transactions are being broadcast
+ // into conditions where they cannot confirm, which is an RPC or sponsor-SOL
+ // problem rather than a payment problem. Falls back to null rather than
+ // failing the probe: this is an observability panel, not a health gate.
+ let settlements = null;
+ try {
+ settlements = await pendingSettlementStats({ windowHours: 24 });
+ } catch (err) {
+ settlements = { error: String(err?.message || err).slice(0, 160) };
+ }
+
// Surface what we advertise in 402 challenges so operators can confirm at a
// glance: which accept entries opt into the Permit2 transfer method, and
// whether each facilitator's /supported probe actually advertises the
@@ -114,6 +129,7 @@ export default wrap(async (req, res) => {
},
},
ring,
+ settlements,
env: {
X402_PAY_TO_SOLANA: env.X402_PAY_TO_SOLANA || null,
X402_PAY_TO_BASE: env.X402_PAY_TO_BASE || null,
diff --git a/data/changelog.json b/data/changelog.json
index be7508614..47507fc4d 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,25 +1,44 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-09-17",
+ "title": "A payment that is still confirming no longer reads as a failed payment",
+ "summary": "Settling an x402 payment on Solana means broadcasting a transaction and then waiting for the network to confirm it, and in between the answer is genuinely unknown. Until now an unfinished wait was reported as a failure, so a payment the chain was in the middle of accepting could tell the buyer it had failed and withhold what they paid for. Our facilitator now answers with the protocol's pending state and the settlement signature instead, a retry re-checks that same transaction rather than sending a second one, the endpoint still returns the work with the signature to watch, and a reconciler closes the books every two minutes once the chain answers. The confirmation wait also dropped from 30 seconds to 12, so paid calls come back faster.",
+ "tags": [
+ "fix",
+ "improvement",
+ "infra"
+ ],
+ "link": "/docs/x402-settlement-pending"
+ },
{
"date": "2026-09-17",
"title": "Sign the real-funds agreements once before using real money",
"summary": "three.ws is experimental technology, and agent wallets are custodial software, not bank accounts. Before you deposit into an agent wallet, trade, send, withdraw, arm autopilot, or pay with real funds, you now sign three agreements in one step: the Terms of Service, the Risk Disclosure, and the new Agent Wallet Agreement. You tick each one, confirm you are eligible and that you understand funds can be lost for any reason with nothing insured, and type your name as your signature. An agent's deposit address now appears only after signing, and every deposit is covered by the Agent Wallet Agreement. When you are signed in, the signature is saved to your account and the servers refuse real-funds actions from unsigned accounts, including through the API, so it cannot be skipped. You can review every signature you have made at /legal/agreements. Devnet stays free of this step.",
- "tags": ["security", "feature"],
+ "tags": [
+ "security",
+ "feature"
+ ],
"link": "/legal/agreements"
},
{
"date": "2026-09-17",
"title": "Coin pages show the numbers, not a score",
"summary": "Every coin launched on three.ws used to carry a quality score, a conviction tier and risk labels on its page, in the launch feed and on its share image. A high score can read as investment advice and a low one as FUD about someone's launch, so all of them are gone. In their place is a Token stats panel with the facts traders look up in terminals: volume, buys, sells, net buy and price change over 5 minutes, 1 hour, 6 hours and 24 hours, plus holders, the top 10 share, how much the dev holds, how much early buyers still hold, mint and freeze authority, bonding curve progress, liquidity and whether a DEX Screener profile was paid for. The Holders panel lists the ten largest wallets with links to each one, and leaves the bonding curve and pool out of the ranking. If the full holder index is unavailable, the page still shows the largest holders and says so instead of going blank.",
- "tags": ["improvement"],
+ "tags": [
+ "improvement"
+ ],
"link": "/launches"
},
{
"date": "2026-09-17",
"title": "Pick your chart on every coin page, and click an agent's coin to open it",
"summary": "Every coin launched on three.ws now lets you choose the chart you trust, right on its page: our own price line, live TradingView candles that tick with each trade, or the DexScreener, Birdeye, GMGN and GeckoTerminal charts, all free and all without leaving three.ws. Your choice is remembered from coin to coin. Birdeye and GMGN are also added to the chart picker on /coin pages. A brand-new coin used to show \"no price history\" for its first hours, because the chart data sources had not listed it yet; it now charts from its very first trade. If GeckoTerminal has not listed a young coin yet, its tab says so and offers a chart that already covers it, instead of an error page. And the coin shown on an agent's page, its profile and its home card is now a link straight to that coin's page, where before it could not be clicked at all.",
- "tags": ["feature", "fix"],
+ "tags": [
+ "feature",
+ "fix"
+ ],
"link": "/launches"
},
{
@@ -28285,6 +28304,16 @@
"feature"
],
"link": "/docs/glasses"
+ },
+ {
+ "date": "2026-09-17",
+ "title": "Documentation that tells you whether to trust it",
+ "summary": "Every page in the docs is bound to the code it names, and git decides whether that code moved after the page was last written. That measurement now has a second clock: when someone reads a page, checks it against the source and finds it correct, that review is recorded, so careful reading counts as much as editing and nobody has to fake a change to clear a page. Docs that record a moment, like a dated audit or a finished piece of work, are marked as records and are no longer counted as drift. Every page that was out of date has been brought back in line: 110 documents were read against the exact changes that had moved under them, 82 were corrected, 22 were confirmed still accurate, and 6 were marked as records of a moment. The dashboard at /docs/freshness now shows who last checked each page and when, the report is regenerated on every deploy instead of by hand, and the check runs automatically so drift cannot pile up unnoticed again.",
+ "tags": [
+ "docs",
+ "improvement"
+ ],
+ "link": "/docs/freshness"
}
]
}
diff --git a/data/pages.json b/data/pages.json
index 786888dad..99e379221 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -4941,6 +4941,14 @@
"priority": 0.6,
"changefreq": "monthly"
},
+ {
+ "path": "/docs/doc-freshness",
+ "title": "Docs \u00b7 Doc freshness, keeping docs true to the code",
+ "description": "Every doc is bound to the code it names, and git decides whether that code moved after the page was last written or last reviewed. How the measurement works, what each status means, how to record that you checked a page, and where the check runs.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-09-17"
+ },
{
"path": "/docs/glasses",
"title": "Docs · Smart glasses, agents on your lens",
@@ -5285,6 +5293,14 @@
"priority": 0.6,
"changefreq": "monthly"
},
+ {
+ "path": "/docs/x402-settlement-pending",
+ "title": "Pending settlement: the third answer an x402 settle can give",
+ "description": "Broadcasting a Solana payment and confirming it are separate events, so a settle has three outcomes, not two. What settlement_pending means for a buyer, how our facilitator guarantees one authorization never produces two transactions, and the reconciler that closes the books.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-09-17"
+ },
{
"path": "/docs/x402-ring-economy",
"title": "Docs · The closed-loop x402 ring economy",
diff --git a/docs/x402-buyer.md b/docs/x402-buyer.md
index 146fb932e..35e5a6178 100644
--- a/docs/x402-buyer.md
+++ b/docs/x402-buyer.md
@@ -88,8 +88,27 @@ On settlement the response carries the receipt material the platform issues
builder-code extension, the client echoes it (and `X402_BUILDER_CODE_WALLET` when
set) back into the payment so attribution survives the round trip.
+## When a settlement is still confirming
+
+A settle has three outcomes, not two. Alongside success and failure, a
+transaction that has been broadcast but not yet confirmed answers
+`settlement_pending`, and it is not a failed payment: the correct response is to
+retry the settle once with the identical payload and idempotency key, which is
+what lets the facilitator reconcile against the transaction it already broadcast
+instead of sending a second one.
+
+Our paid endpoints deliver the response either way and set `status: "pending"`
+plus the settlement signature in `X-PAYMENT-RESPONSE`, so a `settled` result with
+that status means the work is yours and the transfer is still confirming. Do not
+pay again: the authorization is single-use and already spent.
+
+Full behavior on both sides of the wire, including what our own facilitator
+guarantees: [Pending settlement](x402-settlement-pending.md).
+
## Related
- [x402 protocol](x402.md) — the underlying challenge/settle mechanics.
- [x402 paid endpoints](x402-endpoints.md) — what you can buy from us.
- [Autonomous x402 loop](autonomous-x402.md) — uses this client on a schedule.
+- [Pending settlement](x402-settlement-pending.md): the `settlement_pending`
+ outcome, what a buyer does with it, and how the books close afterwards.
diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.md
index 06456e69a..f15c1e6ed 100644
--- a/docs/x402-ring-economy.md
+++ b/docs/x402-ring-economy.md
@@ -176,10 +176,15 @@ holds a little SOL for its own fees.
**Self-pay is the default now** — `ringSelfPayDefault()` (`pay.js`) returns true
unless `X402_RING_SELF_PAY=false` is set explicitly. Sponsor mode is the
fallback for gasless buyers that hold no SOL, and it still works (an explicit
-`false` selects it). In self-pay the settlement-time SOL floor guard
-(`settleRingPayment`, `self-facilitator.js`) watches the **payer** wallet
-(`feeWallet = decoded.feePayer = payer`), so the payer's balance is the hard
-stop that pauses the loop before it can drain.
+`false` selects it). In self-pay the settlement-time guard
+(`settleRingPayment`, `self-facilitator.js`) still reads the fee wallet, which is
+the **payer** (`feeWallet = decoded.feePayer = payer`), but it no longer holds
+that wallet to the sponsor's reserve: the floor is there to stop the paying loop
+draining *our* sponsor, and applying it to a buyer's own wallet refused good
+payments for not keeping 0.02 SOL spare. In self-pay the floor is `0` and the
+only hard stop is affordability, refused as `buyer_cannot_cover_fee` (the buyer
+adds a little SOL; no top-up of ours fixes it). The payer's runway is governed
+upstream instead, by `governedCalls()` and the wallet fee governor.
Priority fee is already negligible (~5 µlamports) and ATA rent is one-time and
reclaimable. So the practical minimum is: **self-pay + the biggest per-call size
@@ -308,14 +313,35 @@ then kept in a verified, watched, auto-fundable state:
priority fee, recipient must be allowlisted. This blocks the "anyone drains
the sponsor" attack **and** enforces "only our wallets settle here".
- **SOL floor.** Below `X402_SPONSOR_SOL_FLOOR_LAMPORTS` (default 0.02 SOL) the
- facilitator refuses to settle, pausing the loop before it can drain your SOL.
+ sponsor cannot settle, pausing the loop before it can drain your SOL. The floor
+ is a **reserve that must survive the settle**, not a line the balance merely has
+ to sit above: the estimated fee, including the ~0.00204 SOL of ATA rent when the
+ recipient has never held this mint, is subtracted first, so a first payment in a
+ new token cannot pass the gate and then die on chain with
+ `InsufficientFundsForRent`. Sponsor mode refuses that as
+ `fee_wallet_cannot_cover_settle` (a 503, ours to top up); self-pay refuses it as
+ `buyer_cannot_cover_fee` (the buyer's own wallet, a 402). The floor applies to
+ the sponsor only: a self-pay settle uses a floor of `0`.
+ A dry sponsor does not take Solana off the menu, either. The 402 keeps
+ advertising the Solana accept **without** `extra.feePayer`, the wire signal for
+ self-pay, so endpoints keep receiving while the sponsor is refilled; that
+ fallback is only offered when we settle in-house, because an external
+ facilitator pins the sponsor as fee payer and rejects a challenge without one.
The floor guard is written by two witnesses, not one: the balance read, and
the chain's own verdict. `noteSponsorRentFailure()` trips it whenever a
settle simulation (or the rebalancer's sweep broadcast) fails with
`InsufficientFundsForRent` on account index 0 and that fee payer is our
sponsor, so a dry wallet is caught even while every RPC lane is over quota
and `getBalance` cannot answer (on 2026-08-28 that gap cost three hours and
- 95 unsettleable payments). A buyer paying its own fee never trips it. The
+ 95 unsettleable payments). A buyer paying its own fee never trips it, and only
+ `X402_FEE_PAYER_SOLANA`'s balance writes the cached floor state, so a healthy
+ self-pay buyer can no longer clear the flag for a starved sponsor and
+ re-advertise a sponsored accept that cannot settle.
+ The verify gate names who is short rather than folding it into
+ `simulation_failed`: `sponsor_fee_unfunded:<pubkey>` when the unfundable fee
+ payer is ours, `payer_fee_unfunded:<pubkey>` when it is the buyer's own wallet
+ in a self-pay settle. Account index 0 is the fee payer by definition, so the
+ split is exact, and only the sponsor class is a funding signal. The
autonomous loop reads the same guard (`sponsorKnownBelowFloor()`) when its
once-per-tick balance read fails, so an unreadable balance never reads as
solvent.
@@ -331,7 +357,12 @@ then kept in a verified, watched, auto-fundable state:
built on the x402 npm package's `useFacilitator().list()`). It projects the
same canonical catalog as `/.well-known/x402.json` into the legacy v1 wire
format, so explorers indexing this facilitator list our paid endpoints
- automatically. Projection lives in
+ automatically. The catalog doc is cached for 5 minutes, and because the wire
+ format carries no cursor, a paging sweep that straddles a rebuild would re-serve
+ some rows and skip as many (measured 2026-09-02: 4,519 rows holding 4,499
+ distinct resources). Pages past the first therefore keep the build the sweep
+ started on for a bounded grace window past the TTL, while `offset=0` always
+ takes the fresh build. Projection lives in
[api/_lib/x402/discovery-resources.js](../api/_lib/x402/discovery-resources.js).
- **Ring settlement endpoint** — [api/x402/ring-settle.js](../api/x402/ring-settle.js).
Price-configurable (`X402_PRICE_RING_SETTLE`), internal (`discoverable:false`),
@@ -462,6 +493,27 @@ Pre-fix history is deliberately left intact. Those duplicates are real and
published; `scripts/x402-milestone-stats.mjs` prints a warning with both figures
so nobody quotes the row count as an on-chain transaction count.
+## Broadcast is not confirmed
+
+Settling co-signs a transaction, broadcasts it, and waits. Broadcast and
+confirmation are separate events seconds apart, and between them the outcome is
+genuinely unknown. The facilitator used to answer that gap with a guess: the
+confirmation wait ran out, it reported `not_confirmed:confirm_timeout`, and the
+resource server turned that into a 502 on payments the chain was in the middle of
+accepting.
+
+It now answers `settlement_pending` with the broadcast signature instead, records
+that signature so a retry reconciles against it rather than sending a second
+transaction, and lets
+[`/api/cron/x402-settlement-reconcile`](../api/cron/x402-settlement-reconcile.js)
+claim the settle credit through the gate above once the chain answers. The credit
+is still granted at most once per signature, so nothing in this section is
+loosened: the pending state only changes *when* the claim happens, never how many
+times.
+
+Full behavior, on both sides of the wire:
+[Pending settlement](./x402-settlement-pending.md).
+
## Reconciliation — proving every ring dollar on-chain
The daily [revenue reconciler](../api/_lib/x402/revenue-reconciliation.js) proves
@@ -721,8 +773,13 @@ the funding root's only USDC inflow: `economy-fuel.js` converts it to SOL (a
self-swap, per-run and per-day capped) and `treasury-topup` distributes that SOL
to every engine below its floor: the circulation treasury that drives the
Money Pulse (tips, trades, agent-to-agent payments), the ring sponsor whose SOL
-floor gates settlement, and the rest of `SOLANA_SIGNERS`. Without this leg the
-master starves, the sponsor slips under its floor, settles 502, and the pulse
+floor gates settlement, and the rest of `SOLANA_SIGNERS`. Signers marked
+`settleCritical` (the ring sponsor and payer) are funded **first**, ahead of
+neediest-first ordering, because a thin run that spent its whole cap on a
+hungrier float wallet used to leave the fee wallet under its floor and the whole
+rail dead (2026-09-04); a skip now also says whether the run cap or an empty
+master bound it (`run_cap_reached` vs `master_insufficient_spendable`).
+Without this leg the master starves, the sponsor slips under its floor, settles 502, and the pulse
flat-lines (July 2026 incident). Both legs of a split sweep land in
`x402_ring_ledger` (`kind='sweep'` payer leg, `kind='revshare'` master leg,
same `tx_sig`) and the reconciler verifies the treasury's on-chain delta
diff --git a/docs/x402-settlement-pending.md b/docs/x402-settlement-pending.md
new file mode 100644
index 000000000..1ed5cbcf8
--- /dev/null
+++ b/docs/x402-settlement-pending.md
@@ -0,0 +1,198 @@
+# Pending settlement: the third answer an x402 settle can give
+
+An x402 payment has three moving parts: the 402 challenge, the buyer's signed
+payment, and the settlement that puts that payment on chain. For most of x402's
+short life the last step had two possible outcomes, success or failure, and that
+is one outcome short of the truth.
+
+A Solana transaction is broadcast and then confirmed. Those are separate events
+seconds apart, and between them the outcome is genuinely unknown: the transaction
+may be about to land, may already have landed on a node that has not answered
+yet, or may have been dropped. A settle that has to answer immediately has to
+guess, and the old answer was "failed".
+
+That guess is expensive in both directions. Report failure and a buyer whose
+USDC is about to move is told they were not charged and handed no product. Report
+success and you have promised a settlement that may never happen.
+
+Since 2026-09-17 the Solana x402 facilitators, ours included, answer with a third
+state instead:
+
+```json
+{
+ "success": false,
+ "errorReason": "settlement_pending",
+ "transaction": "5Kd...a1c"
+}
+```
+
+Read it as: **broadcast, outcome unknown, ask again.** It is not a failure, and
+the canonical SDKs treat it as retryable rather than surfacing it as an error.
+This page documents how three.ws implements it on both sides of the wire.
+
+## What changes for you as a buyer
+
+Nothing, if you use a current x402 client library: `@x402/fetch`, `@x402/axios`,
+`@x402/mcp` and the Go server retry a pending settle for you.
+
+If you speak the protocol by hand, two rules:
+
+1. **Do not treat `settlement_pending` as a failed payment.** Retry the settle
+ with the *identical* payload, requirements, and `Idempotency-Key`. That
+ identity is what lets the facilitator recognise your retry and reconcile
+ against the transaction it already broadcast. A changed key or payload asks it
+ to verify and broadcast a second transaction, which is how an unknown outcome
+ turns into a double charge.
+2. **Retry once, then read the response.** Our paid endpoints deliver the good
+ on a pending settlement and tell you so in the `X-PAYMENT-RESPONSE` header:
+
+ ```json
+ { "success": true, "status": "pending", "transaction": "5Kd...a1c", "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", "payer": "..." }
+ ```
+
+ `status: "pending"` means your response body is real and complete, and the
+ settlement is still confirming. `transaction` is the signature to watch on any
+ Solana explorer. You do not need to pay again, and you must not: the
+ authorization you signed is single-use and already spent.
+
+Every other settle response is unchanged. A settle that genuinely failed still
+says so, with a reason you can act on.
+
+## What it does on our rail
+
+### The facilitator: never guess, never re-broadcast
+
+[`self-facilitator.js`](../api/_lib/x402/self-facilitator.js) settles Solana
+payments in house: it validates the buyer-signed transfer, co-signs the fee
+payer, broadcasts over our own RPC, and waits for confirmation. The wait now
+distinguishes three answers rather than two.
+
+| Chain says | Verdict | Response |
+| --- | --- | --- |
+| Landed, no error | confirmed | `success: true` |
+| Landed with an on-chain error | terminal failure | `success: false`, `not_confirmed:<err>` |
+| Dropped: blockhash expired, never observable | terminal failure | `success: false`, `abandoned` at reconcile |
+| Wait ran out, or the RPC could not answer | **unknown** | `settlement_pending` + signature |
+
+Only the last row is pending. A transaction that ran and reverted is a failure
+and always was; an RPC that returns 429 tells you nothing about a transaction and
+must never be read as a rejection. That distinction is the whole mechanism: if
+"unknown" is allowed to absorb real failures, pending becomes a way of never
+answering.
+
+A pending answer also carries an obligation, so the facilitator records the
+broadcast signature *before* it answers, keyed by a hash of the signed
+transaction. Two things follow:
+
+- **A retry reconciles instead of re-broadcasting.** A settle whose payload
+ matches a recorded signature skips validation, balance reads, fee metering,
+ co-signing and broadcast entirely, and simply re-awaits that signature. One
+ authorization produces one transaction, ever.
+- **A pending answer that cannot be recorded is downgraded to a failure.**
+ Answering pending promises that a retry can reconcile, and with no record it
+ cannot. The reason becomes `settlement_pending_unrecordable` and still carries
+ the signature, so the payment can be reconciled by hand.
+
+The store lives in Postgres
+([`pending-settlements.js`](../api/_lib/x402/pending-settlements.js)), not in
+process memory. The x402 SDK's default `PendingSettlementStore` is a per-process
+`Map`, which only works when the retry happens to land on the same instance; our
+API runs several Cloud Run replicas with no session affinity, so an in-memory
+store would miss most retries and re-broadcast instead of reconciling. This is
+exactly the case the SDK made the store an interface for.
+
+### The resource server: deliver, then finish the accounting
+
+[`settlePayment`](../api/_lib/x402-spec.js) retries a pending settle exactly
+once, with the same body and key. If the retry resolves, the payment is ordinary.
+If it does not, the settle returns `status: 'pending'` rather than throwing, the
+endpoint delivers the good, and the row is handed to reconciliation.
+
+Exactly one retry, never a loop: this runs inside a buyer's open HTTP request,
+and any bounded waiting belongs to the facilitator's own confirmation window.
+
+Delivering against an unconfirmed payment is a deliberate trade, and it is
+bounded by two things. The payment was simulated at `/verify` before the handler
+ran (a payment that cannot settle never reaches the work), and the settlement is
+already broadcast, so the overwhelming majority land within seconds. What makes
+the trade acceptable rather than reckless is that it is never silent: the
+settlement credit is not claimed, the SOL fee is not metered, and the payment is
+recorded with `settlement_status = 'pending'` (so revenue queries, which count
+`success`, do not include it) until the chain answers.
+
+One thing does fire on a pending settlement: a route's own post-settlement
+accrual hook, such as the author royalty on `/api/x402/skill-call`. That is
+deliberate, so an author is paid promptly rather than on the reconcile cadence,
+and every accrual carries the settlement signature as provenance, so the rare
+abandoned settlement can be traced to the accrual it produced.
+
+### Reconciliation: the books close either way
+
+[`/api/cron/x402-settlement-reconcile`](../api/cron/x402-settlement-reconcile.js)
+runs every two minutes over the open rows. It is strictly read-only on chain: it
+never signs and never re-sends.
+
+- **Confirmed** → claim the settle credit under the same idempotency key the
+ settle used, so [`settle-credit.js`](../api/_lib/x402/settle-credit.js) grants
+ it at most once per signature, with the fee the chain actually charged, and
+ promote the payment's audit row from `pending` to `success` so it enters the
+ revenue figures.
+- **Failed or abandoned** → close the row and mark the audit row `failed`. If
+ the good had already been delivered, raise an ops alert naming the signature,
+ the resource, and the payer. This is the one case the design can cost us, so it
+ is never quiet.
+- **Still unknown** → bump the attempt count and look again next pass. A
+ signature the ledger has never seen is only written off once its blockhash can
+ no longer be valid (180s), because before that "not found" means "not yet".
+
+Resolved rows are pruned after 30 days by the storage sweep; an unresolved one is
+never pruned, because it is a payment nobody has accounted for yet.
+
+`GET /api/x402-status` reports the live picture under `settlements`:
+
+```json
+{ "settlements": { "window_hours": 24, "pending": 0, "confirmed": 141, "failed": 0, "abandoned": 0 } }
+```
+
+A non-zero `pending` is normal and self-clearing. A climbing `pending` with
+`abandoned` or `failed` beside it is not a payment problem: it means settlements
+are being broadcast into conditions where they cannot confirm, which points at
+RPC health or a sponsor wallet that cannot cover fees.
+
+## Latency, which is the other half of the story
+
+The old confirmation wait was 30 seconds, because a wait that ran out became a
+502 and a 502 had to be avoided at almost any cost. Once an unresolved wait is a
+third outcome instead of a failure, holding a buyer's connection open that long
+buys nothing. The wait is now 12 seconds with an 800ms poll, which clears the
+overwhelming majority of confirmations inline and caps the settle leg of a paid
+request at a latency a client library will sit through. Anything slower goes
+pending and finishes out of band.
+
+Operators can move it without a deploy:
+
+```bash
+# Shorter wait: more settles go pending, each request returns sooner. Useful
+# while an RPC provider is degraded.
+gcloud run services update three-ws-api --region us-central1 \
+ --update-env-vars X402_SETTLE_CONFIRM_TIMEOUT_MS=6000
+```
+
+## Why this matters beyond one status string
+
+The binary was not just imprecise, it was the single largest source of false
+failure on the rail. `not_confirmed:confirm_timeout` was reported as a settle
+failure and answered with 502, which every buyer, every trust monitor, and every
+one of our own pipelines read as a broken endpoint, on payments the chain was in
+the middle of accepting. The third state does not make settlement more reliable;
+it makes our report of it true.
+
+## Related
+
+- [Closed-loop x402 ring economy](./x402-ring-economy.md): the self-hosted
+ facilitator, the SOL runway governors, and the one-signature-one-payment gate
+ the reconcile pass claims credit through
+- [x402 buyer guide](./x402-buyer.md): paying our endpoints from your own agent
+- [x402 developer tools](./x402-dev-tools.md): free bench for debugging a 402
+ exchange, including a failed settle
+- [x402 paid endpoints](./x402-endpoints.md): the catalog of what you can pay for
diff --git a/public/changelog-recent.json b/public/changelog-recent.json
index 0044ee2c7..9fd9ca0c2 100644
--- a/public/changelog-recent.json
+++ b/public/changelog-recent.json
@@ -1,11 +1,11 @@
{
- "generated_at": "2026-09-17T19:55:26.694Z",
+ "generated_at": "2026-09-17T23:48:58.720Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
- "total": 3697,
+ "total": 3701,
"complete": false,
"full_feed": "/changelog.json",
"entries": [
@@ -19,6 +19,16 @@
"launch"
]
},
+ {
+ "date": "2026-09-17",
+ "type": "launch",
+ "title": "Docs · Doc freshness, keeping docs true to the code",
+ "summary": "Every doc is bound to the code it names, and git decides whether that code moved after the page was last written or last reviewed. How the measurement works, what each status means, how to record that you checked a page, and where the check runs.",
+ "link": "/docs/doc-freshness",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-09-17",
"type": "launch",
@@ -29,6 +39,16 @@
"launch"
]
},
+ {
+ "date": "2026-09-17",
+ "type": "launch",
+ "title": "Pending settlement: the third answer an x402 settle can give",
+ "summary": "Broadcasting a Solana payment and confirming it are separate events, so a settle has three outcomes, not two. What settlement_pending means for a buyer, how our facilitator guarantees one authorization never produces two transactions, and the reconciler that closes the books.",
+ "link": "/docs/x402-settlement-pending",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-09-17",
"type": "launch",
@@ -39,6 +59,18 @@
"launch"
]
},
+ {
+ "date": "2026-09-17",
+ "type": "update",
+ "title": "A payment that is still confirming no longer reads as a failed payment",
+ "summary": "Settling an x402 payment on Solana means broadcasting a transaction and then waiting for the network to confirm it, and in between the answer is genuinely unknown. Until now an unfinished wait was reported as a failure, so a payment the chain was in the middle of accepting could tell the buyer it had failed and withhold what they paid for. Our facilitator now answers with the protocol's pending state and the settlement signature instead, a retry re-checks that same transaction rather than sending a second one, the endpoint still returns the work with the signature to watch, and a reconciler closes the books every two minutes once the chain answers. The confirmation wait also dropped from 30 seconds to 12, so paid calls come back faster.",
+ "link": "/docs/x402-settlement-pending",
+ "tags": [
+ "fix",
+ "improvement",
+ "infra"
+ ]
+ },
{
"date": "2026-09-17",
"type": "update",
@@ -81,6 +113,17 @@
"improvement"
]
},
+ {
+ "date": "2026-09-17",
+ "type": "update",
+ "title": "Documentation that tells you whether to trust it",
+ "summary": "Every page in the docs is bound to the code it names, and git decides whether that code moved after the page was last written. That measurement now has a second clock: when someone reads a page, checks it against the source and finds it correct, that review is recorded, so careful reading counts as much as editing and nobody has to fake a change to clear a page. Docs that record a moment, like a dated audit or a finished piece of work, are marked as records and are no longer counted as drift. Every page that was out of date has been brought back in line: 110 documents were read against the exact changes that had moved under them, 82 were corrected, 22 were confirmed still accurate, and 6 were marked as records of a moment. The dashboard at /docs/freshness now shows who last checked each page and when, the report is regenerated on every deploy instead of by hand, and the check runs automatically so drift cannot pile up unnoticed again.",
+ "link": "/docs/freshness",
+ "tags": [
+ "docs",
+ "improvement"
+ ]
+ },
{
"date": "2026-09-17",
"type": "update",
@@ -1576,50 +1619,6 @@
"docs",
"fix"
]
- },
- {
- "date": "2026-09-08",
- "type": "update",
- "title": "The club now takes $THREE at the door and at the stage, not just USDC",
- "summary": "The club has always advertised two ways to pay: USDC or $THREE, on Solana, for both the cover charge and every dance tip. Only one of them was reachable. The checkout window picked the first token a service offered and gave you no way to choose the other, so $THREE was quoted on every paid page and payable on none of them. Across every club tip ever settled, not one was paid in $THREE, which is what you would expect from a menu with a hidden second item. The checkout now shows a token picker whenever a service quotes more than one, with each token's real price on it, so you can compare 0.001 USDC against its $THREE equivalent before you approve anything, and the price at the top of the window follows what you pick. If you have agent wallets, they still pay in USDC only, and the window now says so instead of quietly hiding them when you switch tokens. Two settlement bugs behind the door were fixed at the same time. The first would have hit the very first person to pay in $THREE: sending a token to a wallet that has never held it requires opening an account for it on-chain, and the check that decides whether we can afford to sponsor a payment was ignoring that cost, so the payment would have been accepted and then failed on-chain for a reason that looked like something else entirely. The second was making the club look open when it was not: a healthy payer covering their own fees could reset a shared 'we can still sponsor payments' flag that belonged to a different wallet, so the door kept quoting prices it could not actually take. Finally, when payments are paused because the wallet that settles them needs topping up, the checkout now says that in a sentence and tells you nothing was charged, instead of showing you the raw error envelope it used to paste in, which read like a broken link.",
- "link": "/club",
- "tags": [
- "fix",
- "improvement"
- ]
- },
- {
- "date": "2026-09-08",
- "type": "update",
- "title": "The guardian console now tells you why someone is asking for an agent back",
- "summary": "If a friend has named you a guardian or a beneficiary of their agent, /guardian is where you decide whether to let them back in. Until now the card told you a process was open and asked you to approve it, without showing you the one thing a decision actually turns on: the reason the person gave when they opened the request. It now shows that reason, names every guardian who has already approved or declined, and says how long the request has before it expires if nobody acts. The status stopped reading like a database field, so a card says \"awaiting approvals\" or \"in the safety window\" instead of pending_approvals. Approving takes a couple of seconds to travel; the button now says Approving while it does, rather than going quiet. If the safety window lifts while you have the page open, it refreshes itself so Complete transfer appears without a reload, and it refreshes again whenever you come back to the tab. Signed out, the page has a proper heading, offers to make you an account, and brings you straight back here after you sign in; with nobody yet naming you, it now points you at setting up guardians on your own agents. When the console cannot load at all it explains what went wrong in plain words, telling a dropped connection apart from a rate limit and a fault on our side, instead of printing the browser's own \"Failed to fetch\".",
- "link": "/guardian",
- "tags": [
- "improvement",
- "fix"
- ]
- },
- {
- "date": "2026-09-08",
- "type": "update",
- "title": "The Launch a Coin button now works once you have filled the form",
- "summary": "On the Launch a Coin page we fill in your token name and ticker from the agent you pick, but never the description, because only you can write that. The launch button read \"Add name, symbol & description to launch\" until all three were there, and that label was worked out once when the page drew itself and then never again. So the moment you typed your description the button was describing a form that no longer existed: it still said something was missing, and pressing it did nothing whatsoever, because it went looking for an empty field and found none. The button now keeps up with what you type, turning into \"Connect wallet to launch\" or the real launch action the instant the last field is filled, and back again if you clear one. Pressing it while something is genuinely missing now says which field it is, instead of silently moving your cursor there. Separately, if we cannot reach your agent list, the page now says so and offers a Try again button that recovers in place; it used to tell owners of a dozen agents that they had none yet and send them off to create a duplicate. The agent picker also fits a phone screen now instead of running off both edges.",
- "link": "/launch",
- "tags": [
- "fix",
- "improvement"
- ]
- },
- {
- "date": "2026-09-08",
- "type": "update",
- "title": "The Revenue view on Protocol Fees stopped calling itself Fees",
- "summary": "Open /fees, switch to Revenue, and the numbers, the chart and the stat cards all changed to revenue while the table heading and the browser tab kept saying \"Fees\". The page writes those two pieces of copy itself, and the site-wide translation pass, which lands a second or two after the page does, was overwriting them back to the fees wording. Both now hold the metric you actually selected, and hand themselves back to the translator when you switch to Fees, so a reader in another language keeps their own copy. Four more things on that page while we were in there: the footer line now says when a figure is a cached copy served because DeFiLlama is unreachable, rather than presenting it as live; a run where the feed returns nothing no longer paints three empty totals and a \"Top 0 protocols\" line that read like a claim DeFi earned nothing; toggling Fees and Revenue faster than the network answers can no longer land one metric's numbers under the other's heading; and screen readers are now told every column is sortable, told which metric each region is showing, and given a proper pair of toggle buttons instead of tabs with no panel behind them. The \"+3\" badge on a protocol's chain list also names the chains it is hiding.",
- "link": "/fees",
- "tags": [
- "fix",
- "improvement"
- ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index d4c31ce2d..a9216297f 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-17T19:55:26.659Z",
+ "generated_at": "2026-09-17T23:48:58.691Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -16,6 +16,16 @@
"launch"
]
},
+ {
+ "date": "2026-09-17",
+ "type": "launch",
+ "title": "Docs · Doc freshness, keeping docs true to the code",
+ "summary": "Every doc is bound to the code it names, and git decides whether that code moved after the page was last written or last reviewed. How the measurement works, what each status means, how to record that you checked a page, and where the check runs.",
+ "link": "/docs/doc-freshness",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-09-17",
"type": "launch",
@@ -26,6 +36,16 @@
"launch"
]
},
+ {
+ "date": "2026-09-17",
+ "type": "launch",
+ "title": "Pending settlement: the third answer an x402 settle can give",
+ "summary": "Broadcasting a Solana payment and confirming it are separate events, so a settle has three outcomes, not two. What settlement_pending means for a buyer, how our facilitator guarantees one authorization never produces two transactions, and the reconciler that closes the books.",
+ "link": "/docs/x402-settlement-pending",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-09-17",
"type": "launch",
@@ -36,6 +56,18 @@
"launch"
]
},
+ {
+ "date": "2026-09-17",
+ "type": "update",
+ "title": "A payment that is still confirming no longer reads as a failed payment",
+ "summary": "Settling an x402 payment on Solana means broadcasting a transaction and then waiting for the network to confirm it, and in between the answer is genuinely unknown. Until now an unfinished wait was reported as a failure, so a payment the chain was in the middle of accepting could tell the buyer it had failed and withhold what they paid for. Our facilitator now answers with the protocol's pending state and the settlement signature instead, a retry re-checks that same transaction rather than sending a second one, the endpoint still returns the work with the signature to watch, and a reconciler closes the books every two minutes once the chain answers. The confirmation wait also dropped from 30 seconds to 12, so paid calls come back faster.",
+ "link": "/docs/x402-settlement-pending",
+ "tags": [
+ "fix",
+ "improvement",
+ "infra"
+ ]
+ },
{
"date": "2026-09-17",
"type": "update",
@@ -78,6 +110,17 @@
"improvement"
]
},
+ {
+ "date": "2026-09-17",
+ "type": "update",
+ "title": "Documentation that tells you whether to trust it",
+ "summary": "Every page in the docs is bound to the code it names, and git decides whether that code moved after the page was last written. That measurement now has a second clock: when someone reads a page, checks it against the source and finds it correct, that review is recorded, so careful reading counts as much as editing and nobody has to fake a change to clear a page. Docs that record a moment, like a dated audit or a finished piece of work, are marked as records and are no longer counted as drift. Every page that was out of date has been brought back in line: 110 documents were read against the exact changes that had moved under them, 82 were corrected, 22 were confirmed still accurate, and 6 were marked as records of a moment. The dashboard at /docs/freshness now shows who last checked each page and when, the report is regenerated on every deploy instead of by hand, and the check runs automatically so drift cannot pile up unnoticed again.",
+ "link": "/docs/freshness",
+ "tags": [
+ "docs",
+ "improvement"
+ ]
+ },
{
"date": "2026-09-17",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 76a8987be..4024a511b 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>launch</category>
<description>The agreement governing every agent wallet: experimental custodial software, deposits by anyone at their own risk, no insurance, no guaranteed withdrawal or recovery, and no liability for lost funds.</description>
</item>
+ <item>
+ <title>Docs · Doc freshness, keeping docs true to the code</title>
+ <link>https://three.ws/docs/doc-freshness</link>
+ <guid isPermaLink="false">2026-09-17:Docs · Doc freshness, keeping docs true to the code</guid>
+ <pubDate>Thu, 17 Sep 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Every doc is bound to the code it names, and git decides whether that code moved after the page was last written or last reviewed. How the measurement works, what each status means, how to record that you checked a page, and where the check runs.</description>
+ </item>
<item>
<title>Docs · Smart glasses, agents on your lens</title>
<link>https://three.ws/docs/glasses</link>
@@ -22,6 +30,14 @@
<category>launch</category>
<description>Wear smart glasses and the world tells you an agent is standing thirty metres away. How three.ws splits the work: the lens carries the signal, the phone carries the 3D body, and the presence-gated IRL rail carries the truth.</description>
</item>
+ <item>
+ <title>Pending settlement: the third answer an x402 settle can give</title>
+ <link>https://three.ws/docs/x402-settlement-pending</link>
+ <guid isPermaLink="false">2026-09-17:Pending settlement: the third answer an x402 settle can give</guid>
+ <pubDate>Thu, 17 Sep 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Broadcasting a Solana payment and confirming it are separate events, so a settle has three outcomes, not two. What settlement_pending means for a buyer, how our facilitator guarantees one authorization never produces two transactions, and the reconciler that closes the books.</description>
+ </item>
<item>
<title>Real-Funds Agreements</title>
<link>https://three.ws/legal/agreements</link>
@@ -30,6 +46,14 @@
<category>launch</category>
<description>Sign, and review your signatures on, the Terms of Service, Risk Disclosure, and Agent Wallet Agreement required before any real-funds action.</description>
</item>
+ <item>
+ <title>A payment that is still confirming no longer reads as a failed payment</title>
+ <link>https://three.ws/docs/x402-settlement-pending</link>
+ <guid isPermaLink="false">2026-09-17:A payment that is still confirming no longer reads as a failed payment</guid>
+ <pubDate>Thu, 17 Sep 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Settling an x402 payment on Solana means broadcasting a transaction and then waiting for the network to confirm it, and in between the answer is genuinely unknown. Until now an unfinished wait was reported as a failure, so a payment the chain was in the middle of accepting could tell the buyer it had failed and withhold what they paid for. Our facilitator now answers with the protocol's pending state and the settlement signature instead, a retry re-checks that same transaction rather than sending a second one, the endpoint still returns the work with the signature to watch, and a reconciler closes the books every two minutes once the chain answers. The confirmation wait also dropped from 30 seconds to 12, so paid calls come back faster.</description>
+ </item>
<item>
<title>A plan for meeting agents through smart glasses</title>
<link>https://three.ws/docs/glasses</link>
@@ -62,6 +86,14 @@
<category>improvement</category>
<description>Every coin launched on three.ws used to carry a quality score, a conviction tier and risk labels on its page, in the launch feed and on its share image. A high score can read as investment advice and a low one as FUD about someone's launch, so all of them are gone. In their place is a Token stats panel with the facts traders look up in terminals: volume, buys, sells, net buy and price change over 5 minutes, 1 hour, 6 hours and 24 hours, plus holders, the top 10 share, how much the dev holds, how much early buyers still hold, mint and freeze authority, bonding curve progress, liquidity and whether a DEX Screener profile was paid for. The Holders panel lists the ten largest wallets with links to each one, and leaves the bonding curve and pool out of the ranking. If the full holder index is unavailable, the page still shows the largest holders and says so instead of going blank.</description>
</item>
+ <item>
+ <title>Documentation that tells you whether to trust it</title>
+ <link>https://three.ws/docs/freshness</link>
+ <guid isPermaLink="false">2026-09-17:Documentation that tells you whether to trust it</guid>
+ <pubDate>Thu, 17 Sep 2026 12:00:00 GMT</pubDate>
+ <category>docs</category>
+ <description>Every page in the docs is bound to the code it names, and git decides whether that code moved after the page was last written. That measurement now has a second clock: when someone reads a page, checks it against the source and finds it correct, that review is recorded, so careful reading counts as much as editing and nobody has to fake a change to clear a page. Docs that record a moment, like a dated audit or a finished piece of work, are marked as records and are no longer counted as drift. Every page that was out of date has been brought back in line: 110 documents were read against the exact changes that had moved under them, 82 were corrected, 22 were confirmed still accurate, and 6 were marked as records of a moment. The dashboard at /docs/freshness now shows who last checked each page and when, the report is regenerated on every deploy instead of by hand, and the check runs automatically so drift cannot pile up unnoticed again.</description>
+ </item>
<item>
<title>Pick your chart on every coin page, and click an agent's coin to open it</title>
<link>https://three.ws/launches</link>
diff --git a/public/features.json b/public/features.json
index 0d63c5892..92791e1ab 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-17T19:55:26.628Z",
+ "generated_at": "2026-09-17T23:48:58.673Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -6328,6 +6328,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/docs/doc-freshness",
+ "title": "Docs · Doc freshness, keeping docs true to the code",
+ "description": "Every doc is bound to the code it names, and git decides whether that code moved after the page was last written or last reviewed. How the measurement works, what each status means, how to record that you checked a page, and where the check runs.",
+ "added": "2026-09-17",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/docs/glasses",
"title": "Docs · Smart glasses, agents on your lens",
@@ -6808,6 +6818,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/docs/x402-settlement-pending",
+ "title": "Pending settlement: the third answer an x402 settle can give",
+ "description": "Broadcasting a Solana payment and confirming it are separate events, so a settle has three outcomes, not two. What settlement_pending means for a buyer, how our facilitator guarantees one authorization never produces two transactions, and the reconciler that closes the books.",
+ "added": "2026-09-17",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/docs/x402-ring-economy",
"title": "Docs · The closed-loop x402 ring economy",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 92a852c3c..d23f0ee9c 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -3844,6 +3844,12 @@ URL: https://three.ws/docs/irl
Take an agent off the screen and pin it at a real GPS coordinate: on your table, at a park bench, outside a venue. Anyone who physically walks up can see it, talk to it, and pay it.
+### Docs · Doc freshness, keeping docs true to the code
+
+URL: https://three.ws/docs/doc-freshness
+
+Every doc is bound to the code it names, and git decides whether that code moved after the page was last written or last reviewed. How the measurement works, what each status means, how to record that you checked a page, and where the check runs.
+
### Docs · Smart glasses, agents on your lens
URL: https://three.ws/docs/glasses
@@ -4132,6 +4138,12 @@ URL: https://three.ws/docs/x402-distribution
three.ws sells dozens of pay-per-call services over x402. Building them is half the job; the other half is making sure every directory, crawler, and agent marketplace can find them. The distribution checklist.
+### Pending settlement: the third answer an x402 settle can give
+
+URL: https://three.ws/docs/x402-settlement-pending
+
+Broadcasting a Solana payment and confirming it are separate events, so a settle has three outcomes, not two. What settlement_pending means for a buyer, how our facilitator guarantees one authorization never produces two transactions, and the reconciler that closes the books.
+
### Docs · The closed-loop x402 ring economy
URL: https://three.ws/docs/x402-ring-economy
diff --git a/public/llms.txt b/public/llms.txt
index b998cd8b5..7712361d3 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -656,6 +656,7 @@ Docs, tutorials, and reference.
- [Docs · Internationalization](https://three.ws/docs/i18n): How the UI translation catalogue works: one source-of-truth file translated incrementally by an LLM, committed as static JSON, and swapped in the browser at runtime. Includes how to add a locale and how the lint pass catches drift.
- [Docs · Introduction and overview](https://three.ws/docs/introduction): three.ws is an open-source, browser-native platform for creating, hosting, and embedding interactive AI agents that live inside 3D avatars. What it does, who it is for, and the shortest path to something running.
- [Docs · IRL, agents in the real world](https://three.ws/docs/irl): Take an agent off the screen and pin it at a real GPS coordinate: on your table, at a park bench, outside a venue. Anyone who physically walks up can see it, talk to it, and pay it.
+- [Docs · Doc freshness, keeping docs true to the code](https://three.ws/docs/doc-freshness): Every doc is bound to the code it names, and git decides whether that code moved after the page was last written or last reviewed. How the measurement works, what each status means, how to record that you checked a page, and where the check runs.
- [Docs · Smart glasses, agents on your lens](https://three.ws/docs/glasses): Wear smart glasses and the world tells you an agent is standing thirty metres away. How three.ws splits the work: the lens carries the signal, the phone carries the 3D body, and the presence-gated IRL rail carries the truth.
- [Docs · JavaScript API reference](https://three.ws/docs/js-api): The internal JavaScript classes behind the three.ws viewer: the application controller, the three.js viewer, the glTF validator, and the small components that render around them. Constructors, methods, and events.
- [Docs · The four layers](https://three.ws/docs/layers): three.ws splits into four horizontal layers. Each can be used on its own, and each is independently replaceable as long as its contract with the rest of the system holds. What those contracts are.
@@ -704,6 +705,7 @@ Docs, tutorials, and reference.
- [Docs · Oracle, the conviction engine](https://three.ws/docs/oracle): The complete story of Oracle: why it was built, how the scoring model works, the exact maths, the agent action loop, every platform feature that runs on it, and the paid integration other agents can call.
- [Docs · The Oracle model, and how to run it yourself](https://three.ws/docs/oracle-model): How the three.ws conviction model is fitted, what its three heads predict, why the outcome labels had to be made independent of the SOL price, how the promotion gate decides which model ships, and how to score launches locally with @three-ws/oracle-model.
- [Docs · x402 distribution](https://three.ws/docs/x402-distribution): three.ws sells dozens of pay-per-call services over x402. Building them is half the job; the other half is making sure every directory, crawler, and agent marketplace can find them. The distribution checklist.
+- [Pending settlement: the third answer an x402 settle can give](https://three.ws/docs/x402-settlement-pending): Broadcasting a Solana payment and confirming it are separate events, so a settle has three outcomes, not two. What settlement_pending means for a buyer, how our facilitator guarantees one authorization never produces two transactions, and the reconciler that closes the books.
- [Docs · The closed-loop x402 ring economy](https://three.ws/docs/x402-ring-economy): A self-contained agent-to-agent payment loop where platform-controlled wallets pay the platform's own paid endpoints in real stablecoin, settled by the platform's own facilitator. No user funds are involved.
- [Docs · The $THREE micro-buy loop](https://three.ws/docs/three-microbuy): Many tiny, real on-chain buys of $THREE per minute, each triggered by and paid through a settled pay-per-call payment. It exists to put continuous, verifiable buy pressure behind the platform's own token.
- [Docs · IBM watsonx and Granite](https://three.ws/docs/ibm): three.ws agents can think on IBM Granite foundation models served through IBM watsonx.ai. The whole integration for developers and operators: model selection, credentials, request shapes, and the fallback behind it.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index c9a86590b..c37226d51 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -96,7 +96,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 940 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 942 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -108,7 +108,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 940 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 942 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd id="sm-filter-kbd" aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" role="status" aria-live="polite"><span id="sm-filter-count"></span><span id="sm-filter-hint" aria-hidden="true"></span></p>
@@ -116,6 +116,14 @@
<h2 id="sm-new-title">Newest<a class="sm-new-more" href="/changelog">full changelog &rarr;</a></h2>
<p class="sm-section-desc">The 9 most recently launched pages, straight to the live surface.</p>
<ul class="sm-list">
+ <li>
+ <a href="/docs/doc-freshness">
+ <span class="sm-new-date">Sep 17, 2026</span>
+ <span class="sm-title">Docs · Doc freshness, keeping docs true to the code</span>
+ <span class="sm-path">/docs/doc-freshness</span>
+ <span class="sm-desc">Every doc is bound to the code it names, and git decides whether that code moved after the page was last written or last reviewed. How the measurement works, what each status means, how to record that you checked a page, and where the check runs.</span>
+ </a>
+ </li>
<li>
<a href="/docs/glasses">
<span class="sm-new-date">Sep 17, 2026</span>
@@ -124,6 +132,14 @@
<span class="sm-desc">Wear smart glasses and the world tells you an agent is standing thirty metres away. How three.ws splits the work: the lens carries the signal, the phone carries the 3D body, and the presence-gated IRL rail carries the truth.</span>
</a>
</li>
+ <li>
+ <a href="/docs/x402-settlement-pending">
+ <span class="sm-new-date">Sep 17, 2026</span>
+ <span class="sm-title">Pending settlement: the third answer an x402 settle can give</span>
+ <span class="sm-path">/docs/x402-settlement-pending</span>
+ <span class="sm-desc">Broadcasting a Solana payment and confirming it are separate events, so a settle has three outcomes, not two. What settlement_pending means for a buyer, how our facilitator guarantees one authorization never produces two transactions, and the reconciler that closes the books.</span>
+ </a>
+ </li>
<li>
<a href="/legal/agent-wallet">
<span class="sm-new-date">Sep 17, 2026</span>
@@ -172,22 +188,6 @@
<span class="sm-desc">Open an image or text written into a public Solana Memo. Paste a transaction signature or Solscan link to preview the signed data without copying a data URI.</span>
</a>
</li>
- <li>
- <a href="/docs/mcp-solana-memo-media">
- <span class="sm-new-date">Sep 15, 2026</span>
- <span class="sm-title">Docs · Solana Memo Media MCP</span>
- <span class="sm-path">/docs/mcp-solana-memo-media</span>
- <span class="sm-desc">Decode validated image data embedded in Solana Memo transactions and return safe inline MCP images with provenance.</span>
- </a>
- </li>
- <li>
- <a href="/docs/x402-vscode">
- <span class="sm-new-date">Sep 13, 2026</span>
- <span class="sm-title">Docs · x402 for VS Code</span>
- <span class="sm-path">/docs/x402-vscode</span>
- <span class="sm-desc">Find, inspect, and pay x402 APIs from VS Code with $THREE or USDC on Solana, including wallet setup, token selection, safety controls, and the $THREE contract address.</span>
- </a>
- </li>
</ul>
</section>
<nav class="sm-toc" aria-label="Sections">
@@ -2583,7 +2583,7 @@
<section class="sm-section" id="learn">
<header>
- <h2>Learn<span class="sm-count" data-count>434</span></h2>
+ <h2>Learn<span class="sm-count" data-count>436</span></h2>
<p class="sm-section-desc">Docs, tutorials, and reference.</p>
</header>
<ul class="sm-list">
@@ -4652,6 +4652,13 @@
<span class="sm-desc">Take an agent off the screen and pin it at a real GPS coordinate: on your table, at a park bench, outside a venue. Anyone who physically walks up can see it, talk to it, and pay it.</span>
</a>
</li>
+ <li>
+ <a href="/docs/doc-freshness">
+ <span class="sm-title">Docs · Doc freshness, keeping docs true to the code</span>
+ <span class="sm-path">/docs/doc-freshness</span>
+ <span class="sm-desc">Every doc is bound to the code it names, and git decides whether that code moved after the page was last written or last reviewed. How the measurement works, what each status means, how to record that you checked a page, and where the check runs.</span>
+ </a>
+ </li>
<li>
<a href="/docs/glasses">
<span class="sm-title">Docs · Smart glasses, agents on your lens</span>
@@ -4988,6 +4995,13 @@
<span class="sm-desc">three.ws sells dozens of pay-per-call services over x402. Building them is half the job; the other half is making sure every directory, crawler, and agent marketplace can find them. The distribution checklist.</span>
</a>
</li>
+ <li>
+ <a href="/docs/x402-settlement-pending">
+ <span class="sm-title">Pending settlement: the third answer an x402 settle can give</span>
+ <span class="sm-path">/docs/x402-settlement-pending</span>
+ <span class="sm-desc">Broadcasting a Solana payment and confirming it are separate events, so a settle has three outcomes, not two. What settlement_pending means for a buyer, how our facilitator guarantees one authorization never produces two transactions, and the reconciler that closes the books.</span>
+ </a>
+ </li>
<li>
<a href="/docs/x402-ring-economy">
<span class="sm-title">Docs · The closed-loop x402 ring economy</span>
diff --git a/tests/api/x402-settlement-reconcile.test.js b/tests/api/x402-settlement-reconcile.test.js
new file mode 100644
index 000000000..72cca9ee5
--- /dev/null
+++ b/tests/api/x402-settlement-reconcile.test.js
@@ -0,0 +1,285 @@
+// The reconcile pass that closes out `settlement_pending` rows
+// (api/cron/x402-settlement-reconcile.js).
+//
+// A pending settlement is a payment whose good has already been delivered
+// against a transaction whose fate was unknown. This cron is the only thing that
+// ever finishes those: confirm the signature, credit the settlement exactly
+// once, and surface the one case that costs us money (a delivered payment that
+// never landed). Each branch below is a different answer from the chain, and
+// getting any of them wrong has a price:
+//
+// confirmed but not credited → revenue and SOL burn missing from the books.
+// failed/abandoned left open → the row is re-probed forever and the loss is
+// never reported.
+// unknown treated as an answer → a payment that was about to land is written
+// off while it lands.
+//
+// The Solana RPC, the credit gate, the store, and the alert sink are mocked; the
+// cron's own decision table is what is under test.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ rows: [],
+ probe: vi.fn(),
+ credit: vi.fn(),
+ resolved: [],
+ alerts: [],
+ promoted: [],
+}));
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: () => Promise.resolve([]),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../../api/_lib/solana/connection.js', () => ({
+ solanaConnection: () => ({ tag: 'conn' }),
+}));
+
+vi.mock('../../api/_lib/x402/self-facilitator.js', () => ({
+ probeSettlementSignature: (...a) => h.probe(...a),
+}));
+
+vi.mock('../../api/_lib/x402/settle-credit.js', () => ({
+ claimSettleCredit: (...a) => h.credit(...a),
+}));
+
+vi.mock('../../api/_lib/x402/audit-log.js', () => ({
+ promotePendingSettlementStatus: async (args) => {
+ h.promoted.push(args);
+ return 1;
+ },
+}));
+
+vi.mock('../../api/_lib/alerts.js', () => ({
+ sendOpsAlert: async (title, body, opts) => {
+ h.alerts.push({ title, body, opts });
+ },
+}));
+
+vi.mock('../../api/_lib/x402/pending-settlements.js', () => ({
+ PENDING_SCOPE_RESOURCE: 'resource',
+ listOpenPendingSettlements: async () => h.rows,
+ resolvePendingSettlement: async (args) => {
+ h.resolved.push(args);
+ },
+}));
+
+const CRON_SECRET = 'test-cron-secret';
+
+function pendingRow(overrides = {}) {
+ return {
+ scope: 'resource',
+ key: 'key-1',
+ tx_sig: 'SigAbc',
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ payer: 'BuyerPubkey',
+ pay_to: 'RecipientPubkey',
+ mint: 'MintPubkey',
+ amount_atomic: '2500',
+ fee_lamports: '5000',
+ fee_payer: 'FeePayerPubkey',
+ resource_url: 'https://three.ws/api/x402/forge',
+ idempotency_key: 'idem-1',
+ attempts: 0,
+ created_at: new Date(Date.now() - 60_000).toISOString(),
+ ...overrides,
+ };
+}
+
+async function run() {
+ vi.resetModules();
+ process.env.CRON_SECRET = CRON_SECRET;
+ const handler = (await import('../../api/cron/x402-settlement-reconcile.js')).default;
+ let status = 0;
+ let body = '';
+ const res = {
+ statusCode: 200,
+ setHeader() {},
+ getHeader() {},
+ writeHead(s) {
+ status = s;
+ },
+ end(b) {
+ body = b || '';
+ },
+ };
+ await handler(
+ {
+ method: 'GET',
+ url: '/api/cron/x402-settlement-reconcile',
+ headers: { authorization: `Bearer ${CRON_SECRET}` },
+ query: {},
+ },
+ res,
+ );
+ return { status: status || res.statusCode, body: body ? JSON.parse(body) : null };
+}
+
+describe('x402-settlement-reconcile', () => {
+ beforeEach(() => {
+ h.rows = [];
+ h.resolved = [];
+ h.alerts = [];
+ h.promoted = [];
+ h.probe = vi.fn();
+ h.credit = vi.fn(async () => ({ granted: true }));
+ });
+
+ it('does no RPC or DB work when nothing is pending', async () => {
+ const { status, body } = await run();
+ expect(status).toBe(200);
+ expect(body).toMatchObject({ ok: true, scanned: 0 });
+ expect(h.probe).not.toHaveBeenCalled();
+ });
+
+ it('credits a confirmed settlement under the settle idempotency key, with the fee the chain charged', async () => {
+ h.rows = [pendingRow()];
+ h.probe = vi.fn(async () => ({ state: 'confirmed', feeLamports: 5432 }));
+
+ const { body } = await run();
+
+ expect(body).toMatchObject({ scanned: 1, confirmed: 1, credited: 1 });
+ expect(h.credit).toHaveBeenCalledTimes(1);
+ const claimed = h.credit.mock.calls[0][0].row;
+ expect(claimed).toMatchObject({
+ txSig: 'SigAbc',
+ // The SAME key the settle used: the credit gate reads a different key on a
+ // known signature as a different payment reusing it, and refuses.
+ idempotencyKey: 'idem-1',
+ // The real fee, not the estimate recorded at broadcast.
+ feeLamports: 5432,
+ feePayer: 'FeePayerPubkey',
+ });
+ // bigint columns arrive as strings; the credit row needs a number.
+ expect(claimed.amountAtomic).toBe(2500);
+ expect(h.resolved).toEqual([
+ { scope: 'resource', key: 'key-1', state: 'confirmed', error: null },
+ ]);
+ // The audit row was written as 'pending' while the outcome was unknown, and
+ // every revenue query counts 'success'. Left pending, this payment would
+ // never appear in the books.
+ expect(h.promoted).toEqual([{ txHash: 'SigAbc', status: 'success' }]);
+ expect(h.alerts).toHaveLength(0);
+ });
+
+ it('falls back to the recorded fee estimate when the parsed fee is unavailable', async () => {
+ h.rows = [pendingRow()];
+ h.probe = vi.fn(async () => ({ state: 'confirmed', feeLamports: null }));
+ await run();
+ expect(h.credit.mock.calls[0][0].row.feeLamports).toBe('5000');
+ });
+
+ it('closes a confirmed row even when the credit is refused, and keeps the reason', async () => {
+ // Another payment already owns this signature (or the DB could not answer).
+ // Re-probing a transaction the chain has already confirmed would never change
+ // the verdict, so the row closes with the refusal recorded.
+ h.rows = [pendingRow()];
+ h.probe = vi.fn(async () => ({ state: 'confirmed', feeLamports: 5000 }));
+ h.credit = vi.fn(async () => ({ granted: false, reason: 'signature_already_settled' }));
+
+ const { body } = await run();
+
+ expect(body).toMatchObject({ confirmed: 1, credited: 0 });
+ expect(h.resolved[0]).toMatchObject({
+ state: 'confirmed',
+ error: 'signature_already_settled',
+ });
+ });
+
+ it('alerts when a delivered payment turns out never to have settled', async () => {
+ h.rows = [pendingRow({ scope: 'resource' })];
+ h.probe = vi.fn(async () => ({ state: 'abandoned', error: 'not_found_after_600s' }));
+
+ const { body } = await run();
+
+ expect(body).toMatchObject({ abandoned: 1 });
+ expect(h.credit).not.toHaveBeenCalled();
+ expect(h.resolved[0]).toMatchObject({ state: 'abandoned' });
+ expect(h.promoted).toEqual([{ txHash: 'SigAbc', status: 'failed' }]);
+ expect(h.alerts).toHaveLength(1);
+ // The signature and the resource are what an operator needs to trace it.
+ expect(h.alerts[0].body).toContain('SigAbc');
+ expect(h.alerts[0].body).toContain('/api/x402/forge');
+ expect(h.alerts[0].opts.signature).toContain('SigAbc');
+ });
+
+ it('does not alert for a facilitator-scope row, where nothing was delivered on credit', async () => {
+ h.rows = [pendingRow({ scope: 'facilitator', key: 'fkey' })];
+ h.probe = vi.fn(async () => ({ state: 'failed', error: 'InstructionError' }));
+
+ const { body } = await run();
+
+ expect(body).toMatchObject({ failed: 1 });
+ expect(h.resolved[0]).toMatchObject({ scope: 'facilitator', state: 'failed' });
+ expect(h.alerts).toHaveLength(0);
+ });
+
+ it('leaves a still-unknown row open and only bumps its attempt count', async () => {
+ h.rows = [pendingRow()];
+ h.probe = vi.fn(async () => ({ state: 'pending', error: 'not_found_yet' }));
+
+ const { body } = await run();
+
+ expect(body).toMatchObject({ still_pending: 1, confirmed: 0, abandoned: 0 });
+ expect(h.credit).not.toHaveBeenCalled();
+ expect(h.resolved[0]).toMatchObject({ state: 'pending', error: 'not_found_yet' });
+ // Nothing is decided, so the audit row must stay pending too.
+ expect(h.promoted).toHaveLength(0);
+ });
+
+ it('treats a thrown probe as unknown rather than an answer', async () => {
+ h.rows = [pendingRow()];
+ h.probe = vi.fn(async () => {
+ throw new Error('rpc exploded');
+ });
+
+ const { body } = await run();
+
+ expect(body).toMatchObject({ still_pending: 1 });
+ expect(h.resolved[0].state).toBe('pending');
+ expect(h.resolved[0].error).toContain('probe_failed');
+ });
+
+ it('processes every row in the batch independently', async () => {
+ h.rows = [
+ pendingRow({ key: 'a', tx_sig: 'SigA' }),
+ pendingRow({ key: 'b', tx_sig: 'SigB' }),
+ pendingRow({ key: 'c', tx_sig: 'SigC' }),
+ ];
+ h.probe = vi.fn(async ({ signature }) => {
+ if (signature === 'SigA') return { state: 'confirmed', feeLamports: 5000 };
+ if (signature === 'SigB') return { state: 'failed', error: 'reverted' };
+ return { state: 'pending', error: 'not_found_yet' };
+ });
+
+ const { body } = await run();
+
+ expect(body).toMatchObject({ scanned: 3, confirmed: 1, failed: 1, still_pending: 1 });
+ expect(h.resolved.map((r) => r.key)).toEqual(['a', 'b', 'c']);
+ // One alert for the one delivered-but-unsettled payment, not one per row.
+ expect(h.alerts).toHaveLength(1);
+ });
+
+ it('refuses an unauthenticated caller before touching anything', async () => {
+ h.rows = [pendingRow()];
+ vi.resetModules();
+ process.env.CRON_SECRET = CRON_SECRET;
+ const handler = (await import('../../api/cron/x402-settlement-reconcile.js')).default;
+ let status = 0;
+ const res = {
+ statusCode: 200,
+ setHeader() {},
+ getHeader() {},
+ writeHead(s) {
+ status = s;
+ },
+ end() {},
+ };
+ await handler({ method: 'GET', url: '/x', headers: {}, query: {} }, res);
+ expect(status || res.statusCode).toBe(401);
+ expect(h.probe).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/x402-settlement-pending-resource.test.js b/tests/x402-settlement-pending-resource.test.js
new file mode 100644
index 000000000..190a46100
--- /dev/null
+++ b/tests/x402-settlement-pending-resource.test.js
@@ -0,0 +1,215 @@
+// The resource server's half of `settlement_pending`.
+//
+// settlePayment() sits inside a buyer's open request. When the facilitator says
+// "broadcast, outcome unknown", three things must hold or the mechanism does
+// more harm than the 502 it replaces:
+//
+// 1. EXACTLY ONE retry, with the identical body and idempotency key. That
+// identity is what lets the facilitator recognize the retry and reconcile
+// against the signature it already broadcast; a changed key would make it
+// verify and broadcast again. Exactly one, never a loop, because this runs
+// with a client waiting.
+// 2. A still-unresolved settle returns `status:'pending'` rather than throwing,
+// so the buyer gets the good they paid for plus the settlement hash.
+// 3. Pending is only allowed when the pending record was durably stored. With
+// no record nothing can reconcile it later. Delivering against it would be
+// an unaccountable giveaway, so that case stays a hard failure.
+//
+// callFacilitator is internal to x402-spec.js and talks over fetch, so the
+// facilitator's replies are injected at the fetch boundary (same approach as
+// tests/x402-floor-degradation.test.js).
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ writes: [],
+ writeFails: false,
+}));
+
+// `recordResourcePending` goes through the Postgres-backed store; the store's
+// own SQL is covered by its module tests, so here only the durable/not-durable
+// outcome matters.
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (strings, ...values) => {
+ const query = Array.isArray(strings) ? strings.join(' ') : String(strings ?? '');
+ if (/INSERT INTO x402_pending_settlements/i.test(query)) {
+ h.writes.push({ query, values });
+ if (h.writeFails) return Promise.reject(new Error('db unavailable'));
+ }
+ return Promise.resolve([]);
+ },
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const REQUIREMENT = {
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ payTo: 'RecipientPubkey',
+ asset: 'MintPubkey',
+ amount: '1000',
+ scheme: 'exact',
+ resource: 'https://three.ws/api/x402/forge',
+};
+
+const reply = (body) =>
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+
+// Answer each /settle call from `sequence`, recording what was sent.
+function facilitator(sequence) {
+ const calls = [];
+ const fetchMock = vi.fn(async (url, init) => {
+ calls.push({
+ url: String(url),
+ body: JSON.parse(init.body),
+ idempotencyKey: init.headers['Idempotency-Key'],
+ });
+ const next = sequence[Math.min(calls.length - 1, sequence.length - 1)];
+ return reply(next);
+ });
+ return { calls, fetchMock };
+}
+
+async function settleWith(sequence) {
+ vi.resetModules();
+ h.writes = [];
+ process.env.X402_FACILITATOR_URL_SOLANA = 'https://facilitator.test';
+ const { calls, fetchMock } = facilitator(sequence);
+ vi.stubGlobal('fetch', fetchMock);
+ const { settlePayment } = await import('../api/_lib/x402-spec.js');
+ try {
+ const result = await settlePayment({
+ requirement: REQUIREMENT,
+ paymentPayload: { x402Version: 2, payload: { transaction: 'dGVzdA==' } },
+ verifiedPayer: 'BuyerPubkey',
+ });
+ return { result, calls, error: null };
+ } catch (error) {
+ return { result: null, calls, error };
+ } finally {
+ vi.unstubAllGlobals();
+ }
+}
+
+const PENDING = { success: false, errorReason: 'settlement_pending', transaction: 'SigAbc' };
+const CONFIRMED = {
+ success: true,
+ transaction: 'SigAbc',
+ network: REQUIREMENT.network,
+ payer: 'BuyerPubkey',
+};
+
+describe('settlePayment on settlement_pending', () => {
+ beforeEach(() => {
+ h.writeFails = false;
+ });
+
+ it('retries once with the identical body and idempotency key', async () => {
+ const { result, calls } = await settleWith([PENDING, CONFIRMED]);
+
+ expect(calls).toHaveLength(2);
+ expect(calls[0].url).toContain('/settle');
+ // Byte-identical retry: same payload, same requirements, same key. Anything
+ // else and the facilitator treats it as a new payment to broadcast.
+ expect(calls[1].body).toEqual(calls[0].body);
+ expect(calls[1].idempotencyKey).toBe(calls[0].idempotencyKey);
+ expect(calls[0].idempotencyKey).toBeTruthy();
+ // The retry resolved, so this is an ordinary settled payment.
+ expect(result).toMatchObject({ success: true, transaction: 'SigAbc' });
+ expect(result.status).toBeUndefined();
+ });
+
+ it('never retries more than once, even if the second answer is also pending', async () => {
+ const { calls } = await settleWith([PENDING, PENDING]);
+ expect(calls).toHaveLength(2);
+ });
+
+ it('returns status pending (not an error) when the retry is still unresolved', async () => {
+ const { result, error } = await settleWith([PENDING, PENDING]);
+
+ expect(error).toBeNull();
+ expect(result).toMatchObject({
+ success: true,
+ status: 'pending',
+ pending: true,
+ transaction: 'SigAbc',
+ network: REQUIREMENT.network,
+ payer: 'BuyerPubkey',
+ });
+ // Recorded for /api/cron/x402-settlement-reconcile to close out.
+ expect(h.writes).toHaveLength(1);
+ expect(h.writes[0].values).toContain('SigAbc');
+ });
+
+ it('fails hard when the pending record cannot be stored', async () => {
+ h.writeFails = true;
+ const { result, error } = await settleWith([PENDING, PENDING]);
+
+ expect(result).toBeNull();
+ expect(error).toMatchObject({ code: 'settle_failed', status: 502 });
+ // The operator (and the buyer) need the signature that is out there.
+ expect(error.message).toContain('SigAbc');
+ });
+
+ it('treats a pending reason with no transaction as an ordinary failure', async () => {
+ // Nothing to reconcile against, so there is nothing to wait for: this is a
+ // failed settle wearing a non-terminal label.
+ const { calls, error } = await settleWith([
+ { success: false, errorReason: 'settlement_pending' },
+ ]);
+ expect(calls).toHaveLength(1);
+ expect(error).toMatchObject({ code: 'settle_failed' });
+ });
+
+ it('does not retry an ordinary settle failure', async () => {
+ const { calls, error } = await settleWith([
+ { success: false, errorReason: 'insufficient_funds' },
+ ]);
+ expect(calls).toHaveLength(1);
+ expect(error).toMatchObject({ code: 'settle_failed', status: 502 });
+ });
+
+ it('leaves a first-attempt success untouched', async () => {
+ const { result, calls, error } = await settleWith([CONFIRMED]);
+ expect(error).toBeNull();
+ expect(calls).toHaveLength(1);
+ expect(result).toMatchObject({ success: true, transaction: 'SigAbc' });
+ expect(h.writes).toHaveLength(0);
+ });
+});
+
+describe('isSettlementPending', () => {
+ it('requires both the protocol reason and a broadcast transaction', async () => {
+ vi.resetModules();
+ const { isSettlementPending, SETTLEMENT_PENDING_REASON } = await import(
+ '../api/_lib/x402-spec.js'
+ );
+ expect(SETTLEMENT_PENDING_REASON).toBe('settlement_pending');
+ expect(isSettlementPending({ success: false, errorReason: 'settlement_pending', transaction: 's' })).toBe(true);
+ expect(isSettlementPending({ success: false, errorReason: 'settlement_pending' })).toBe(false);
+ expect(isSettlementPending({ success: false, errorReason: 'other', transaction: 's' })).toBe(false);
+ expect(isSettlementPending({ success: true, transaction: 's' })).toBe(false);
+ expect(isSettlementPending(null)).toBe(false);
+ });
+});
+
+describe('encodePaymentResponseHeader with a pending settlement', () => {
+ it('tells the buyer the settlement is pending and which signature to watch', async () => {
+ vi.resetModules();
+ const { encodePaymentResponseHeader } = await import('../api/_lib/x402-spec.js');
+ const header = encodePaymentResponseHeader({
+ success: true,
+ status: 'pending',
+ transaction: 'SigAbc',
+ network: REQUIREMENT.network,
+ payer: 'BuyerPubkey',
+ });
+ const decoded = JSON.parse(Buffer.from(header, 'base64').toString('utf8'));
+ expect(decoded).toMatchObject({
+ success: true,
+ status: 'pending',
+ transaction: 'SigAbc',
+ });
+ });
+});
diff --git a/tests/x402-settlement-pending.test.js b/tests/x402-settlement-pending.test.js
new file mode 100644
index 000000000..845b59360
--- /dev/null
+++ b/tests/x402-settlement-pending.test.js
@@ -0,0 +1,447 @@
+// `settlement_pending`: the third settle outcome, end to end.
+//
+// Before this behavior existed, a settle whose confirmation wait ran out was
+// reported as a failure: the facilitator answered `not_confirmed:confirm_timeout`
+// and the resource server turned that into a 502. That is wrong whenever the
+// transaction actually lands a slot later, which is exactly the case a timeout
+// cannot distinguish. The buyer is charged and told they were not, and the good
+// they paid for is withheld.
+//
+// The rail now answers `{ success:false, errorReason:'settlement_pending',
+// transaction }` for an unknown outcome, retries it once against the recorded
+// signature instead of broadcasting a second transaction, and reconciles the
+// result out of band. These tests pin the three properties that make that safe:
+//
+// 1. UNKNOWN is never reported as failure, and never without a durable record.
+// 2. A retry of a payload already broadcast NEVER broadcasts again.
+// 3. A definite on-chain failure is still a failure. Pending is for unknown,
+// not for "we would rather not say".
+//
+// The confirmation window is squeezed to ~1ms via env so the unknown-outcome
+// cases do not spend the real 12s wait.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import {
+ Keypair,
+ TransactionMessage,
+ VersionedTransaction,
+ ComputeBudgetProgram,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync,
+ createTransferCheckedInstruction,
+} from '@solana/spl-token';
+import bs58 from 'bs58';
+
+const { settleRingPayment, probeSettlementSignature } = await import(
+ '../api/_lib/x402/self-facilitator.js'
+);
+const {
+ SETTLEMENT_PENDING_REASON,
+ SETTLEMENT_PENDING_UNRECORDABLE_REASON,
+ pendingSettlementKey,
+ recordPendingOrTerminal,
+} = await import('../api/_lib/x402/pending-settlements.js');
+
+const DECIMALS = 6;
+
+// Self-pay settle (buyer is its own fee payer) so the sponsor min-settle and
+// SOL-floor guards are exempt and the flow reaches the broadcast with a minimal
+// connection mock. Mirrors the harness in x402-self-facilitator-settle-recovery.
+function buildSelfPay(amount = 10_000) {
+ const buyer = Keypair.generate();
+ const recipientOwner = Keypair.generate();
+ const mint = Keypair.generate().publicKey;
+ process.env.X402_ASSET_MINT_SOLANA = mint.toBase58();
+ const sourceAta = getAssociatedTokenAddressSync(mint, buyer.publicKey);
+ const destAta = getAssociatedTokenAddressSync(mint, recipientOwner.publicKey);
+ const transferIx = createTransferCheckedInstruction(
+ sourceAta, mint, destAta, buyer.publicKey, amount, DECIMALS,
+ );
+ const message = new TransactionMessage({
+ payerKey: buyer.publicKey,
+ recentBlockhash: '11111111111111111111111111111111',
+ instructions: [ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }), transferIx],
+ }).compileToV0Message();
+ const tx = new VersionedTransaction(message);
+ tx.sign([buyer]);
+ const txBase64 = Buffer.from(tx.serialize()).toString('base64');
+ return {
+ sig: bs58.encode(tx.signatures[0]),
+ txBase64,
+ key: pendingSettlementKey(txBase64),
+ payTo: recipientOwner.publicKey.toBase58(),
+ requirement: {
+ network: 'solana',
+ asset: mint.toBase58(),
+ amount: String(amount),
+ payTo: recipientOwner.publicKey.toBase58(),
+ },
+ paymentPayload: { transaction: txBase64 },
+ };
+}
+
+// The PendingSettlementStore contract, in memory. The production store is
+// Postgres-backed (shared across Cloud Run replicas); the contract under test
+// here is get/set/delete, not the storage.
+function memoryStore({ failWrites = false } = {}) {
+ const entries = new Map();
+ return {
+ entries,
+ writes: [],
+ deletes: [],
+ async get(key) {
+ return entries.get(key);
+ },
+ async set(key, txHash, meta) {
+ this.writes.push({ key, txHash, meta });
+ if (failWrites) return false;
+ entries.set(key, txHash);
+ return true;
+ },
+ async delete(key) {
+ this.deletes.push(key);
+ entries.delete(key);
+ },
+ };
+}
+
+describe('settlement_pending: unknown confirmation is not a failure', () => {
+ const saved = {};
+ beforeEach(() => {
+ saved.payTo = process.env.X402_PAY_TO_SOLANA;
+ saved.mint = process.env.X402_ASSET_MINT_SOLANA;
+ saved.confirmMs = process.env.X402_SETTLE_CONFIRM_TIMEOUT_MS;
+ process.env.X402_SETTLE_CONFIRM_TIMEOUT_MS = '1';
+ });
+ afterEach(() => {
+ for (const [envName, key] of [
+ ['X402_PAY_TO_SOLANA', 'payTo'],
+ ['X402_ASSET_MINT_SOLANA', 'mint'],
+ ['X402_SETTLE_CONFIRM_TIMEOUT_MS', 'confirmMs'],
+ ]) {
+ if (saved[key] === undefined) delete process.env[envName];
+ else process.env[envName] = saved[key];
+ }
+ });
+
+ it('answers settlement_pending (not a failure) when the confirmation wait ends unknown', async () => {
+ const p = buildSelfPay();
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ const store = memoryStore();
+ const conn = {
+ getBalance: async () => 1_000_000_000,
+ sendRawTransaction: async () => p.sig,
+ // Broadcast landed nowhere yet: no status at all, which is precisely the
+ // state a timeout cannot tell apart from "about to land".
+ getSignatureStatuses: async () => ({ value: [null] }),
+ };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ pendingStore: store,
+ idempotencyKey: 'idem-1',
+ });
+
+ expect(res.success).toBe(false);
+ expect(res.reason).toBe(SETTLEMENT_PENDING_REASON);
+ expect(res.pending).toBe(true);
+ // The signature is what makes the outcome recoverable; a pending answer
+ // without one is useless to a retry and to reconciliation.
+ expect(res.transaction).toBe(p.sig);
+ expect(store.entries.get(p.key)).toBe(p.sig);
+ // Recorded with the caller's idempotency key, so the reconcile pass claims
+ // the settle credit under the SAME key the resource server used.
+ expect(store.writes[0].meta.idempotencyKey).toBe('idem-1');
+ });
+
+ it('downgrades pending to a terminal failure when the record cannot be stored', async () => {
+ // Answering pending promises that a retry can reconcile. With no record a
+ // retry would re-verify and re-broadcast, turning an unknown outcome into a
+ // double send, so an unrecordable pending must be terminal instead.
+ const p = buildSelfPay();
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ const store = memoryStore({ failWrites: true });
+ const conn = {
+ getBalance: async () => 1_000_000_000,
+ sendRawTransaction: async () => p.sig,
+ getSignatureStatuses: async () => ({ value: [null] }),
+ };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ pendingStore: store,
+ });
+
+ expect(res.success).toBe(false);
+ expect(res.pending).toBe(false);
+ expect(res.reason.startsWith(SETTLEMENT_PENDING_UNRECORDABLE_REASON)).toBe(true);
+ // The signature still rides along: it is the only handle anyone has for
+ // reconciling this payment by hand.
+ expect(res.transaction).toBe(p.sig);
+ });
+
+ it('still reports a definite on-chain failure as a failure', async () => {
+ const p = buildSelfPay();
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ const store = memoryStore();
+ const conn = {
+ getBalance: async () => 1_000_000_000,
+ sendRawTransaction: async () => p.sig,
+ getSignatureStatuses: async () => ({
+ value: [{ err: { InstructionError: [1, 'InsufficientFunds'] }, confirmationStatus: 'confirmed' }],
+ }),
+ };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ pendingStore: store,
+ });
+
+ expect(res.success).toBe(false);
+ expect(res.pending).toBeFalsy();
+ expect(res.reason).toContain('not_confirmed');
+ expect(res.reason).toContain('InsufficientFunds');
+ // Nothing to wait for, so no pending entry is left behind to re-probe.
+ expect(store.entries.has(p.key)).toBe(false);
+ expect(store.deletes).toContain(p.key);
+ });
+
+ it('treats an RPC that cannot answer as unknown, never as failure', async () => {
+ const p = buildSelfPay();
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ const store = memoryStore();
+ const conn = {
+ getBalance: async () => 1_000_000_000,
+ sendRawTransaction: async () => p.sig,
+ getSignatureStatuses: async () => {
+ throw new Error('429 Too Many Requests');
+ },
+ };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ pendingStore: store,
+ });
+
+ expect(res.reason).toBe(SETTLEMENT_PENDING_REASON);
+ expect(res.pending).toBe(true);
+ expect(store.writes[0].meta.lastError).toContain('confirm_rpc_unavailable');
+ });
+
+ it('clears the pending entry once a settle confirms', async () => {
+ const p = buildSelfPay();
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ const store = memoryStore();
+ const conn = {
+ getBalance: async () => 1_000_000_000,
+ sendRawTransaction: async () => p.sig,
+ getSignatureStatuses: async () => ({ value: [{ err: null, confirmationStatus: 'confirmed' }] }),
+ getParsedTransaction: async () => ({ meta: { fee: 5000 } }),
+ };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ pendingStore: store,
+ });
+
+ expect(res.success).toBe(true);
+ expect(store.deletes).toContain(p.key);
+ expect(store.entries.size).toBe(0);
+ });
+});
+
+describe('settlement_pending: a retry reconciles instead of re-broadcasting', () => {
+ const saved = {};
+ beforeEach(() => {
+ saved.payTo = process.env.X402_PAY_TO_SOLANA;
+ saved.mint = process.env.X402_ASSET_MINT_SOLANA;
+ saved.confirmMs = process.env.X402_SETTLE_CONFIRM_TIMEOUT_MS;
+ process.env.X402_SETTLE_CONFIRM_TIMEOUT_MS = '1';
+ });
+ afterEach(() => {
+ for (const [envName, key] of [
+ ['X402_PAY_TO_SOLANA', 'payTo'],
+ ['X402_ASSET_MINT_SOLANA', 'mint'],
+ ['X402_SETTLE_CONFIRM_TIMEOUT_MS', 'confirmMs'],
+ ]) {
+ if (saved[key] === undefined) delete process.env[envName];
+ else process.env[envName] = saved[key];
+ }
+ });
+
+ it('confirms the signature already on the wire without sending a second transaction', async () => {
+ const p = buildSelfPay();
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ const store = memoryStore();
+ await store.set(p.key, p.sig, {});
+ store.writes.length = 0;
+
+ const send = vi.fn(async () => p.sig);
+ const conn = {
+ getBalance: async () => 1_000_000_000,
+ sendRawTransaction: send,
+ getSignatureStatuses: async () => ({ value: [{ err: null, confirmationStatus: 'confirmed' }] }),
+ getParsedTransaction: async () => ({ meta: { fee: 5000 } }),
+ };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ pendingStore: store,
+ });
+
+ // The whole point: one broadcast for one authorization, ever.
+ expect(send).not.toHaveBeenCalled();
+ expect(res.success).toBe(true);
+ expect(res.reconciled).toBe(true);
+ expect(res.transaction).toBe(p.sig);
+ expect(store.entries.size).toBe(0);
+ });
+
+ it('stays pending (and still does not re-broadcast) when the retry is also unknown', async () => {
+ const p = buildSelfPay();
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ const store = memoryStore();
+ await store.set(p.key, p.sig, {});
+
+ const send = vi.fn(async () => p.sig);
+ const conn = {
+ getBalance: async () => 1_000_000_000,
+ sendRawTransaction: send,
+ getSignatureStatuses: async () => ({ value: [null] }),
+ };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ pendingStore: store,
+ });
+
+ expect(send).not.toHaveBeenCalled();
+ expect(res.reason).toBe(SETTLEMENT_PENDING_REASON);
+ expect(store.entries.get(p.key)).toBe(p.sig);
+ });
+
+ it('reports failure (and clears the entry) when the reconciled signature reverted', async () => {
+ const p = buildSelfPay();
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ const store = memoryStore();
+ await store.set(p.key, p.sig, {});
+
+ const conn = {
+ getBalance: async () => 1_000_000_000,
+ sendRawTransaction: async () => p.sig,
+ getSignatureStatuses: async () => ({
+ value: [{ err: { InstructionError: [1, 'Custom'] }, confirmationStatus: 'finalized' }],
+ }),
+ };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ pendingStore: store,
+ });
+
+ expect(res.success).toBe(false);
+ expect(res.reason).toContain('not_confirmed');
+ expect(store.entries.has(p.key)).toBe(false);
+ });
+});
+
+describe('pendingSettlementKey', () => {
+ it('is deterministic per payload and distinct across payloads', () => {
+ const a = buildSelfPay();
+ const b = buildSelfPay();
+ expect(pendingSettlementKey(a.txBase64)).toBe(pendingSettlementKey(a.txBase64));
+ expect(pendingSettlementKey(a.txBase64)).not.toBe(pendingSettlementKey(b.txBase64));
+ expect(pendingSettlementKey(null)).toBe(null);
+ });
+});
+
+describe('recordPendingOrTerminal', () => {
+ it('is terminal when no store is supplied at all', async () => {
+ const res = await recordPendingOrTerminal({
+ store: null,
+ key: 'k',
+ signature: 'sig',
+ network: 'solana',
+ payer: 'payer',
+ cause: 'confirm_timeout',
+ });
+ expect(res.pending).toBe(false);
+ expect(res.reason).toContain(SETTLEMENT_PENDING_UNRECORDABLE_REASON);
+ expect(res.reason).toContain('confirm_timeout');
+ });
+});
+
+describe('probeSettlementSignature (the reconcile pass read)', () => {
+ it('confirms with the real fee the chain charged', async () => {
+ const conn = {
+ getSignatureStatuses: async (sigs, opts) => {
+ expect(opts?.searchTransactionHistory).toBe(true);
+ return { value: [{ err: null, confirmationStatus: 'finalized' }] };
+ },
+ getParsedTransaction: async () => ({ meta: { fee: 5432 } }),
+ };
+ const out = await probeSettlementSignature({ conn, signature: 'sig', broadcastAtMs: Date.now() });
+ expect(out.state).toBe('confirmed');
+ expect(out.feeLamports).toBe(5432);
+ });
+
+ it('reports failed for a signature that landed with an error', async () => {
+ const conn = {
+ getSignatureStatuses: async () => ({ value: [{ err: { InstructionError: [0, 'X'] } }] }),
+ };
+ const out = await probeSettlementSignature({ conn, signature: 'sig', broadcastAtMs: Date.now() });
+ expect(out.state).toBe('failed');
+ expect(out.error).toContain('InstructionError');
+ });
+
+ it('stays pending while the transaction could still land', async () => {
+ const conn = { getSignatureStatuses: async () => ({ value: [null] }) };
+ const out = await probeSettlementSignature({ conn, signature: 'sig', broadcastAtMs: Date.now() });
+ expect(out.state).toBe('pending');
+ });
+
+ it('abandons a signature the ledger has never seen past the blockhash horizon', async () => {
+ // A transaction can only be included while its blockhash is live. Past that
+ // "not found" stops meaning "not yet" and starts meaning "dropped", which is
+ // the difference between waiting forever and closing the row.
+ const conn = { getSignatureStatuses: async () => ({ value: [null] }) };
+ const out = await probeSettlementSignature({
+ conn,
+ signature: 'sig',
+ broadcastAtMs: Date.now() - 10 * 60_000,
+ });
+ expect(out.state).toBe('abandoned');
+ });
+
+ it('does not conclude anything from an RPC that failed', async () => {
+ const conn = {
+ getSignatureStatuses: async () => {
+ throw new Error('connection reset');
+ },
+ };
+ const out = await probeSettlementSignature({
+ conn,
+ signature: 'sig',
+ // Old enough to be abandoned IF the RPC had actually answered "not found".
+ broadcastAtMs: Date.now() - 10 * 60_000,
+ });
+ expect(out.state).toBe('pending');
+ expect(out.error).toContain('probe_rpc_failed');
+ });
+});
diff --git a/vercel.json b/vercel.json
index c443097b0..b7f7579d0 100644
--- a/vercel.json
+++ b/vercel.json
@@ -6531,6 +6531,10 @@
"path": "/api/cron/x402-ring-leak-scan",
"schedule": "*/10 * * * *"
},
+ {
+ "path": "/api/cron/x402-settlement-reconcile",
+ "schedule": "*/2 * * * *"
+ },
{
"path": "/api/cron/wallets-leak-scan",
"schedule": "*/15 * * * *"