x402trace 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/LICENSE +201 -0
  3. package/README.md +121 -0
  4. package/dist/chain/abi.d.ts +48 -0
  5. package/dist/chain/abi.js +34 -0
  6. package/dist/chain/client.d.ts +6 -0
  7. package/dist/chain/client.js +283 -0
  8. package/dist/chain/index.d.ts +4 -0
  9. package/dist/chain/index.js +4 -0
  10. package/dist/chain/retry.d.ts +18 -0
  11. package/dist/chain/retry.js +37 -0
  12. package/dist/chain/types.d.ts +94 -0
  13. package/dist/chain/types.js +12 -0
  14. package/dist/cli/color.d.ts +30 -0
  15. package/dist/cli/color.js +26 -0
  16. package/dist/cli/exit-codes.d.ts +12 -0
  17. package/dist/cli/exit-codes.js +11 -0
  18. package/dist/cli/format-result.d.ts +20 -0
  19. package/dist/cli/format-result.js +58 -0
  20. package/dist/cli/index.d.ts +26 -0
  21. package/dist/cli/index.js +130 -0
  22. package/dist/cli/inspect-command.d.ts +28 -0
  23. package/dist/cli/inspect-command.js +63 -0
  24. package/dist/cli/proxy-command.d.ts +74 -0
  25. package/dist/cli/proxy-command.js +197 -0
  26. package/dist/cli/replay.d.ts +44 -0
  27. package/dist/cli/replay.js +193 -0
  28. package/dist/cli.d.ts +2 -0
  29. package/dist/cli.js +20 -0
  30. package/dist/decoder/decoder.d.ts +20 -0
  31. package/dist/decoder/decoder.js +118 -0
  32. package/dist/decoder/format.d.ts +9 -0
  33. package/dist/decoder/format.js +50 -0
  34. package/dist/decoder/index.d.ts +5 -0
  35. package/dist/decoder/index.js +5 -0
  36. package/dist/decoder/parse.d.ts +53 -0
  37. package/dist/decoder/parse.js +179 -0
  38. package/dist/decoder/redact.d.ts +12 -0
  39. package/dist/decoder/redact.js +22 -0
  40. package/dist/decoder/types.d.ts +86 -0
  41. package/dist/decoder/types.js +9 -0
  42. package/dist/proxy/event-bus.d.ts +18 -0
  43. package/dist/proxy/event-bus.js +75 -0
  44. package/dist/proxy/id.d.ts +6 -0
  45. package/dist/proxy/id.js +8 -0
  46. package/dist/proxy/index.d.ts +5 -0
  47. package/dist/proxy/index.js +5 -0
  48. package/dist/proxy/jsonl-sink.d.ts +18 -0
  49. package/dist/proxy/jsonl-sink.js +44 -0
  50. package/dist/proxy/proxy.d.ts +21 -0
  51. package/dist/proxy/proxy.js +238 -0
  52. package/dist/proxy/types.d.ts +95 -0
  53. package/dist/proxy/types.js +32 -0
  54. package/dist/reconciliation/engine.d.ts +40 -0
  55. package/dist/reconciliation/engine.js +178 -0
  56. package/dist/reconciliation/index.d.ts +3 -0
  57. package/dist/reconciliation/index.js +3 -0
  58. package/dist/reconciliation/match.d.ts +31 -0
  59. package/dist/reconciliation/match.js +39 -0
  60. package/dist/reconciliation/types.d.ts +72 -0
  61. package/dist/reconciliation/types.js +17 -0
  62. package/package.json +85 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,71 @@
1
+ # Changelog
2
+
3
+ All notable changes to **x402trace** will be documented in this file.
4
+
5
+ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
+ Versioning: [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ---
9
+
10
+ ## [Unreleased]
11
+
12
+
13
+
14
+ ## [0.1.0] — 2026-05-12
15
+
16
+ The v0.1 wedge: a local proxy + timeout-reconciliation engine that catches the canonical [coinbase/x402#1062](https://github.com/coinbase/x402/issues/1062) symptom — buyer is debited on-chain but the facilitator/server thinks the payment failed. Verified end-to-end on real Base Sepolia + the live `x402.org/facilitator` (tx [`0x116ccf73…ba52`](https://sepolia.basescan.org/tx/0x116ccf73fa77eda19aea149606042f1e848e8afe2f719a0d2890dd2b2ff0ba52)). 215 tests, GitHub Actions CI on Node 20 + 22, Apache-2.0.
17
+
18
+ ### Added
19
+
20
+ - Initial project scaffold (X402-2)
21
+ - `CLAUDE.md` operating manual for Claude Code sessions
22
+ - `TESTING.md` defining test requirements per change type
23
+ - `SPEC.md`, `ARCHITECTURE.md`, `DECISIONS.md` skeletons
24
+ - `CONTRIBUTING.md`, `dogfood-notes.md` skeletons
25
+ - `.env.example` configuration template
26
+ - `.github/PULL_REQUEST_TEMPLATE.md` enforcing test checklist
27
+ - Apache 2.0 license
28
+ - Dogfood rig on Base Sepolia (X402-3): Hono + `x402-hono@1.2.0` server (`src/dogfood/app.ts`, `api/[...all].ts` for Vercel, `scripts/dev-server.ts` for local), paying client via `x402-fetch@1.2.0` (`scripts/dogfood-client.ts`), env validation with mainnet-RPC guard (`src/dogfood/config.ts`), and 20 unit tests covering config validation and 402 challenge generation. **Verified end-to-end against the real `x402.org/facilitator`** on Base Sepolia — paid GET returned 200 with on-chain settlement tx [`0x8b53a04d…b3428`](https://sepolia.basescan.org/tx/0x8b53a04d71cd7dcc35fdf3682ae173758a76213db4ec1abae3e846b8c12b3428).
29
+ - Public Vercel production deploy (X402-3) on the `v1` branch alias at [`x402trace-dogfood-git-v1-fardinvahdats-projects.vercel.app`](https://x402trace-dogfood-git-v1-fardinvahdats-projects.vercel.app) serving `/` (static landing) and `/api/weather` (x402-gated). Second on-chain settlement against the real `x402.org/facilitator` from this production endpoint: tx [`0xc5758bf2…6cbf`](https://sepolia.basescan.org/tx/0xc5758bf2a0f8668a5613aae125a7ab529ef90ce96760020a1ff73309788c6cbf).
30
+ - Five-failure-mode reproduction harness for X402-4 (`scripts/failure-modes.ts`, `pnpm dogfood:failure-modes <n>`). Captures verbatim server/client/facilitator error strings for: wrong chain ID, expired `validBefore`, insufficient USDC, malformed signature, facilitator unavailable. Full transcripts + diagnoses in `dogfood-notes.md` § Failure modes.
31
+ - Week-1 pain synthesis (X402-6) in `dogfood-notes.md` § Top painful moments: 9 ranked pains + 5 wedge candidates (A reconciliation, B inspect+doctor, C bazaar-check, D cross-facilitator, E proxy substrate) — pulls from X402-3 dogfood capture, X402-4 failure modes, X402-5 GitHub catalogue, and the Notion Validation evidence page. CLAUDE.md updated to point future sessions at the table for feature-scope work.
32
+ - **v0.1 wedge accepted (X402-7) — ADR-001 in `DECISIONS.md`: local HTTP proxy substrate + timeout-reconciliation engine on top.** Scope tightened for the 5-week timeline: Base Sepolia only, single facilitator profile (`x402.org/facilitator`), `exact` EVM scheme only, detect-and-notify (no auto-refund in v0.1). CLAUDE.md status updated from "tentative" to "accepted." Bazaar diagnostics, cross-facilitator drift, inspect/doctor/versions deferred to v0.2+.
33
+ - v0.1 implementation spec (X402-8) filled in at `SPEC.md`: problem, solution, user flow (`x402trace proxy --upstream <url> --reconcile` + sample `RECONCILED ⚠ settled-but-server-thinks-not` output), v0.1 scope/v0.2 stretch lists, 5 success-criteria checkboxes, explicit out-of-scope non-goals, and per-competitor differentiation against xpay / x402scan / x402lint / x402-watch / zauth / PaySentry. Linked from CLAUDE.md.
34
+ - v0.1 architecture (X402-9) finalized in `ARCHITECTURE.md`: 5-component decomposition (Proxy `src/proxy/`, Decoder `src/decoder/`, Chain `src/chain/`, Reconciliation `src/reconciliation/`, CLI `src/cli/`) with one-example data flow traced through every component for happy / rejected / timeout outcomes; TypeScript interface stubs ready to become source code (PaymentRequirements, PaymentPayload, FacilitatorResponse, PaymentExchange, ExchangeOutcome, ChainTransfer, ReconciliationResult); canonical JSONL record format (the file is the API); full configuration precedence table; v0.2 extension points named per feature so no v0.1 component is rewritten for v0.2.
35
+ - **Proxy core (X402-10)** in `src/proxy/`: forward HTTP proxy that captures every exchange to a JSONL log + in-process event bus. Five modules — `proxy.ts` (server + forwarding via fetch), `types.ts` (`ProxyEvent` / `CapturedRequest` / `CapturedResponse` / `ExchangeOutcome` discriminated union + `isLikelyX402Exchange` heuristic), `event-bus.ts` (subscribe-with-queue-and-drop-counter pub-sub), `jsonl-sink.ts` (append-only writer), `id.ts` (per-exchange UUIDs). Hop-by-hop headers stripped per RFC; non-UTF8 bodies base64-encoded; upstream timeout returns 502 + `proxy.error` event. Deliberately dumb — no x402 parsing here (that's X402-11). 18 new unit tests + a 4-test integration that pipes the dogfood client through the proxy at the X402-3 dogfood rig (mock-facilitator-backed) and asserts both the 402 and the paid 200 are captured to JSONL with the right discriminants. `pnpm proxy --upstream <url>` runs it; full `npx x402trace proxy` plumbing arrives in X402-14.
36
+ - **x402 message decoder (X402-11)** in `src/decoder/`: pure-function parsers that turn raw `ProxyEvent`s into typed `DecodedEvent`s. Six modules — `types.ts` (`PaymentRequirements`, `PaymentAuthorization`, `PaymentPayload`, `FacilitatorResponse`, `DecodedEvent` discriminated union), `parse.ts` (`parseChallengeBody`, `parsePaymentHeader`, `parseSettlementHeader`, version detection — uses `x402/schemes`'s `exact.evm.decodePayment` for the v1 fast path, hand-rolled fallback for v2), `redact.ts` (signature redaction by default, `--log-secrets` opt-in), `format.ts` (`formatHuman` and `formatJson`), `decoder.ts` (`createDecoder()` stream consumer), `index.ts`. Includes [`src/decoder/schema.md`](src/decoder/schema.md) documenting the JSONL contract. Handles both v1 (`X-PAYMENT` / `X-PAYMENT-RESPONSE`) and v2 (`PAYMENT-SIGNATURE` / `PAYMENT-RESPONSE`) header surfaces. 22 new unit tests covering v1 + v2 parsers, redaction, formatting + a 4-test integration that asserts the proxy→decoder→PaymentExchange pipeline produces the right structured events from a paid flow. Stdout sample of the readable output is captured in [`dogfood-notes.md` § "Decoder readable-output sample"](dogfood-notes.md#decoder-readable-output-sample-x402-11-2026-05-12) per acceptance criterion; `pnpm decoder:demo` reproduces it.
37
+ - **Base RPC client (X402-12)** in `src/chain/`: thin viem wrapper over Base Sepolia. Five modules — `types.ts` (`ChainTransfer` + `VerifyTransferResult` 7-variant discriminated union: `confirmed` / `pending` / `reverted` / `not_found` / `wrong_recipient` / `wrong_amount` / `wrong_token`), `abi.ts` (Base Sepolia USDC address `0x036CbD…CF7e` + Transfer + EIP-3009 AuthorizationUsed event ABIs), `retry.ts` (exponential backoff, 3 attempts default per ARCHITECTURE.md), `client.ts` (`createChainClient` with `verifyTransfer`, `getTransferByTxHash`, `subscribeUsdcTransfers` AsyncIterable, `getBlockNumber`), `index.ts`. Read-only — never holds private keys, never broadcasts. `subscribeUsdcTransfers` enriches each `Transfer` event with the matching `AuthorizationUsed.nonce` from the same tx so the reconciliation engine can match by EIP-3009 nonce. 16 unit tests with mocked transport covering all 7 verify variants + the retry helper + 4 e2e tests against live Base Sepolia (gated by `X402_E2E=1`; verified against the two real X402-3 settlement txs `0x8b53a04d…b3428` and `0xc5758bf2…6cbf`).
38
+ - **GitHub Actions CI (X402-18)** — `.github/workflows/ci.yml` runs `pnpm typecheck`, `pnpm lint`, `pnpm test`, `pnpm build` on every PR + push to `v1` / `staging` / `main`. **Node 20 + 22 matrix**, pnpm-store cached via `actions/setup-node@v4`, 10-min job timeout, in-progress runs cancelled when a fresher commit lands on the same ref. `pnpm test` auto-skips `tests/e2e/chain-live.test.ts` (gated on `X402_E2E=1`), so the live-Base-Sepolia suite never burns testnet funds in CI. Companion `.github/workflows/release.yml` is the X402-19 substrate: tag-triggered (`v*.*.*`), runs the same quality bar, builds, and has the npm-publish step commented out until [X402-19](https://vahdatfardin.atlassian.net/browse/X402-19) wires the `NPM_TOKEN` secret. The CI badge in `README.md` (placeholder since X402-16) lights up on the first run.
39
+ - **Unit-test coverage hardening (X402-17)** — Week-4 risk-reduction pass on the decoder, reconciliation, and CLI. Per the ticket spec ("chase risk reduction, not coverage targets"), targeted the gaps that break silently: (a) the streaming decoder's dispatch logic (`createDecoder().decode()`) had zero direct tests — new `tests/unit/decoder-decoder.test.ts` (11 tests) covers settlement-header parse errors, the `outcome.rawPaymentResponseHeader` fallback path, and `proxy.error` passthrough; (b) base64 + unicode edge cases on `parsePaymentHeader` / `parseChallengeBody` / `parseSettlementHeader` mirroring the [coinbase/x402#865](https://github.com/coinbase/x402/issues/865) surface area — CJK + emoji in `description` and `extra.name` round-trip, padding-stripped base64 tolerated, JSON primitives rejected, URL-safe base64 contract documented; (c) reconciliation `extractErrorReason` paths (non-JSON rawBody, JSON without `error`, missing rawBody), the `unknown` proxy outcome branch the X402-15 demo relies on, chain-transfer race conditions (arrival before pending join, duplicate transfers after match); (d) `x402trace proxy` env-var-vs-flag precedence — extracted `resolveProxyConfig(opts, env)` as a pure function from `proxy-command.ts` (small refactor for testability), then pinned the contract from [ARCHITECTURE.md § Configuration](./ARCHITECTURE.md#configuration) with 28 unit tests across `X402TRACE_UPSTREAM`, `X402TRACE_PORT`, `X402TRACE_LOG`, `X402TRACE_RECONCILE` (including non-truthy strings), `BASE_RPC_URL`, `X402TRACE_WATCH_TIMEOUT_MS`, `X402TRACE_UPSTREAM_TIMEOUT_MS`. Pipeline: **215 tests / 4 e2e skipped** (+57 vs the X402-16 baseline). Coverage: reconciliation **97% → 100%** lines/branches/funcs, decoder **79% → 90%**, src/cli **80.8% → 82%**.
40
+ - **README rewrite (X402-16)**: replaced the pre-release skeleton with a 115-line README that hits all seven X402-16 required sections — elevator pitch, the problem (with the verbatim 502 the buyer sees), 30-second quickstart (`git clone` → `pnpm install` → `cp .env.example .env` → `./examples/e2e-timeout-reconciliation.sh`), how-it-works (4 bullets + ASCII flow diagram of proxy → server → facilitator → chain → engine), CLI reference (links to `--help` rather than duplicating), v0.2 roadmap pulled from [SPEC.md § 5](./SPEC.md#5-v02-stretch-deferred-not-killed), differentiation, contributing, license. Three badges added: Apache-2.0 license (live), GitHub Actions CI (placeholder — wires up automatically when [X402-18](https://vahdatfardin.atlassian.net/browse/X402-18) lands the workflow), npm version (placeholder — wires up automatically when [X402-19](https://vahdatfardin.atlassian.net/browse/X402-19) publishes `x402trace@0.1.0`). The captured X402-15 settlement tx [`0x116ccf73…ba52`](https://sepolia.basescan.org/tx/0x116ccf73fa77eda19aea149606042f1e848e8afe2f719a0d2890dd2b2ff0ba52) is linked from the quickstart's "what success looks like" output block; the asciinema cast is referenced by relative path for local `asciinema play` until [X402-23](https://vahdatfardin.atlassian.net/browse/X402-23) uploads it for an embeddable URL.
41
+ - **End-to-end testnet demo (X402-15)** in `examples/e2e-timeout-reconciliation.sh` + `examples/README.md` + recorded asciinema cast at `examples/cast/e2e-timeout-reconciliation.cast`. The flagship reproduction of the canonical [#1062](https://github.com/coinbase/x402/issues/1062) scenario, runnable against real Base Sepolia + the real `x402.org/facilitator`. Choreography: dogfood server with new `DEMO_SLEEP_MS=10000` knob sleeps 10s *during* the x402-hono paymentMiddleware's protected handler — x402-hono verifies before the handler and settles after, so the post-handler /settle still broadcasts on-chain even though the proxy in front gave up at 5s. `x402trace proxy --reconcile --upstream-timeout-ms 5000` returns 502 to the client (the canonical "I thought it failed" signal), pends the exchange, watches Base Sepolia via the chain client's `subscribeUsdcTransfers`, matches the EIP-3009 nonce, and emits `RECONCILED ⚠ settled-but-server-thinks-not` with the live tx hash. **Verified end-to-end on Base Sepolia 2026-05-12** with on-chain settlement tx [`0x116ccf73…ba52`](https://sepolia.basescan.org/tx/0x116ccf73fa77eda19aea149606042f1e848e8afe2f719a0d2890dd2b2ff0ba52) (block 41402768) — captured in the committed asciinema cast; reconcile gap from proxy timeout to chain-detected was **11.9 seconds**. New `--upstream-timeout-ms` CLI flag on `x402trace proxy` exposes `ProxyOptions.upstreamTimeoutMs` to the surface. New `demoSleepMs` / `demoFailAfterSleep` fields on `DogfoodConfig` plus `DEMO_SLEEP_MS` / `DEMO_FAIL_AFTER_SLEEP` env wiring in `loadServerConfig` (`demoFailAfterSleep` is documented but NOT used in the canonical demo because x402-hono skips /settle on 5xx responses). 9 new tests — 8 unit tests covering env validation (positive/negative/zero/non-numeric) and CLI help inclusion, plus 1 hermetic integration test (`tests/integration/demo-timeout-reconciliation.test.ts`) that reproduces the full demo storyline against the mock facilitator with a synthetic `ChainTransfer`. Pipeline: 158 tests / 4 e2e skipped, typecheck + lint clean. README rewritten with a quick-demo hero section.
42
+ - **CLI binary (X402-14)** in `src/cli/` + `src/cli.ts`: the user-facing surface for v0.1, composing the four substrates (Proxy / Decoder / Chain / Reconciliation) into a single `x402trace` command. Two subcommands — `x402trace proxy --upstream <url> [--port 8402] [--log human|json] [--log-file <path>] [--log-secrets] [--reconcile] [--rpc-url <url>] [--watch-timeout-ms <n>]` runs the live pipeline; `x402trace inspect <jsonl-log-file> [--log human|json] [--watch-timeout-ms <n>]` replays a captured log and re-runs reconciliation offline. Built on `commander@14`. Modules — `index.ts` (commander dispatch + `runCli` testable entry), `proxy-command.ts` (live pipeline wiring; opens a second `JsonlSink` against the same log path for `chain.transfer` and `reconcile.result` records — **closes the X402-13 deferred acceptance bullet** "All reconciliation events written to a local JSONL log file"), `inspect-command.ts` (offline replay), `replay.ts` (JSONL reader driving a virtual-clock engine via the new `engine.tick()` sweep method), `format-result.ts` (human + JSON renderers for `ReconciliationResult` — the canonical `RECONCILED ⚠ settled-but-server-thinks-not` headline per [SPEC.md § 3](./SPEC.md#3-user-flow)), `color.ts` (TTY + `NO_COLOR`-aware ANSI helpers; no `chalk` dep), `exit-codes.ts` (0 success / 1 usage / 2 runtime per the X402-14 ticket). 28 new unit tests + 1 smoke test that drives the full proxy + decoder + JSONL pipeline against the dogfood rig and replays the captured log through `inspect`. Pipeline: 149 tests / 4 e2e skipped, typecheck + lint clean. `scripts/proxy.ts` is now a thin shim that defers to `runCli`; `pnpm proxy` and `pnpm x402trace` both work, and `npx x402trace` will work once published.
43
+ - **Timeout reconciliation engine (X402-13)** in `src/reconciliation/`: the headline feature of the v0.1 wedge. Four modules — `types.ts` (`PendingExchange` + `ReconciliationResult` 4-variant discriminated union: `settled_on_chain` / `not_settled` / `value_mismatch` / `recipient_mismatch`), `match.ts` (pure `matchPendingAgainstTransfer` checking `(payer, payee, value, nonce)` exact-equality; case-insensitive on addresses + nonce), `engine.ts` (`createReconciliationEngine({watchTimeoutMs?, sweepIntervalMs?, now?}) → Engine` with three ingest methods for proxy / decoder / chain streams, in-memory pending-set with two-half-join semantics, periodic sweep for `not_settled` after `watchTimeoutMs` (default 60_000), injectable clock for tests), `index.ts`. 17 unit tests covering the match function + engine lifecycle (rejected outcomes flag, paid outcomes don't, settled_on_chain emit, not_settled timeout, value/recipient mismatch, arrival-order independence) + 2-test integration that **reproduces the canonical [#1062](https://github.com/coinbase/x402/issues/1062) scenario** end-to-end: mock facilitator rejects → engine emits `settled_on_chain` when matching ChainTransfer arrives. Pipeline: 120 tests / 4 e2e skipped, no new deps.
44
+ - Local mock x402 facilitator (X402-3) at `src/dogfood/mock-facilitator.ts` implementing v1 `POST /verify` and `POST /settle` with canned-success responses. Unblocks integration testing without on-chain USDC and provides the test harness `TESTING.md` calls for. `scripts/mock-facilitator.ts` is the standalone entry; `tests/integration/dogfood-paid-flow.test.ts` asserts the full 402 → signed retry → 200 + `X-PAYMENT-RESPONSE` flow against it.
45
+ - Shared `src/dogfood/http-adapter.ts` for mounting a Hono app on a Node `http` server (used by `dev-server.ts`, `mock-facilitator.ts`, and the integration test). Avoids a separate `@hono/node-server` dep.
46
+ - Minimal `tsconfig.json` (strict ESM NodeNext), `vitest.config.ts`, `eslint.config.js` (flat), and `.prettierrc.json` scoped to what X402-3 needed. X402-10 will tighten and broaden these.
47
+
48
+ ### Changed
49
+
50
+
51
+
52
+ ### Deprecated
53
+
54
+
55
+
56
+ ### Removed
57
+
58
+
59
+
60
+ ### Fixed
61
+
62
+
63
+
64
+ ### Security
65
+
66
+
67
+
68
+ ---
69
+
70
+ [Unreleased]: https://github.com/fardinvahdat/x402trace/compare/v0.1.0...HEAD
71
+ [0.1.0]: https://github.com/fardinvahdat/x402trace/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 fardin vahdat
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,121 @@
1
+ # x402trace
2
+
3
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](./LICENSE)
4
+ [![CI](https://github.com/fardinvahdat/x402trace/actions/workflows/ci.yml/badge.svg?branch=v1)](https://github.com/fardinvahdat/x402trace/actions/workflows/ci.yml)
5
+ [![npm version](https://img.shields.io/npm/v/x402trace.svg)](https://www.npmjs.com/package/x402trace)
6
+
7
+ **A local CLI that catches `x402` payment failures that cost real money** — starting with the [coinbase/x402 #1062](https://github.com/coinbase/x402/issues/1062) symptom: the buyer is debited on-chain, but the facilitator times out and your server thinks the payment failed.
8
+
9
+ ---
10
+
11
+ ## The problem
12
+
13
+ You wire up [x402](https://x402.org) on Base Sepolia. A buyer sends `X-PAYMENT`. The facilitator broadcasts the EIP-3009 `transferWithAuthorization` — and then hangs. Your `paymentMiddleware` times out and your client gets back:
14
+
15
+ ```
16
+ HTTP/1.1 502 Bad Gateway
17
+ content-type: text/plain
18
+
19
+ Bad Gateway
20
+ ```
21
+
22
+ The buyer sees a failure. The buyer's wallet was actually debited. The on-chain receipt exists, but nothing in your logs points at it. You have no programmatic path to reconcile.
23
+
24
+ This is the [#1062](https://github.com/coinbase/x402/issues/1062) gap. **x402trace closes it.**
25
+
26
+ ## 30-second quickstart
27
+
28
+ > Requires Node ≥ 20, pnpm, and a Base Sepolia test wallet funded with USDC + dust ETH. See [`examples/README.md`](./examples/README.md) for the full prereq list.
29
+
30
+ ```bash
31
+ # 1. Install
32
+ git clone https://github.com/fardinvahdat/x402trace.git
33
+ cd x402trace
34
+ pnpm install
35
+
36
+ # 2. Populate .env (one-time)
37
+ cp .env.example .env
38
+ $EDITOR .env # set PAYER_PRIVATE_KEY + RECEIVER_ADDRESS
39
+
40
+ # 3. Run the canonical #1062 demo (real Base Sepolia, ~17s)
41
+ ./examples/e2e-timeout-reconciliation.sh
42
+ ```
43
+
44
+ The last line of output is the detection x402trace was built for:
45
+
46
+ ```
47
+ RECONCILED ⚠ settled-but-server-thinks-not id=35d9aea1…
48
+ tx=0x116ccf73… value=1000 payer=0xADEe…B895 → payee=0xADEe…B895 gap=11904ms
49
+ ```
50
+
51
+ That `tx=` field is a real Base Sepolia settlement — [view it on basescan](https://sepolia.basescan.org/tx/0x116ccf73fa77eda19aea149606042f1e848e8afe2f719a0d2890dd2b2ff0ba52). An asciinema replay of the full run is committed at [`examples/cast/e2e-timeout-reconciliation.cast`](./examples/cast/e2e-timeout-reconciliation.cast) — `asciinema play` it locally.
52
+
53
+ ## Install
54
+
55
+ ```bash
56
+ npm install -g x402trace # or `pnpm add -g x402trace`, `npx x402trace --help`
57
+ ```
58
+
59
+ Requires Node ≥ 20.
60
+
61
+ ## How it works
62
+
63
+ ```
64
+ ┌────────┐ ┌────────────┐ ┌──────────┐ ┌─────────────────────┐
65
+ │ client │ ──► │ x402trace │ ──► │ your │ ──► │ x402.org/facilitator│
66
+ └────────┘ │ proxy │ │ server │ └──────────┬──────────┘
67
+ └──────┬─────┘ └──────────┘ │
68
+ │ ▲ │ /settle
69
+ │ │ slow/timeout broadcasts
70
+ │ │ ▼
71
+ │ ┌─────┴────────┐ ┌──────────────┐
72
+ │ │ reconcile │ ◄── │ Base Sepolia │
73
+ └──────────►│ engine │ │ USDC Transfer│
74
+ └──────────────┘ └──────────────┘
75
+ ```
76
+
77
+ - **Proxy** — sits between the client and your x402 server. Captures every `X-PAYMENT` / `X-PAYMENT-RESPONSE` header to a JSONL log.
78
+ - **Decoder** — turns each captured request into structured `PaymentRequirements` / `PaymentPayload` / `FacilitatorResponse` records.
79
+ - **Chain client** — subscribes to Base Sepolia USDC `Transfer` events, enriches each with the matching EIP-3009 `AuthorizationUsed.nonce`.
80
+ - **Reconciliation engine** — joins facilitator-rejected exchanges against on-chain transfers by `(payer, payee, value, nonce)` and emits `settled_on_chain` / `not_settled` / `value_mismatch` / `recipient_mismatch`.
81
+
82
+ Full architecture: [ARCHITECTURE.md](./ARCHITECTURE.md). Wedge rationale: [DECISIONS.md → ADR-001](./DECISIONS.md). On-disk schema: [`src/decoder/schema.md`](./src/decoder/schema.md).
83
+
84
+ ## CLI
85
+
86
+ ```bash
87
+ x402trace proxy --upstream <url> [--reconcile] [--log human|json] …
88
+ x402trace inspect <jsonl-log-file> [--log human|json] …
89
+ ```
90
+
91
+ The authoritative flag list is `x402trace --help` / `x402trace proxy --help` / `x402trace inspect --help` — they're the source of truth and are wired into the unit tests. See also [`pnpm x402trace --help`](./src/cli/index.ts) directly in the repo.
92
+
93
+ ## Roadmap
94
+
95
+ **v0.1** (current, ~6 weeks from project start) — local proxy + timeout reconciliation + structured logs. Base Sepolia, `x402.org/facilitator`, `exact` EVM scheme only. Detect-and-notify, no auto-refund. Wedge accepted in [ADR-001](./DECISIONS.md).
96
+
97
+ **v0.2 stretch** (from [SPEC.md § 5](./SPEC.md#5-v02-stretch-deferred-not-killed), ordered by ranked dogfood pain):
98
+
99
+ - Mainnet (after ≥1 week of clean testnet traffic)
100
+ - `x402trace inspect <captured-402.json>` — pure-function offline 402 decode
101
+ - `x402trace doctor <wallet> <service>` — pre-flight wallet/service check
102
+ - `x402trace bazaar-check` — Bazaar indexing diagnostics
103
+ - `x402trace versions` — SDK-skew audit across `x402`, `x402-fetch`, facilitator
104
+ - Multi-facilitator support (CDP, PayAI, x402-rs)
105
+ - Reconciliation **actions** beyond JSONL (webhook, structured remediation)
106
+
107
+ ## Differentiation
108
+
109
+ `x402scan` / `xpay` / `x402lint` are excellent at general inspection and routing. x402trace is for the narrow, expensive moment when your payment vanished into the gap between facilitator and chain — when you most need a debugger and least have one. Full comparison in [SPEC.md § 8](./SPEC.md#8-differentiation).
110
+
111
+ ## Contributing
112
+
113
+ Personal project. PRs and bug reports welcome. Read in this order:
114
+
115
+ 1. [CLAUDE.md](./CLAUDE.md) — operating manual + hard rules
116
+ 2. [TESTING.md](./TESTING.md) — testing is a hard requirement, not a nice-to-have
117
+ 3. [CONTRIBUTING.md](./CONTRIBUTING.md) — branching + PR workflow
118
+
119
+ ## License
120
+
121
+ [Apache 2.0](./LICENSE)
@@ -0,0 +1,48 @@
1
+ /**
2
+ * USDC + EIP-3009 event ABIs and well-known addresses for v0.1 (Base Sepolia only).
3
+ *
4
+ * Per ADR-001 the v0.1 wedge is Base-Sepolia-only with `exact` EVM scheme.
5
+ * The USDC contract there (Circle's testnet FiatTokenV2) emits two events
6
+ * we care about on a `transferWithAuthorization`:
7
+ *
8
+ * 1. `Transfer(from, to, value)` — ERC-20 standard event
9
+ * 2. `AuthorizationUsed(authorizer, nonce)` — EIP-3009 settlement marker
10
+ *
11
+ * The reconciliation engine matches facilitator-timed-out payments to
12
+ * on-chain settlements by `(payer, payee, value, nonce)` — the nonce is
13
+ * what makes the match exact, since EIP-3009 nonces are unique per
14
+ * (payer, contract).
15
+ */
16
+ import type { Address } from "./types.js";
17
+ /** Base Sepolia USDC (Circle testnet FiatTokenV2). */
18
+ export declare const BASE_SEPOLIA_USDC: Address;
19
+ export declare const USDC_TRANSFER_EVENT: {
20
+ readonly type: "event";
21
+ readonly name: "Transfer";
22
+ readonly inputs: readonly [{
23
+ readonly indexed: true;
24
+ readonly name: "from";
25
+ readonly type: "address";
26
+ }, {
27
+ readonly indexed: true;
28
+ readonly name: "to";
29
+ readonly type: "address";
30
+ }, {
31
+ readonly indexed: false;
32
+ readonly name: "value";
33
+ readonly type: "uint256";
34
+ }];
35
+ };
36
+ export declare const AUTHORIZATION_USED_EVENT: {
37
+ readonly type: "event";
38
+ readonly name: "AuthorizationUsed";
39
+ readonly inputs: readonly [{
40
+ readonly indexed: true;
41
+ readonly name: "authorizer";
42
+ readonly type: "address";
43
+ }, {
44
+ readonly indexed: true;
45
+ readonly name: "nonce";
46
+ readonly type: "bytes32";
47
+ }];
48
+ };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * USDC + EIP-3009 event ABIs and well-known addresses for v0.1 (Base Sepolia only).
3
+ *
4
+ * Per ADR-001 the v0.1 wedge is Base-Sepolia-only with `exact` EVM scheme.
5
+ * The USDC contract there (Circle's testnet FiatTokenV2) emits two events
6
+ * we care about on a `transferWithAuthorization`:
7
+ *
8
+ * 1. `Transfer(from, to, value)` — ERC-20 standard event
9
+ * 2. `AuthorizationUsed(authorizer, nonce)` — EIP-3009 settlement marker
10
+ *
11
+ * The reconciliation engine matches facilitator-timed-out payments to
12
+ * on-chain settlements by `(payer, payee, value, nonce)` — the nonce is
13
+ * what makes the match exact, since EIP-3009 nonces are unique per
14
+ * (payer, contract).
15
+ */
16
+ /** Base Sepolia USDC (Circle testnet FiatTokenV2). */
17
+ export const BASE_SEPOLIA_USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
18
+ export const USDC_TRANSFER_EVENT = {
19
+ type: "event",
20
+ name: "Transfer",
21
+ inputs: [
22
+ { indexed: true, name: "from", type: "address" },
23
+ { indexed: true, name: "to", type: "address" },
24
+ { indexed: false, name: "value", type: "uint256" },
25
+ ],
26
+ };
27
+ export const AUTHORIZATION_USED_EVENT = {
28
+ type: "event",
29
+ name: "AuthorizationUsed",
30
+ inputs: [
31
+ { indexed: true, name: "authorizer", type: "address" },
32
+ { indexed: true, name: "nonce", type: "bytes32" },
33
+ ],
34
+ };
@@ -0,0 +1,6 @@
1
+ import type { ChainClient, ChainClientOptions } from "./types.js";
2
+ /**
3
+ * Build a read-only chain client for Base Sepolia. Never holds private
4
+ * keys; never broadcasts transactions. Only reads logs + receipts.
5
+ */
6
+ export declare function createChainClient(opts?: ChainClientOptions): ChainClient;