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): fresh-wallet workers buy real work from a brand-new wallet per job, with a public Data Desk

qhqffeb1c03334fa
diff --git a/.env.example b/.env.example
index d174d73e0..859bd81c0 100644
--- a/.env.example
+++ b/.env.example
@@ -574,6 +574,32 @@ X402_VOLUME_PER_RUN_CAP_ATOMIC=1100000
# tick's own daily cap (X402_RING_DAILY_CAP_ATOMIC below) — the two never mix.
X402_AUTONOMOUS_DAILY_CAP_ATOMIC=
+# ── Fresh-wallet workers (api/cron/x402-fresh-workers.js) ──────────────────────
+# Every minute: mint brand-new wallets, fund each with one job's USDC plus its
+# own fees, have each buy real work (a 3D prop for /forged or a dataset for
+# /data-desk) over x402, then empty and close it. Fired by the economy
+# heartbeat; ON by default; the global X402_AUTONOMOUS_ENABLED=false pauses it.
+# Docs: docs/x402-fresh-workers.md.
+X402_FRESH_WORKERS_ENABLED=true
+# Fresh wallets minted (and jobs bought) per minute. Default 3.
+X402_FRESH_WORKERS_PER_TICK=3
+# One paid Forge generation every N ticks; the other slots buy datasets.
+# Default 10 → ~144 new library props a day.
+X402_FRESH_WORKERS_FORGE_EVERY_N_TICKS=10
+# The lane's OWN daily USDC ceiling (atomics), summed from x402_autonomous_log
+# rows tagged pipeline='fresh-workers'. Default $40. The USDC recirculates to
+# the treasury; this bounds the float in flight, not a cost.
+X402_FRESH_WORKERS_DAILY_CAP_ATOMIC=40000000
+# Wall-clock budget per tick (ms), kept under the heartbeat's 60 s abort.
+X402_FRESH_WORKERS_TICK_BUDGET_MS=50000
+# A wallet left mid-flight for this long (s) is reclaimed by the next tick.
+X402_FRESH_WORKERS_RECLAIM_AFTER_S=90
+# Sweep retries before a wallet is marked stranded and an ops alert fires.
+X402_FRESH_WORKERS_MAX_SWEEP_ATTEMPTS=20
+# How long (h) a fresh wallet stays in the controlled-wallet set so the leak
+# scanner classifies its funding leg as internal.
+X402_FRESH_WORKERS_MEMBERSHIP_HOURS=36
+
# ── Per-minute ring tick (api/cron/x402-ring-tick.js) ──────────────────────────
# A dedicated * * * * * cron that produces steady, capped, fee-minimal paid
# traffic: cheap tips/services every minute plus a periodic ring-settle carrier.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index be9e4ee1b..af0fbb8c5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,12 @@
Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).
+## 2026-09-22
+
+- **Data Desk** (`/data-desk`): Live market data bought minute by minute by brand-new agent wallets over x402. Every dataset carries its receipt: the wallet that paid, the price, and the Solana settlement transaction.
+- **Docs · Fresh-wallet workers** (`/docs/x402-fresh-workers`): How the platform mints a brand-new Solana wallet for every x402 purchase, what those wallets buy (3D props for the library, datasets for the data desk), how each wallet is emptied and closed so nothing strands, and where to watch it.
+- **Agents now buy real work from brand-new wallets, and you can watch it**: The platform's agent economy used to prove the payment rail from a few long-lived wallets buying test calls. It now mints a fresh Solana wallet for every purchase: each one is created, given exactly one job's worth of USDC, pays a three.ws endpoint, and is emptied and closed within the minute. Every purchase does something useful. Some buy a 3D generation that lands in the Agent-Forged Gallery, where a new fresh wallet badge marks it. The rest buy live market data, which now has its own page, the Data Desk, showing each dataset with the wallet that paid, the price, and the Solana receipt. Both feeds are public JSON as well, and a new stats endpoint lists every wallet with its three transactions. (`/data-desk`) `[feature]`
+
## 2026-09-21
- **Forge now asks what your model is for**: Under a finished model in Forge there is a new one-tap row: Game, Web, Avatar, Simulation, Print, AR, or Just playing. It is optional, it is remembered in your browser so you are only asked once, and it rides along on your later generations. We are using it to see which kinds of work Forge does well and which it does not, by use, instead of one blended number for everyone. Developers calling the Forge API can send the same thing as a destination field. (`/forge`) `[improvement]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 5756f7c3b..a1fc911a5 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -164,6 +164,7 @@ bottom.
| Choreographer | [pages/choreograph.html](pages/choreograph.html) + [src/choreograph-page.js](src/choreograph-page.js), engine [src/runtime/choreography.js](src/runtime/choreography.js) | Live at `/choreograph` | Timeline for composing gesture slots into named, timed routines, previewed on the shared live-preview engine with crossfades and a scrubbable playhead. One dependency-free module defines the routine format, the URL wire format and the timing engine; the studio, `PUT /api/agents/:id/animations` (stored at `meta.choreographies`), the public manifest and `AgentAvatar.playChoreography` all import it, and `<agent-3d>.playRoutine('welcome')` performs one from any embed. Also published as `@three-ws/avatar/runtime/choreography.js` · see [docs/choreography.md](docs/choreography.md) |
| Character Library | [pages/character-library.html](pages/character-library.html) + [src/character-library.js](src/character-library.js) (search/sort/link logic in [src/shared/character-library-view.js](src/shared/character-library-view.js), covered by [tests/character-library-view.test.js](tests/character-library-view.test.js)) → `/character-library`, API [api/avatars/library.js](api/avatars/library.js) | Live at `/character-library` | Professionally rigged Mixamo characters (skinned GLB + thumbnails on R2, `avatars/mixamo/`), each drives the full animation library. The live count comes from the R2 manifest and renders in the hero; no page copy hard-codes it. Pipeline: [scripts/fetch-mixamo-avatars.mjs](scripts/fetch-mixamo-avatars.mjs) → [scripts/convert-mixamo-avatars.mjs](scripts/convert-mixamo-avatars.mjs) → [scripts/fetch-mixamo-avatar-thumbnails.mjs](scripts/fetch-mixamo-avatar-thumbnails.mjs) → [scripts/build-mixamo-avatar-library.mjs](scripts/build-mixamo-avatar-library.mjs) publishes `avatars/library/manifest.json`. Cards deep-link into the 3D viewer (`/app#model=`), Widget Studio (`/studio?model=`), and Animation Studio (`/pose?src=`). Mirrors the animation-library R2-manifest pattern (no DB). See [public/avatars/mixamo/README.md](public/avatars/mixamo/README.md) |
| Object Library | [pages/objects.html](pages/objects.html) + [src/objects-library.js](src/objects-library.js) → `/objects`, API [api/objects/library.js](api/objects/library.js) | Live at `/objects` | Hundreds of CC0 (public-domain) 3D props from Poly Haven (packed to GLB on R2, `objects/polyhaven/`). Pipeline: [scripts/fetch-polyhaven-objects.mjs](scripts/fetch-polyhaven-objects.mjs) (glTF→GLB via @gltf-transform) → [scripts/render-glb-thumbnails.mjs](scripts/render-glb-thumbnails.mjs) → [scripts/build-object-library.mjs](scripts/build-object-library.mjs) publishes `objects/library/manifest.json`. Same R2-manifest pattern as the Character/animation libraries (no DB). Cards preview in the 3D viewer (`/app#model=`), place into AR Studio (`/ar/studio?src=`), and download the GLB directly (CC0). AR Studio's tray also has an Objects tab over the same manifest. The grid renders 48 cards at a time (a Load more button, plus an IntersectionObserver that pulls the next chunk as you approach it) and each card is a still thumbnail until you dwell on it, at which point that one card upgrades to a live auto-rotating `<model-viewer>`; at most six stay mounted. The manifest read falls back to the bucket's public CDN domain when the signed S3 read fails (`getPublicObjectBuffer` in [api/_lib/r2.js](api/_lib/r2.js)), so a bad storage credential can no longer empty a library of public CC0 bytes. |
+| Data Desk | [pages/data-desk.html](pages/data-desk.html) + [src/data-desk.js](src/data-desk.js) `→ /data-desk`, API [api/data-desk.js](api/data-desk.js) `→ /api/data-desk`, writer [api/_lib/x402/fresh-workers/jobs.js](api/_lib/x402/fresh-workers/jobs.js) | Live at `/data-desk` | Live market data BOUGHT by the fresh-wallet workers with real USDC over x402: the newest purchase of each of 18 datasets (global snapshot, trending, gas, DeFi TVL, stablecoins, news pulse, fees, DEX volumes, mood, hacks, yields, DeFi radar, chains, crypto intel, market pulse, heatmap, $THREE intel, coin markets), each rendered with a slug-specific layout and its receipt (fresh wallet, price, Solscan link), a ledger of recent purchases, and the lane's 24 h numbers (wallets closed, USDC recirculated, SOL burned in fees, rent recycled). Honest feed: no synthetic rows; before the first purchase the page shows its designed empty state. Auto-refreshes every minute, `/` focuses the filter. |
| Agent-Forged Gallery | [pages/forged.html](pages/forged.html) + [src/forged-gallery.js](src/forged-gallery.js) → `/forged`, API [api/forged.js](api/forged.js), writer [api/_lib/x402/pipelines/forge-content.js](api/_lib/x402/pipelines/forge-content.js) | Live at `/forged` | 3D props BOUGHT by the autonomous x402 agents with real USDC: the hourly forge-content pipeline pays `/api/x402/forge` (draft tier), the generated GLB lands in `forge_autonomous_props` with payment provenance (payer wallet, price, Solana settlement signature), and `/forged` renders each prop with its on-chain receipt linked to Solscan. Honest feed: no synthetic entries; before the first paid generation the page shows its designed empty state. Category chips built from the eight families in [api/_lib/x402/pipelines/forge-catalog.js](api/_lib/x402/pipelines/forge-catalog.js) (club-decor, ar-object, diorama-set, avatar-item, vehicle, container, furniture, terrain), prompt search, newest/priciest/most-novel sorts. |
| Motion Swap (avatar body-swap in video) | [pages/motion-swap.html](pages/motion-swap.html) `→ /motion-swap` + [src/motion-swap.js](src/motion-swap.js), API [api/motion-swap.js](api/motion-swap.js), worker [workers/model-video2motion/](workers/model-video2motion) | Live | Upload a video of one person, get it back with a 3D avatar performing their motion. The worker (CPU Cloud Run, MediaPipe pose + hands + multiclass person segmentation, all Apache-2.0) tracks 33 body world landmarks plus 21 per hand each frame, solves them onto the canonical Wolf3D skeleton, body and all 30 finger bones, with an in-house bend-plane IK solver ([pose_solver.py](workers/model-video2motion/pose_solver.py), pure NumPy, unit-tested), and emits a standard `AnimationClip.toJSON()` + person-mask video + per-frame screen anchors. The browser composites in one WebGL scene: footage on a shader quad with the subject pixelated under the mask, avatar retargeted via [src/animation-retarget.js](src/animation-retarget.js) and pinned to the subject's anchor each frame, MediaRecorder export with original audio. Provider mode `video2motion` (`GCP_VIDEO2MOTION_URL`) in [api/_providers/gcp.js](api/_providers/gcp.js). Docs: [docs/motion-swap.md](docs/motion-swap.md). Tests: [test_pose_solver.py](workers/model-video2motion/test_pose_solver.py) (solver) and [test_service.py](workers/model-video2motion/test_service.py) (HTTP contract, ffmpeg normalize/mask encode, SSRF guard, live MediaPipe pass). |
| Smart home (`/smart-home`) | Page [pages/smart-home.html](pages/smart-home.html) `→ /smart-home` and `/smart-home/:id` + [src/home/](src/home) (connect, manage, scene-model, scene-render, scene-fallback, satellite, satellite-link, pcm-player, plan, api). Store [api/_lib/home/store.js](api/_lib/home/store.js), runtime + backpressure [runtime.js](api/_lib/home/runtime.js) + [admission.js](api/_lib/home/admission.js), gate + tools [tools.js](api/_lib/home/tools.js) + [confirm.js](api/_lib/home/confirm.js), roster [members.js](api/_lib/home/members.js), privacy [privacy.js](api/_lib/home/privacy.js), plans + quotas [entitlements.js](api/_lib/home/entitlements.js) + [usage.js](api/_lib/home/usage.js), SSRF pin [api/_lib/home-url-guard.js](api/_lib/home-url-guard.js). HTTP [api/home/](api/home) (index, [id], [id]/call, [id]/activate, [id]/stream, [id]/grants, [id]/members, [id]/confirm, invites/[token], pair, pair/redeem, privacy, plan). Client [packages/home-bridge/](packages/home-bridge/README.md), MCP server [packages/home-mcp/](packages/home-mcp/README.md), hosted MCP tools [api/_mcp/tools/home.js](api/_mcp/tools/home.js). Dial-out for LAN-only houses [services/home-relay/](services/home-relay/README.md) + [home-assistant-integration/](home-assistant-integration) (HACS). Voice [services/home-satellite/](services/home-satellite/README.md) (Wyoming). Harness [scripts/home-test-instance.mjs](scripts/home-test-instance.mjs), unroutable-LAN relay rig [scripts/home-relay-live.mjs](scripts/home-relay-live.mjs) + [scripts/home-relay-e2e.mjs](scripts/home-relay-e2e.mjs) + [scripts/home-relay-gate-proof.mjs](scripts/home-relay-gate-proof.mjs), load fleet + envelope + chaos [scripts/home-fleet.mjs](scripts/home-fleet.mjs) / [scripts/home-load.mjs](scripts/home-load.mjs) / [scripts/home-chaos.mjs](scripts/home-chaos.mjs) (`npm run home:fleet`, `home:load`, `home:chaos`). Migrations `api/_lib/migrations/*_home_*.sql` | Live | The agent past the screen and into the building. **Zero device code, ever:** Home Assistant owns Zigbee, Z-Wave, Matter, Thread, BLE and 1,500 integrations, and three.ws is the layer in between: a connection record with the token encrypted at rest, a pooled per-home WebSocket, a room graph the 3D scene renders live, intent resolved to the household's own scenes, and one gate in front of everything. **The gate is the product decision:** reads are free, moves toward safety (lock, close, arm) run immediately and never prompt, and moves that OPEN the house (unlock, open a door/gate/garage, disarm) never run from a model call at all. They mint a pending confirmation a signed-in person redeems at `POST /api/home/:id/confirm`, which refuses every bearer principal including one holding `home:act`. It exists because Home Assistant's own `intent__HassTurnOff` is documented as performing an **unlock** on a lock, verified live. Entity and area names are untrusted input travelling in `structuredContent`, never interpolated into prose. Three reachability answers, all shipped: a remote https URL, a browser or MCP server inside the network, and the HACS integration that dials out so no Home Assistant credential ever leaves the house. Docs: [docs/smart-home.md](docs/smart-home.md), [docs/tutorials/connect-your-home.md](docs/tutorials/connect-your-home.md), [docs/home-households.md](docs/home-households.md), [docs/home-privacy.md](docs/home-privacy.md), [docs/home-plans.md](docs/home-plans.md), [docs/ops/home-operations.md](docs/ops/home-operations.md) (SLOs, the alerts, the measured scale envelope, the backpressure ladder, the seven chaos scenarios and the Cloud Run sizing). Evidence: [tasks/home/](tasks/home). Tests: `tests/home-*.test.js`, [tests/e2e/home-connect.spec.js](tests/e2e/home-connect.spec.js), [packages/home-bridge/tests/](packages/home-bridge/tests), [packages/home-mcp/tests/](packages/home-mcp/tests) |
@@ -230,6 +231,7 @@ bottom.
| 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), [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) |
+| Fresh-wallet workers (x402 volume from never-used wallets) | [api/_lib/x402/fresh-workers/](api/_lib/x402/fresh-workers) (`plan.js` pure planning, `chain.js` fund + sweep legs, `jobs.js` job catalog + sinks, `wallets.js` lifecycle store, `run.js` the tick), cron [api/cron/x402-fresh-workers.js](api/cron/x402-fresh-workers.js) fired by [api/cron/economy-tick.js](api/cron/economy-tick.js), stats API [api/fresh-workers.js](api/fresh-workers.js) `→ /api/fresh-workers`, runner [scripts/x402-fresh-workers-run.mjs](scripts/x402-fresh-workers-run.mjs), migration [api/_lib/migrations/20260922100000_x402_fresh_workers.sql](api/_lib/migrations/20260922100000_x402_fresh_workers.sql) | Live (on by default) | Every minute mints a few brand-new Solana wallets (secret-box encrypted, never mirrored into `x402_ring_wallets`), funds each in one transaction with exactly one job's USDC plus its own fees, has each self-pay a real x402 endpoint (a standard-tier Forge generation every N ticks, otherwise the next dataset in an 18-entry market-data rotation), lands the result where the site reads it (`forge_autonomous_props` → `/forged` with a fresh-wallet badge; `x402_data_desk` → `/data-desk`), then sweeps leftover USDC to the treasury, closes the token account (rent back to the funder) and drains the wallet to exactly zero. Stateful per wallet so an interrupted tick is finished by the next tick's reclaim pass; stranded wallets alert. Fresh wallets join `ringAllowedAddresses()` for a bounded window (`X402_FRESH_WORKERS_MEMBERSHIP_HOURS`) so the leak scanner classifies the funding leg as internal. Env: `X402_FRESH_WORKERS_*` (see [.env.example](.env.example)). Docs: [docs/x402-fresh-workers.md](docs/x402-fresh-workers.md). Tests: [tests/x402-fresh-workers.test.js](tests/x402-fresh-workers.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/20260922100000_x402_fresh_workers.sql b/api/_lib/migrations/20260922100000_x402_fresh_workers.sql
new file mode 100644
index 000000000..7b888f063
--- /dev/null
+++ b/api/_lib/migrations/20260922100000_x402_fresh_workers.sql
@@ -0,0 +1,73 @@
+-- x402 fresh-wallet workers: one brand-new Solana wallet per paid job.
+--
+-- The ring's payer pool reuses wallets to amortize USDC-ATA rent. This lane does
+-- the opposite on purpose: every job is bought by a wallet that never existed on
+-- chain before, and the wallet is emptied and its token account closed the moment
+-- the job is done, so the rent it borrowed goes straight back to the funder. Net
+-- cost per job is three base transaction fees; nothing strands.
+--
+-- Each row is one wallet's whole life:
+-- minted -> funded -> paid | pay_failed -> closed
+-- \-> sweep_failed (retried) -> stranded (alerted)
+-- fund_failed is terminal and moved no money.
+--
+-- The key is secret-box encrypted (WALLET_ENCRYPTION_KEY) exactly like the payer
+-- pool and custodial agent wallets. Rows are never deleted: the pubkey history is
+-- what lets the on-chain leak scanner classify the funding leg as internal.
+
+CREATE TABLE IF NOT EXISTS x402_fresh_wallets (
+ id bigserial PRIMARY KEY,
+ pubkey text NOT NULL UNIQUE,
+ usdc_ata text NOT NULL,
+ encrypted_secret text NOT NULL,
+ state text NOT NULL DEFAULT 'minted',
+ job_kind text NOT NULL, -- 'forge' | 'data'
+ job_slug text NOT NULL, -- ring-catalog slug the wallet buys
+ job_title text,
+ sol_funded_lamports bigint NOT NULL DEFAULT 0,
+ usdc_funded_atomic bigint NOT NULL DEFAULT 0,
+ fund_sig text,
+ pay_sig text,
+ amount_atomic bigint NOT NULL DEFAULT 0, -- USDC the job actually cost
+ sweep_sig text,
+ sol_reclaimed_lamports bigint NOT NULL DEFAULT 0,
+ usdc_returned_atomic bigint NOT NULL DEFAULT 0,
+ rent_reclaimed_lamports bigint NOT NULL DEFAULT 0,
+ attempts int NOT NULL DEFAULT 0,
+ error text,
+ run_id uuid,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ funded_at timestamptz,
+ paid_at timestamptz,
+ closed_at timestamptz
+);
+
+CREATE INDEX IF NOT EXISTS x402_fresh_wallets_state_updated ON x402_fresh_wallets (state, updated_at);
+CREATE INDEX IF NOT EXISTS x402_fresh_wallets_created ON x402_fresh_wallets (created_at DESC);
+
+COMMENT ON TABLE x402_fresh_wallets IS
+ 'One row per throwaway payer wallet in the x402 fresh-workers lane: minted, funded, pays one useful job, swept back and closed. Secrets secret-box encrypted.';
+
+-- The data desk: what the fresh wallets bought from the paid market-data and
+-- intel endpoints, kept so the site can show it with the receipt attached. One
+-- row per purchase; the public feed reads the newest row per slug.
+CREATE TABLE IF NOT EXISTS x402_data_desk (
+ id bigserial PRIMARY KEY,
+ ts timestamptz NOT NULL DEFAULT now(),
+ slug text NOT NULL,
+ title text NOT NULL,
+ endpoint_path text NOT NULL,
+ payload jsonb NOT NULL,
+ payer text,
+ tx_sig text,
+ amount_atomic bigint NOT NULL DEFAULT 0,
+ run_id uuid,
+ wallet_id bigint
+);
+
+CREATE INDEX IF NOT EXISTS x402_data_desk_slug_ts ON x402_data_desk (slug, ts DESC);
+CREATE INDEX IF NOT EXISTS x402_data_desk_ts ON x402_data_desk (ts DESC);
+
+COMMENT ON TABLE x402_data_desk IS
+ 'Datasets bought over x402 by fresh worker wallets, with payer, price and settlement signature. Served by /api/data-desk and rendered at /data-desk.';
diff --git a/api/_lib/x402/fresh-workers/chain.js b/api/_lib/x402/fresh-workers/chain.js
new file mode 100644
index 000000000..332b27432
--- /dev/null
+++ b/api/_lib/x402/fresh-workers/chain.js
@@ -0,0 +1,163 @@
+// api/_lib/x402/fresh-workers/chain.js
+//
+// The on-chain legs of a fresh worker wallet's life, as small effectful helpers
+// over the shared connection + read guards: fund a batch of new wallets in one
+// transaction, read a wallet's SOL/USDC, and sweep a wallet back to the funders
+// while closing its token account so the rent it borrowed goes home.
+//
+// Invariants: every recipient is a funder or a fresh wallet this lane minted;
+// USDC only ever moves treasury -> fresh -> treasury; SOL only ever moves
+// funder -> fresh -> funder. Nothing here touches a wallet it did not create.
+
+import {
+ PublicKey, SystemProgram, TransactionMessage, VersionedTransaction, ComputeBudgetProgram,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync,
+ createTransferCheckedInstruction,
+ createAssociatedTokenAccountIdempotentInstruction,
+ createCloseAccountInstruction,
+ TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+
+import { env } from '../../env.js';
+import { blockhashKey, getRecentBlockhashInfo, readAccountInfoOrNull } from '../../solana/read-guards.js';
+import { tokenAmountFromAccountData } from '../pipelines/ring-pool-fund.js';
+import { ATA_RENT_LAMPORTS, BASE_FEE_LAMPORTS, RENT_EXEMPT_FALLBACK_LAMPORTS, sweepAmountLamports } from './plan.js';
+
+// Compute-unit ceiling for the funding tx (a handful of transfers + ATA creates)
+// and the sweep (one transfer, one close, one system transfer). Generous but far
+// below the 1.4M default, so a tiny priority price stays a tiny fee.
+const FUND_CU_LIMIT = 200_000;
+const SWEEP_CU_LIMIT = 60_000;
+// Lowest nonzero priority the funding tx pays so it lands promptly under load.
+const FUND_PRIORITY_MICROLAMPORTS = 5;
+
+export function usdcAtaOf(owner, mint) {
+ return getAssociatedTokenAddressSync(mint, owner, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);
+}
+
+let _rentExempt = { value: null, at: 0 };
+/** Rent-exempt minimum for a 0-byte account, read once an hour; constant fallback when RPC is dark. */
+export async function rentExemptLamports(conn, now = Date.now()) {
+ if (_rentExempt.value && now - _rentExempt.at < 3_600_000) return _rentExempt.value;
+ try {
+ const v = Number(await conn.getMinimumBalanceForRentExemption(0));
+ if (Number.isFinite(v) && v > 0) {
+ _rentExempt = { value: v, at: now };
+ return v;
+ }
+ } catch { /* fall through to the constant */ }
+ return _rentExempt.value || RENT_EXEMPT_FALLBACK_LAMPORTS;
+}
+
+export async function confirmSignature(conn, signature, timeoutMs = 30_000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const st = await conn.getSignatureStatuses([signature]).catch(() => null);
+ const v = st?.value?.[0];
+ if (v?.err) return { confirmed: false, err: JSON.stringify(v.err) };
+ if (v && (v.confirmationStatus === 'confirmed' || v.confirmationStatus === 'finalized')) return { confirmed: true };
+ await new Promise((r) => setTimeout(r, 1200));
+ }
+ return { confirmed: false, err: 'timeout' };
+}
+
+async function sendIxs(conn, feePayer, signers, instructions, { confirmMs = 30_000 } = {}) {
+ const { blockhash } = await getRecentBlockhashInfo(conn, blockhashKey({ url: env.SOLANA_RPC_URL }), { forceFresh: true });
+ const msg = new TransactionMessage({ payerKey: feePayer.publicKey, recentBlockhash: blockhash, instructions }).compileToV0Message();
+ const vtx = new VersionedTransaction(msg);
+ vtx.sign(signers);
+ const signature = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false, maxRetries: 5 });
+ const conf = await confirmSignature(conn, signature, confirmMs);
+ return { ok: conf.confirmed, signature, err: conf.confirmed ? null : conf.err };
+}
+
+/** SOL balance in lamports (0 for a never-seen account), or null when unreadable. */
+export async function readSolLamports(conn, pubkey) {
+ const info = await readAccountInfoOrNull(conn, pubkey, { commitment: 'confirmed', withCause: true });
+ if (info === null) return 0;
+ if (info === undefined) return null;
+ return Number(info.lamports || 0);
+}
+
+/** USDC held by an owner's ATA: { exists, atomic } or null when unreadable. */
+export async function readUsdc(conn, ata) {
+ const info = await readAccountInfoOrNull(conn, ata, { commitment: 'confirmed', withCause: true });
+ if (info === null) return { exists: false, atomic: 0n };
+ if (info === undefined) return null;
+ return { exists: true, atomic: tokenAmountFromAccountData(info.data) };
+}
+
+/**
+ * Fund every wallet in `targets` in ONE transaction: SOL from the funder, the
+ * wallet's USDC ATA created (rent paid by the funder), and the job's USDC moved
+ * from the treasury. Both funders sign; the treasury only as token authority.
+ * @param {{ conn, solFunder, treasury, mint, decimals, targets: Array<{ pubkey: PublicKey, ata: PublicKey, solLamports: number, usdcAtomic: bigint }> }} p
+ */
+export async function fundWallets({ conn, solFunder, treasury, mint, decimals, targets, confirmMs }) {
+ const treasuryAta = usdcAtaOf(treasury.publicKey, mint);
+ const ixs = [
+ ComputeBudgetProgram.setComputeUnitLimit({ units: FUND_CU_LIMIT }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: FUND_PRIORITY_MICROLAMPORTS }),
+ ];
+ for (const t of targets) {
+ ixs.push(SystemProgram.transfer({ fromPubkey: solFunder.publicKey, toPubkey: t.pubkey, lamports: t.solLamports }));
+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(
+ solFunder.publicKey, t.ata, t.pubkey, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ ));
+ if (t.usdcAtomic > 0n) {
+ ixs.push(createTransferCheckedInstruction(
+ treasuryAta, mint, t.ata, treasury.publicKey, t.usdcAtomic, decimals, [], TOKEN_PROGRAM_ID,
+ ));
+ }
+ }
+ const signers = solFunder.publicKey.equals(treasury.publicKey) ? [solFunder] : [solFunder, treasury];
+ return sendIxs(conn, solFunder, signers, ixs, { confirmMs });
+}
+
+/**
+ * Empty a fresh wallet and close its token account in ONE self-paid
+ * transaction: leftover USDC -> treasury, ATA rent -> the SOL funder, every
+ * remaining lamport but the base fee -> the SOL funder. The wallet ends at
+ * exactly zero. Returns what moved so the caller can book it.
+ * @param {{ conn, wallet, solFunder: PublicKey, treasury: PublicKey, mint, decimals, confirmMs?: number }} p
+ */
+export async function sweepWallet({ conn, wallet, solFunder, treasury, mint, decimals, confirmMs }) {
+ const owner = wallet.publicKey;
+ const ata = usdcAtaOf(owner, mint);
+ const [sol, usdc] = await Promise.all([readSolLamports(conn, owner), readUsdc(conn, ata)]);
+ if (sol === null || usdc === null) return { ok: false, err: 'balance_unreadable' };
+ if (sol === 0 && !usdc.exists) return { ok: true, signature: null, alreadyEmpty: true, solLamports: 0, usdcAtomic: 0n, rentLamports: 0 };
+ if (sol < BASE_FEE_LAMPORTS) return { ok: false, err: `below_sweep_fee:${sol}` };
+
+ const ixs = [
+ ComputeBudgetProgram.setComputeUnitLimit({ units: SWEEP_CU_LIMIT }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 0 }),
+ ];
+ if (usdc.exists) {
+ if (usdc.atomic > 0n) {
+ const treasuryAta = usdcAtaOf(treasury, mint);
+ ixs.push(createTransferCheckedInstruction(ata, mint, treasuryAta, owner, usdc.atomic, decimals, [], TOKEN_PROGRAM_ID));
+ }
+ // closeAccount: [account, rent destination, authority]. The funder paid the
+ // rent when it created the account, so the funder gets it back.
+ ixs.push(createCloseAccountInstruction(ata, solFunder, owner, [], TOKEN_PROGRAM_ID));
+ }
+ const send = sweepAmountLamports({ balanceLamports: sol, feeLamports: BASE_FEE_LAMPORTS });
+ if (send > 0) ixs.push(SystemProgram.transfer({ fromPubkey: owner, toPubkey: solFunder, lamports: send }));
+
+ const res = await sendIxs(conn, wallet, [wallet], ixs, { confirmMs });
+ if (!res.ok) return { ok: false, signature: res.signature, err: res.err };
+ return {
+ ok: true,
+ signature: res.signature,
+ solLamports: send,
+ usdcAtomic: usdc.exists ? usdc.atomic : 0n,
+ // USDC is a classic SPL account, so its rent is the fixed classic figure
+ // (the same constant the facilitator books when it creates one).
+ rentLamports: usdc.exists ? ATA_RENT_LAMPORTS : 0,
+ };
+}
+
+export { PublicKey };
diff --git a/api/_lib/x402/fresh-workers/jobs.js b/api/_lib/x402/fresh-workers/jobs.js
new file mode 100644
index 000000000..35a47983d
--- /dev/null
+++ b/api/_lib/x402/fresh-workers/jobs.js
@@ -0,0 +1,150 @@
+// api/_lib/x402/fresh-workers/jobs.js
+//
+// What a fresh wallet buys, and where the purchase lands so the site can show
+// it. Two kinds of job:
+//
+// forge : one paid text-to-3D generation on /api/x402/forge (standard tier).
+// The prop is persisted through the same path the hourly forge
+// pipeline uses, so it appears in the /forged library with the fresh
+// wallet as its payer.
+// data : one paid dataset from the market-data / intel storefront. The
+// response is stored in x402_data_desk with its receipt and served
+// by /api/data-desk for the /data-desk page.
+//
+// Every data job resolves its request contract (path, method, query, body,
+// default price) from the ring catalog (../ring-catalog.js), which is derived
+// from the handlers themselves, so a purchase never spends money on a request
+// the endpoint would reject.
+
+import { bySlug } from '../ring-catalog.js';
+import { priceFor } from '../../x402-prices.js';
+import { priceAtomicsForTier } from '../../forge-tiers.js';
+import {
+ forgePropForSeed,
+ persistProp,
+ ensureSchema as ensureForgePropsSchema,
+} from '../pipelines/forge-content.js';
+import { trimPayload } from './plan.js';
+
+// The datasets worth buying every few minutes: each one is something a visitor
+// can read at a glance and the site did not otherwise refresh on a schedule.
+// Order is the rotation order; a tick takes the next few in turn.
+export const DATA_JOBS = Object.freeze([
+ { slug: 'market-global', title: 'Global market snapshot', blurb: 'Total market cap, 24h volume, largest-coin dominance and the Fear & Greed index.' },
+ { slug: 'market-trending', title: 'Trending assets', blurb: 'The most-searched coins and categories of the last 24 hours.' },
+ { slug: 'market-gas', title: 'Gas oracle', blurb: 'Slow, standard and fast gas tiers with USD cost estimates.' },
+ { slug: 'market-defi', title: 'DeFi protocol TVL', blurb: 'Top protocols by total value locked with 1d and 7d change.' },
+ { slug: 'market-stablecoins', title: 'Stablecoin monitor', blurb: 'Top pegged assets by supply with live peg health.' },
+ { slug: 'news-pulse', title: 'News pulse', blurb: 'Headline flow and sentiment for $THREE over the last day.' },
+ { slug: 'market-fees', title: 'Protocol fees', blurb: 'Which protocols actually earn, ranked by 24h fees.' },
+ { slug: 'market-dex-volumes', title: 'DEX volume rankings', blurb: 'Decentralized exchanges ranked by 24h trading volume.' },
+ { slug: 'market-mood', title: 'Market mood', blurb: 'A one-number read of where the market is leaning right now.' },
+ { slug: 'market-hacks', title: 'Exploit database', blurb: 'Recorded DeFi hacks with amounts, techniques and 12-month totals.' },
+ { slug: 'market-yields', title: 'Yield opportunities', blurb: 'Pools ranked by APY with the median yield across the market.' },
+ { slug: 'defi-radar', title: 'DeFi radar', blurb: 'The protocols moving most right now.' },
+ { slug: 'market-chains', title: 'Chain TVL', blurb: 'Blockchains ranked by total value locked.' },
+ { slug: 'crypto-intel', title: 'Crypto intel: SOL', blurb: 'Live market intel for Solana.' },
+ { slug: 'market-pulse', title: 'Market pulse bundle', blurb: 'Global stats, Fear & Greed, top coins, gas, DeFi and stablecoins in one call.' },
+ { slug: 'market-heatmap', title: 'Market heatmap', blurb: 'Sector-by-sector performance at a glance.' },
+ { slug: 'three-intel', title: '$THREE intel', blurb: 'A live market signal for the platform coin.' },
+ { slug: 'market-coins', title: 'Coin markets', blurb: 'The ranked coin table: price, market cap, volume and 7-day change.' },
+]);
+
+export const DATA_JOB_SLUGS = Object.freeze(DATA_JOBS.map((j) => j.slug));
+
+const FORGE_TIER = 'standard';
+
+/** Resolve a data job's request contract and live price from the ring catalog. */
+export function resolveDataJob(slug) {
+ const meta = DATA_JOBS.find((j) => j.slug === slug);
+ const entry = bySlug(slug);
+ if (!meta || !entry) throw new Error(`fresh-workers: unknown data job "${slug}"`);
+ const qs = entry.query ? `?${new URLSearchParams(entry.query).toString()}` : '';
+ return {
+ kind: 'data',
+ slug,
+ title: meta.title,
+ blurb: meta.blurb,
+ path: `${entry.path}${qs}`,
+ endpointPath: entry.path,
+ method: entry.method,
+ body: entry.method === 'POST' ? entry.body() : null,
+ priceAtomic: Number(priceFor(entry.priceSlug, entry.priceAtomicDefault)),
+ };
+}
+
+/** Resolve the forge job for a tick: a prompt from the prop catalog keyed by the seed. */
+export function resolveForgeJob(seed) {
+ const { category, prompt } = forgePropForSeed(seed);
+ return {
+ kind: 'forge',
+ slug: 'forge',
+ title: `3D prop: ${category}`,
+ blurb: prompt,
+ category,
+ path: '/api/x402/forge',
+ endpointPath: '/api/x402/forge',
+ method: 'POST',
+ body: { prompt, tier: FORGE_TIER, aspect_ratio: '1:1' },
+ priceAtomic: Number(priceAtomicsForTier(FORGE_TIER)),
+ };
+}
+
+/** Resolve a planned { kind, slug } into a full job. */
+export function resolveJob(planned, seed) {
+ return planned.kind === 'forge' ? resolveForgeJob(seed) : resolveDataJob(planned.slug);
+}
+
+export async function ensureDataDeskSchema(sql) {
+ await sql`
+ CREATE TABLE IF NOT EXISTS x402_data_desk (
+ id bigserial PRIMARY KEY,
+ ts timestamptz NOT NULL DEFAULT now(),
+ slug text NOT NULL,
+ title text NOT NULL,
+ endpoint_path text NOT NULL,
+ payload jsonb NOT NULL,
+ payer text,
+ tx_sig text,
+ amount_atomic bigint NOT NULL DEFAULT 0,
+ run_id uuid,
+ wallet_id bigint
+ )`;
+ await sql`CREATE INDEX IF NOT EXISTS x402_data_desk_slug_ts ON x402_data_desk (slug, ts DESC)`;
+ await sql`CREATE INDEX IF NOT EXISTS x402_data_desk_ts ON x402_data_desk (ts DESC)`;
+}
+
+/**
+ * Land a successful purchase where the site reads it. Returns a compact
+ * summary for the call log. Never throws: a sink fault is reported in the
+ * summary so the payment is still recorded.
+ */
+export async function storeJobResult({ sql, job, wallet, result, runId }) {
+ const payer = wallet.pubkey;
+ const txSig = result.txSig || null;
+ const amountAtomic = result.paid ? result.amountAtomic : 0;
+ if (job.kind === 'forge') {
+ try {
+ await ensureForgePropsSchema();
+ } catch (err) {
+ return { sink: 'forge_autonomous_props', stored: false, error: `schema_failed:${err?.message}` };
+ }
+ const value = await persistProp({
+ runId, prompt: job.body.prompt, category: job.category,
+ response: result.responseBody, txSig, payer, amountAtomic,
+ });
+ return { sink: 'forge_autonomous_props', ...value };
+ }
+ try {
+ await ensureDataDeskSchema(sql);
+ const payload = trimPayload(result.responseBody);
+ const rows = await sql`
+ INSERT INTO x402_data_desk (slug, title, endpoint_path, payload, payer, tx_sig, amount_atomic, run_id, wallet_id)
+ VALUES (${job.slug}, ${job.title}, ${job.endpointPath}, ${JSON.stringify(payload)}::jsonb,
+ ${payer}, ${txSig}, ${amountAtomic}, ${runId}, ${wallet.id})
+ RETURNING id`;
+ return { sink: 'x402_data_desk', stored: true, id: rows[0]?.id ?? null, slug: job.slug };
+ } catch (err) {
+ return { sink: 'x402_data_desk', stored: false, error: err?.message || 'persist_failed' };
+ }
+}
diff --git a/api/_lib/x402/fresh-workers/plan.js b/api/_lib/x402/fresh-workers/plan.js
new file mode 100644
index 000000000..84585b514
--- /dev/null
+++ b/api/_lib/x402/fresh-workers/plan.js
@@ -0,0 +1,184 @@
+// api/_lib/x402/fresh-workers/plan.js
+//
+// Pure planning for the fresh-wallet workers lane: config parsing, the SOL a
+// brand-new wallet needs to pay one job and empty itself, which jobs a tick buys,
+// whether the funders can afford them, and what to do with a wallet that was
+// left mid-flight. No I/O, no signing, unit-tested on its own.
+//
+// The lane exists so that x402 volume comes from wallets that have never existed
+// before, and so that every payment buys real work: a 3D prop for the /forged
+// library or a dataset for the /data-desk page. The reused payer pool
+// (../pool.js) amortizes USDC-ATA rent across many settles; this lane instead
+// closes the token account the moment the job is done and hands the rent back,
+// so a throwaway wallet costs three base fees and strands nothing.
+
+// Solana constants. The rent-exempt minimum for a data-less system account is
+// read live at runtime (getMinimumBalanceForRentExemption(0)); this is the
+// mainnet value it has returned since 2021 and the fallback when RPC is dark.
+export const RENT_EXEMPT_FALLBACK_LAMPORTS = 890_880;
+// Rent locked by a classic SPL token account (matches self-facilitator.js).
+export const ATA_RENT_LAMPORTS = 2_039_280;
+// One signature at the base fee. The sweep transaction sets a zero priority
+// price so its fee is exactly this, which is what makes an exact drain possible.
+export const BASE_FEE_LAMPORTS = 5_000;
+
+const num = (v, d) => {
+ const n = Number(v);
+ return Number.isFinite(n) && n >= 0 ? n : d;
+};
+
+/** Every knob of the lane, parsed from env with the defaults documented in .env.example. */
+export function freshWorkersConfig(e = process.env) {
+ return {
+ // 'false' pauses the lane; anything else leaves it on. X402_AUTONOMOUS_ENABLED
+ // is the global kill switch and is honored by the cron before this is read.
+ enabled: String(e.X402_FRESH_WORKERS_ENABLED ?? 'true').trim().toLowerCase() !== 'false',
+ // Fresh wallets minted (and jobs bought) per minute.
+ perTick: Math.max(0, Math.floor(num(e.X402_FRESH_WORKERS_PER_TICK, 3))),
+ // One of the tick's jobs is a paid Forge generation every N ticks; the rest
+ // buy datasets. 10 -> ~144 new library props a day at 1 tick/min.
+ forgeEveryNTicks: Math.max(1, Math.floor(num(e.X402_FRESH_WORKERS_FORGE_EVERY_N_TICKS, 10))),
+ // USDC the lane may spend per UTC day (atomics). Recirculates to the treasury.
+ dailyCapAtomic: Math.floor(num(e.X402_FRESH_WORKERS_DAILY_CAP_ATOMIC, 40_000_000)),
+ // Worst-case fee the pay transaction may carry (mirrors the ring ceiling).
+ maxPayFeeLamports: Math.floor(num(e.X402_RING_MAX_FEE_PER_TX_LAMPORTS, 10_000)),
+ // Wall-clock budget for one tick. The economy heartbeat aborts a target at
+ // 60 s, so the lane stops launching new stages before that and lets the
+ // next tick finish whatever is still in flight.
+ tickBudgetMs: Math.max(10_000, Math.floor(num(e.X402_FRESH_WORKERS_TICK_BUDGET_MS, 50_000))),
+ // A wallet untouched for this long in a non-terminal state is reclaimed.
+ reclaimAfterS: Math.max(30, Math.floor(num(e.X402_FRESH_WORKERS_RECLAIM_AFTER_S, 90))),
+ // Sweep retries before a wallet is declared stranded and alerted.
+ maxSweepAttempts: Math.max(1, Math.floor(num(e.X402_FRESH_WORKERS_MAX_SWEEP_ATTEMPTS, 20))),
+ // How long a fresh wallet stays in the controlled-wallet set after minting.
+ // The leak scanner only classifies signatures newer than its cursor, so a
+ // day and a half covers any scan gap without growing the set without bound.
+ membershipWindowHours: Math.max(1, Math.floor(num(e.X402_FRESH_WORKERS_MEMBERSHIP_HOURS, 36))),
+ // Reclaims attempted per tick, so a backlog drains without eating the tick.
+ reclaimBatch: Math.max(1, Math.floor(num(e.X402_FRESH_WORKERS_RECLAIM_BATCH, 12))),
+ };
+}
+
+/**
+ * SOL a fresh wallet must hold to (1) stay rent-exempt as a system account,
+ * (2) pay its own 1-signature x402 settle fee at the worst-case priority the
+ * ring allows, and (3) pay the base fee of the sweep that empties it.
+ */
+export function walletSolLamports({
+ rentExemptLamports = RENT_EXEMPT_FALLBACK_LAMPORTS,
+ maxPayFeeLamports,
+ sweepFeeLamports = BASE_FEE_LAMPORTS,
+}) {
+ return Math.floor(rentExemptLamports) + Math.floor(maxPayFeeLamports) + Math.floor(sweepFeeLamports);
+}
+
+/**
+ * Which jobs this tick buys, in launch order. Deterministic in (tickSeq,
+ * cursor) so two instances with the same inputs plan the same thing. The forge
+ * job comes first on its tick because it is the slow one.
+ * @param {{ tickSeq:number, perTick:number, forgeEveryNTicks:number, dataSlugs:string[], cursor:number }} p
+ * @returns {Array<{ kind:'forge'|'data', slug:string }>}
+ */
+export function planTickJobs({ tickSeq, perTick, forgeEveryNTicks, dataSlugs, cursor }) {
+ const jobs = [];
+ if (perTick <= 0) return jobs;
+ const forgeTick = forgeEveryNTicks > 0 && tickSeq % forgeEveryNTicks === 0;
+ if (forgeTick) jobs.push({ kind: 'forge', slug: 'forge' });
+ const len = dataSlugs.length;
+ let i = 0;
+ while (jobs.length < perTick && len > 0) {
+ const idx = (((cursor + i) % len) + len) % len;
+ jobs.push({ kind: 'data', slug: dataSlugs[idx] });
+ i += 1;
+ }
+ return jobs;
+}
+
+/**
+ * Trim a job list to the USDC still allowed today. Jobs are kept in order until
+ * the next one would cross the cap; a $0 job never blocks.
+ */
+export function fitJobsToBudget({ jobs, priceOf, dailySpentAtomic, dailyCapAtomic }) {
+ let remaining = Math.max(0, dailyCapAtomic - dailySpentAtomic);
+ const kept = [];
+ const dropped = [];
+ for (const job of jobs) {
+ const price = Math.max(0, Math.floor(priceOf(job)));
+ if (price <= remaining) {
+ kept.push(job);
+ remaining -= price;
+ } else {
+ dropped.push(job);
+ }
+ }
+ return { kept, dropped, remainingAtomic: remaining };
+}
+
+/**
+ * What one funding transaction must move for a batch of jobs.
+ * solLamports = per-wallet SOL + one ATA rent per wallet (paid by the SOL
+ * funder, returned to it at close) + the funding tx's own fee
+ * usdcAtomic = the sum of the job prices
+ */
+export function fundingRequirement({ jobs, priceOf, solPerWalletLamports, ataRentLamports = ATA_RENT_LAMPORTS, txFeeLamports = BASE_FEE_LAMPORTS }) {
+ const n = jobs.length;
+ const usdcAtomic = jobs.reduce((s, j) => s + Math.max(0, Math.floor(priceOf(j))), 0);
+ const solLamports = n * (Math.floor(solPerWalletLamports) + Math.floor(ataRentLamports)) + (n > 0 ? txFeeLamports : 0);
+ return { wallets: n, solLamports, usdcAtomic };
+}
+
+/**
+ * Can the SOL funder cover `needLamports` while keeping `floorLamports` (the
+ * facilitator's sponsor floor) untouched? Below the floor every sponsored
+ * settle on the platform is refused, so this lane never eats into it.
+ */
+export function funderHeadroom({ balanceLamports, floorLamports, needLamports }) {
+ const spendable = Math.max(0, Math.floor(balanceLamports) - Math.floor(floorLamports));
+ const ok = spendable >= needLamports;
+ return { ok, spendable, shortfall: ok ? 0 : needLamports - spendable };
+}
+
+/** Exact lamports a wallet can send in its own 1-signature sweep and end at zero. */
+export function sweepAmountLamports({ balanceLamports, feeLamports = BASE_FEE_LAMPORTS }) {
+ return Math.max(0, Math.floor(balanceLamports) - Math.floor(feeLamports));
+}
+
+/**
+ * Decide what a reclaim pass does with a wallet that is not terminal.
+ * 'sweep' : try to empty and close it now
+ * 'wait' : it was touched recently; a live tick still owns it
+ * 'stranded' : sweeps keep failing; stop retrying and alert
+ */
+export function classifyReclaim({ state, updatedAtMs, attempts, nowMs, reclaimAfterS, maxSweepAttempts }) {
+ if (['closed', 'fund_failed', 'stranded', 'minted'].includes(state)) return 'skip';
+ if (attempts >= maxSweepAttempts) return 'stranded';
+ if (nowMs - updatedAtMs < reclaimAfterS * 1000) return 'wait';
+ return 'sweep';
+}
+
+/** Payload kept for the data desk: bounded arrays, bounded bytes, never a throw. */
+export function trimPayload(payload, { maxItems = 40, maxBytes = 60_000 } = {}) {
+ if (payload == null || typeof payload !== 'object') return { value: payload };
+ const clip = (v, depth) => {
+ if (Array.isArray(v)) return v.slice(0, maxItems).map((x) => (depth < 2 ? clip(x, depth + 1) : x));
+ if (v && typeof v === 'object' && depth < 2) {
+ const out = {};
+ for (const [k, x] of Object.entries(v)) out[k] = clip(x, depth + 1);
+ return out;
+ }
+ return v;
+ };
+ let trimmed = clip(payload, 0);
+ let text = JSON.stringify(trimmed);
+ if (text.length > maxBytes) {
+ trimmed = clip(payload, 0);
+ for (const k of Object.keys(trimmed)) {
+ if (Array.isArray(trimmed[k])) trimmed[k] = trimmed[k].slice(0, 10);
+ }
+ text = JSON.stringify(trimmed);
+ if (text.length > maxBytes) {
+ trimmed = { truncated: true, keys: Object.keys(payload).slice(0, 24) };
+ }
+ }
+ return trimmed;
+}
diff --git a/api/_lib/x402/fresh-workers/run.js b/api/_lib/x402/fresh-workers/run.js
new file mode 100644
index 000000000..0b5d20ff9
--- /dev/null
+++ b/api/_lib/x402/fresh-workers/run.js
@@ -0,0 +1,400 @@
+// api/_lib/x402/fresh-workers/run.js
+//
+// One tick of the fresh-wallet workers lane. Every minute:
+//
+// 1. Reclaim: any wallet a previous tick left mid-flight (funded but unpaid,
+// paid but unswept, sweep failed) is emptied and closed, or declared
+// stranded and alerted after too many attempts.
+// 2. Plan: which jobs this tick buys (a Forge generation every N ticks, the
+// rest datasets, in rotation), trimmed to the daily USDC cap.
+// 3. Afford: the SOL funder must cover every wallet's SOL plus its ATA rent
+// without dipping under the facilitator's sponsor floor, and the treasury
+// must hold the USDC. Otherwise the tick skips with a named reason.
+// 4. Mint + fund: brand-new keypairs, encrypted at rest, funded in ONE
+// transaction (SOL from the funder, ATA created by the funder, USDC from
+// the treasury).
+// 5. Pay: each wallet self-pays its job over the shared payX402 client (one
+// signature, its own fee), the response lands in the library or the data
+// desk, and the call is recorded to x402_autonomous_log.
+// 6. Sweep: each wallet sends leftover USDC to the treasury, closes its token
+// account (rent back to the funder) and sends every remaining lamport but
+// the base fee to the funder. It ends at zero and is never used again.
+//
+// The tick is stateful by design: every stage writes the wallet's state first,
+// so a timeout, a crash or a lost RPC mid-flight leaves nothing stranded; the
+// next tick's reclaim pass finishes the job. Real on-chain payments only.
+
+import { randomUUID } from 'node:crypto';
+import { Keypair, PublicKey } from '@solana/web3.js';
+
+import { sql as defaultSql } from '../../db.js';
+import { env } from '../../env.js';
+import { logger } from '../../usage.js';
+import { sendOpsAlert } from '../../alerts.js';
+import { solanaConnection } from '../../solana/connection.js';
+import { mintDecimals } from '../../solana/read-guards.js';
+import { payX402, bootstrapSolanaContext, decodeSeedSecret, USDC_MINT } from '../pay.js';
+import { ringAllowedAddresses } from '../ring-allowlist.js';
+import { SPONSOR_SOL_FLOOR_LAMPORTS } from '../self-facilitator.js';
+import { resolveQueuedJobs } from '../pipelines/forge-content.js';
+import { ensureVolumeSchema, upsertVolumeMetric } from '../pipelines/volume-shared.js';
+import {
+ ATA_RENT_LAMPORTS,
+ freshWorkersConfig,
+ planTickJobs,
+ fitJobsToBudget,
+ fundingRequirement,
+ funderHeadroom,
+ walletSolLamports,
+ classifyReclaim,
+} from './plan.js';
+import { DATA_JOB_SLUGS, resolveJob, storeJobResult } from './jobs.js';
+import {
+ ensureFreshSchema, mintWallet, recoverKeypair,
+ markFunded, markFundFailed, markPaid, markPayFailed, markClosed, markSweepFailed, markStranded,
+ claimReclaimable, dailySpentAtomic,
+} from './wallets.js';
+import {
+ rentExemptLamports, fundWallets, sweepWallet, readSolLamports, readUsdc, confirmSignature, usdcAtaOf,
+} from './chain.js';
+
+const log = logger('x402-fresh-workers');
+
+export const PIPELINE = 'fresh-workers';
+const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const TICK_SEQ_KEY = 'x402:fresh:tick:seq';
+const DATA_CURSOR_KEY = 'x402:fresh:data:cursor';
+// The pay stage keeps this much of the tick for the sweeps that follow it.
+const SWEEP_RESERVE_MS = 12_000;
+// How long a sweep waits for the wallet's own payment to confirm before it
+// reads balances. A settle the facilitator broadcast lands in a few seconds.
+const PAY_CONFIRM_MS = 15_000;
+
+let _memTickSeq = 0;
+let _memCursor = 0;
+
+function loadFunder(secret, label) {
+ const bytes = decodeSeedSecret(secret);
+ if (!bytes) throw new Error(`${label}_undecodable`);
+ return Keypair.fromSecretKey(bytes);
+}
+
+async function nextTickSeq(redis) {
+ if (redis) {
+ try { return Number(await redis.incr(TICK_SEQ_KEY)); } catch { /* fall through */ }
+ }
+ return (_memTickSeq += 1);
+}
+
+async function reserveCursor(redis, count) {
+ if (count <= 0) return _memCursor;
+ if (redis) {
+ try { return Number(await redis.incrby(DATA_CURSOR_KEY, count)) - count; } catch { /* fall through */ }
+ }
+ const start = _memCursor;
+ _memCursor += count;
+ return start;
+}
+
+const skip = (reason, extra = {}) => ({ ok: true, skipped: true, reason, ...extra });
+
+async function recordCall(sql, { runId, wallet, job, endpointUrl, result, durationMs, sink }) {
+ try {
+ await sql`
+ INSERT INTO x402_autonomous_log
+ (run_id, endpoint_type, service_name, endpoint_url,
+ network, amount_atomic, asset, tx_signature,
+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)
+ VALUES
+ (${runId}, ${'self'}, ${`Fresh: ${job.title}`}, ${endpointUrl},
+ ${'solana:mainnet'}, ${result.paid ? result.amountAtomic : 0}, ${ASSET}, ${result.txSig || null},
+ ${JSON.stringify({ status: result.status, paid: result.paid === true, skipped: result.skipped === true })},
+ ${JSON.stringify({ payer: wallet.pubkey, wallet_id: wallet.id, job_kind: job.kind, slug: job.slug, fresh_wallet: true, ...(sink || {}) })},
+ ${durationMs || 0}, ${result.success === true}, ${result.errorMsg || null}, ${PIPELINE})`;
+ } catch (err) {
+ log.warn('fresh_call_log_insert_failed', { message: err?.message });
+ }
+ try {
+ await upsertVolumeMetric(sql, { key: job.slug, name: job.title, path: job.endpointPath }, {
+ amountAtomic: result.paid ? result.amountAtomic : 0, txSig: result.txSig, success: result.success === true,
+ status: result.status, errorMsg: result.errorMsg, runId,
+ });
+ } catch (err) {
+ log.warn('fresh_volume_metric_failed', { message: err?.message });
+ }
+}
+
+async function recordLedger(sql, { kind, from, to, amountAtomic, txSig, runId }) {
+ try {
+ await sql`INSERT INTO x402_ring_ledger (kind, from_wallet, to_wallet, mint, amount_atomic, tx_sig, run_id)
+ VALUES (${kind}, ${from}, ${to}, ${ASSET}, ${Number(amountAtomic || 0)}, ${txSig || null}, ${runId})`;
+ } catch (err) {
+ log.warn('fresh_ledger_write_failed', { kind, message: err?.message });
+ }
+}
+
+/**
+ * Empty and close one wallet, booking the outcome. Shared by the sweep stage
+ * and the reclaim pass. Returns the state it left the row in.
+ */
+async function settleWallet({ sql, conn, wallet, keypair, funders, mint, decimals, runId, confirmMs }) {
+ const res = await sweepWallet({
+ conn, wallet: keypair, solFunder: funders.solFunder.publicKey, treasury: funders.treasury.publicKey,
+ mint, decimals, confirmMs,
+ });
+ if (!res.ok) {
+ await markSweepFailed(sql, wallet.id, res.err);
+ return { state: 'sweep_failed', error: res.err };
+ }
+ await markClosed(sql, wallet.id, {
+ sweepSig: res.signature, solLamports: res.solLamports, usdcAtomic: Number(res.usdcAtomic || 0n), rentLamports: res.rentLamports,
+ });
+ if (res.usdcAtomic && res.usdcAtomic > 0n) {
+ await recordLedger(sql, { kind: 'sweep', from: wallet.pubkey, to: funders.treasury.publicKey.toBase58(), amountAtomic: Number(res.usdcAtomic), txSig: res.signature, runId });
+ }
+ return { state: 'closed', signature: res.signature, solLamports: res.solLamports, rentLamports: res.rentLamports };
+}
+
+async function reclaimPass({ sql, conn, cfg, funders, mint, decimals, runId, timeLeft }) {
+ const out = { claimed: 0, closed: 0, failed: 0, stranded: 0, waiting: 0 };
+ let rows = [];
+ try {
+ rows = await claimReclaimable({ sql, reclaimAfterS: cfg.reclaimAfterS, limit: cfg.reclaimBatch });
+ } catch (err) {
+ log.warn('fresh_reclaim_claim_failed', { message: err?.message });
+ return out;
+ }
+ out.claimed = rows.length;
+ for (const row of rows) {
+ if (timeLeft() < SWEEP_RESERVE_MS) { out.waiting += 1; continue; }
+ // The claim query already applied the age window, so only the attempt
+ // ceiling is left to judge here.
+ const verdict = classifyReclaim({
+ state: row.state, updatedAtMs: 0, attempts: Number(row.attempts || 0), nowMs: Date.now(),
+ reclaimAfterS: 0, maxSweepAttempts: cfg.maxSweepAttempts,
+ });
+ if (verdict === 'stranded') {
+ await markStranded(sql, row.id, `sweep_attempts_exhausted:${row.attempts}`);
+ out.stranded += 1;
+ await sendOpsAlert(
+ 'x402 fresh worker wallet stranded',
+ `Wallet ${row.pubkey} (job ${row.job_kind}/${row.job_slug}) could not be swept after ${row.attempts} attempts. Its SOL and any USDC are still on chain under a key in x402_fresh_wallets; run the reclaim manually once the cause is fixed.`,
+ { signature: `fresh-workers:stranded:${row.pubkey}` },
+ ).catch(() => {});
+ continue;
+ }
+ let keypair;
+ try { keypair = await recoverKeypair(row.encrypted_secret); }
+ catch (err) { await markSweepFailed(sql, row.id, `key_recover_failed:${err?.message}`); out.failed += 1; continue; }
+ if (row.state === 'paid' && row.pay_sig) {
+ await confirmSignature(conn, row.pay_sig, Math.min(PAY_CONFIRM_MS, Math.max(2_000, timeLeft() - SWEEP_RESERVE_MS)));
+ }
+ const done = await settleWallet({
+ sql, conn, wallet: { id: row.id, pubkey: row.pubkey }, keypair, funders, mint, decimals, runId,
+ confirmMs: Math.min(30_000, Math.max(5_000, timeLeft() - 2_000)),
+ });
+ if (done.state === 'closed') out.closed += 1; else out.failed += 1;
+ }
+ return out;
+}
+
+/**
+ * Run one tick. Standalone callers (scripts/x402-fresh-workers-run.mjs) pass
+ * the same shape the cron does: { sql?, redis?, origin?, runId? }.
+ */
+export async function run(ctx = {}) {
+ const started = Date.now();
+ const sql = ctx.sql || defaultSql;
+ const redis = ctx.redis || null;
+ const origin = (ctx.origin || env.APP_ORIGIN || 'https://three.ws').replace(/\/+$/, '');
+ const runId = ctx.runId || randomUUID();
+ const cfg = freshWorkersConfig();
+ const deadline = started + cfg.tickBudgetMs;
+ const timeLeft = () => deadline - Date.now();
+
+ if (!cfg.enabled) return skip('X402_FRESH_WORKERS_ENABLED=false');
+ if (!USDC_MINT) return skip('usdc_mint_unset');
+ if (!process.env.WALLET_ENCRYPTION_KEY) return skip('wallet_encryption_key_unset');
+ const treasurySecret = process.env.X402_TREASURY_SECRET_BASE58;
+ const solFunderSecret = process.env.X402_FEE_PAYER_SECRET_BASE58 || treasurySecret;
+ if (!treasurySecret) return skip('treasury_secret_unset');
+
+ let funders;
+ try {
+ funders = { treasury: loadFunder(treasurySecret, 'treasury_secret'), solFunder: loadFunder(solFunderSecret, 'sol_funder_secret') };
+ } catch (err) {
+ return { ok: false, skipped: true, reason: err.message };
+ }
+ if (env.X402_PAY_TO_SOLANA && funders.treasury.publicKey.toBase58() !== env.X402_PAY_TO_SOLANA) {
+ return { ok: false, skipped: true, reason: 'treasury_pubkey_mismatch' };
+ }
+
+ await ensureFreshSchema(sql);
+ await ensureVolumeSchema(sql);
+
+ let allowed;
+ try { allowed = await ringAllowedAddresses({ sql }); } catch { allowed = new Set(); }
+ const treasuryB58 = funders.treasury.publicKey.toBase58();
+ const solFunderB58 = funders.solFunder.publicKey.toBase58();
+ if (!allowed.has(treasuryB58) || !allowed.has(solFunderB58)) {
+ return { ok: false, skipped: true, reason: 'funder_not_allowlisted' };
+ }
+
+ // One Solana context for the whole tick: the blockhash the payments sign
+ // against (refreshed inside payX402 as it ages) and the USDC decimals.
+ let solana;
+ try {
+ solana = await bootstrapSolanaContext({ buyer: funders.solFunder });
+ } catch (err) {
+ return skip('rpc_unavailable', { error: err?.message });
+ }
+ const conn = ctx.conn || solana.conn || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
+ const mint = new PublicKey(USDC_MINT);
+ const decimals = solana.mintInfo?.decimals ?? await mintDecimals(conn, mint);
+ const mintInfo = { decimals };
+
+ // ── 1. Reclaim whatever an earlier tick left behind ───────────────────────
+ const reclaim = await reclaimPass({ sql, conn, cfg, funders, mint, decimals, runId, timeLeft });
+ // Finished Forge jobs from earlier ticks (async generations) converge here
+ // too, so the library keeps filling even on a tick that buys nothing.
+ const resolvedProps = await resolveQueuedJobs(origin).catch(() => 0);
+
+ // ── 2. Plan this tick's jobs inside the daily cap ─────────────────────────
+ const tickSeq = await nextTickSeq(redis);
+ if (cfg.perTick === 0) return { ok: true, skipped: true, reason: 'per_tick_zero', reclaim, tick_seq: tickSeq };
+ const dataCount = Math.max(0, cfg.perTick - (tickSeq % cfg.forgeEveryNTicks === 0 ? 1 : 0));
+ const cursor = await reserveCursor(redis, dataCount);
+ const planned = planTickJobs({ tickSeq, perTick: cfg.perTick, forgeEveryNTicks: cfg.forgeEveryNTicks, dataSlugs: DATA_JOB_SLUGS, cursor });
+ const jobs = planned.map((p) => resolveJob(p, tickSeq));
+ const dailySpent = await dailySpentAtomic(sql);
+ const fit = fitJobsToBudget({ jobs, priceOf: (j) => j.priceAtomic, dailySpentAtomic: dailySpent, dailyCapAtomic: cfg.dailyCapAtomic });
+ if (fit.kept.length === 0) {
+ log.info('fresh_daily_cap_reached', { spent: dailySpent, cap: cfg.dailyCapAtomic });
+ return { ok: true, skipped: true, reason: 'daily_cap_reached', daily_spent_usdc: (dailySpent / 1e6).toFixed(4), reclaim, tick_seq: tickSeq };
+ }
+
+ // ── 3. Can the funders afford it without touching the sponsor floor? ──────
+ const rentExempt = await rentExemptLamports(conn);
+ const solPerWallet = walletSolLamports({ rentExemptLamports: rentExempt, maxPayFeeLamports: cfg.maxPayFeeLamports });
+ const need = fundingRequirement({ jobs: fit.kept, priceOf: (j) => j.priceAtomic, solPerWalletLamports: solPerWallet, ataRentLamports: ATA_RENT_LAMPORTS });
+ const [funderSol, treasuryUsdc] = await Promise.all([
+ readSolLamports(conn, funders.solFunder.publicKey),
+ readUsdc(conn, usdcAtaOf(funders.treasury.publicKey, mint)),
+ ]);
+ if (funderSol === null || treasuryUsdc === null) return skip('funder_balance_unreadable', { reclaim, tick_seq: tickSeq });
+ const headroom = funderHeadroom({ balanceLamports: funderSol, floorLamports: SPONSOR_SOL_FLOOR_LAMPORTS, needLamports: need.solLamports });
+ if (!headroom.ok) {
+ log.warn('fresh_funder_headroom', { balance: funderSol, floor: SPONSOR_SOL_FLOOR_LAMPORTS, need: need.solLamports, shortfall: headroom.shortfall });
+ await sendOpsAlert(
+ 'x402 fresh workers paused: SOL funder headroom',
+ `The fee wallet holds ${(funderSol / 1e9).toFixed(4)} SOL; funding ${need.wallets} fresh wallet(s) needs ${(need.solLamports / 1e9).toFixed(4)} SOL above the ${(SPONSOR_SOL_FLOOR_LAMPORTS / 1e9).toFixed(3)} SOL sponsor floor. Fund the economy master; the lane resumes on its own.`,
+ { signature: 'fresh-workers:funder_headroom' },
+ ).catch(() => {});
+ return skip('funder_headroom', { shortfall_lamports: headroom.shortfall, reclaim, tick_seq: tickSeq });
+ }
+ if (treasuryUsdc.atomic < BigInt(need.usdcAtomic)) {
+ return skip('treasury_usdc_short', { have: String(treasuryUsdc.atomic), need: need.usdcAtomic, reclaim, tick_seq: tickSeq });
+ }
+
+ // ── 4. Mint + fund ─────────────────────────────────────────────────────────
+ const wallets = [];
+ for (const job of fit.kept) {
+ try {
+ wallets.push(await mintWallet({ sql, job, mint, runId }));
+ } catch (err) {
+ log.warn('fresh_mint_failed', { message: err?.message });
+ }
+ }
+ if (wallets.length === 0) return { ok: false, skipped: true, reason: 'mint_failed', reclaim, tick_seq: tickSeq };
+
+ const fund = await fundWallets({
+ conn, solFunder: funders.solFunder, treasury: funders.treasury, mint, decimals,
+ targets: wallets.map((w) => ({ pubkey: w.keypair.publicKey, ata: new PublicKey(w.ata), solLamports: solPerWallet, usdcAtomic: BigInt(w.job.priceAtomic) })),
+ confirmMs: Math.min(30_000, Math.max(8_000, timeLeft() - 25_000)),
+ });
+ if (!fund.ok) {
+ // A funding tx that did not confirm in time may still land. The rows stay
+ // reclaimable: after the window the reclaim pass reads their balances and
+ // sweeps whatever arrived, so a late landing never strands funds.
+ await markFundFailed(sql, wallets.map((w) => w.id), `fund_failed:${fund.err}`);
+ log.warn('fresh_fund_failed', { wallets: wallets.length, err: fund.err, signature: fund.signature });
+ return { ok: false, reason: 'fund_failed', error: fund.err, signature: fund.signature, reclaim, tick_seq: tickSeq };
+ }
+ await markFunded(sql, wallets.map((w) => w.id), {
+ fundSig: fund.signature, solLamports: solPerWallet,
+ usdcAtomicById: new Map(wallets.map((w) => [w.id, w.job.priceAtomic])),
+ });
+ for (const w of wallets) {
+ await recordLedger(sql, { kind: 'fund', from: treasuryB58, to: w.pubkey, amountAtomic: w.job.priceAtomic, txSig: fund.signature, runId });
+ }
+
+ // ── 5. Pay: every fresh wallet buys its job, in parallel ───────────────────
+ const onAccept = (accept) => (allowed.has(accept.payTo) ? null : { abort: true, reason: 'payto_outside_ring' });
+ const payBudgetMs = Math.max(5_000, timeLeft() - SWEEP_RESERVE_MS);
+ const payOne = async (w) => {
+ const url = `${origin}${w.job.path}`;
+ const t0 = Date.now();
+ let result;
+ try {
+ result = await Promise.race([
+ payX402({ url, method: w.job.method, body: w.job.body, buyer: w.keypair, conn, blockhash: solana.blockhash, mintInfo, remainingCap: w.job.priceAtomic, selfPay: true, onAccept }),
+ new Promise((resolve) => setTimeout(() => resolve({ success: false, paid: false, skipped: false, amountAtomic: 0, txSig: null, status: 0, responseBody: null, errorMsg: 'tick_deadline' }), payBudgetMs)),
+ ]);
+ } catch (err) {
+ result = { success: false, paid: false, skipped: false, amountAtomic: 0, txSig: null, status: 0, responseBody: null, errorMsg: err?.message || 'pay_failed' };
+ }
+ let sink = null;
+ if (result.success) {
+ sink = await storeJobResult({ sql, job: w.job, wallet: w, result, runId });
+ await markPaid(sql, w.id, { paySig: result.txSig, amountAtomic: result.paid ? result.amountAtomic : 0 });
+ } else {
+ await markPayFailed(sql, w.id, result.errorMsg || `http_${result.status}`);
+ }
+ await recordCall(sql, { runId, wallet: w, job: w.job, endpointUrl: url, result, durationMs: Date.now() - t0, sink });
+ return { wallet: w, result, sink };
+ };
+ const paid = await Promise.all(wallets.map(payOne));
+
+ // ── 6. Sweep: empty and close every wallet this tick funded ────────────────
+ const sweeps = await Promise.all(paid.map(async ({ wallet, result }) => {
+ if (timeLeft() < 3_000) return { wallet, state: 'deferred' };
+ if (result.txSig) await confirmSignature(conn, result.txSig, Math.min(PAY_CONFIRM_MS, Math.max(2_000, timeLeft() - 4_000)));
+ const done = await settleWallet({
+ sql, conn, wallet, keypair: wallet.keypair, funders, mint, decimals, runId,
+ confirmMs: Math.min(30_000, Math.max(4_000, timeLeft())),
+ });
+ return { wallet, ...done };
+ }));
+
+ const summary = {
+ ok: true,
+ run_id: runId,
+ tick_seq: tickSeq,
+ duration_ms: Date.now() - started,
+ reclaim,
+ resolved_props: resolvedProps,
+ wallets: wallets.length,
+ paid: paid.filter((p) => p.result.paid).length,
+ failed: paid.filter((p) => !p.result.success).length,
+ spent_usdc: (paid.reduce((s, p) => s + (p.result.paid ? p.result.amountAtomic : 0), 0) / 1e6).toFixed(4),
+ closed: sweeps.filter((s) => s.state === 'closed').length,
+ sweep_failed: sweeps.filter((s) => s.state === 'sweep_failed').length,
+ deferred: sweeps.filter((s) => s.state === 'deferred').length,
+ dropped_for_cap: fit.dropped.length,
+ fund_signature: fund.signature,
+ jobs: paid.map(({ wallet, result, sink }, i) => ({
+ payer: wallet.pubkey,
+ kind: wallet.job.kind,
+ slug: wallet.job.slug,
+ paid: result.paid === true,
+ amount_usdc: result.paid ? (result.amountAtomic / 1e6).toFixed(4) : '0',
+ tx: result.txSig || null,
+ error: result.errorMsg || null,
+ stored: sink?.stored ?? null,
+ state: sweeps[i]?.state || null,
+ sweep_tx: sweeps[i]?.signature || null,
+ })),
+ };
+ log.info('fresh_tick_complete', { run_id: runId, tick_seq: tickSeq, wallets: summary.wallets, paid: summary.paid, closed: summary.closed, spent_usdc: summary.spent_usdc, duration_ms: summary.duration_ms });
+ return summary;
+}
diff --git a/api/_lib/x402/fresh-workers/wallets.js b/api/_lib/x402/fresh-workers/wallets.js
new file mode 100644
index 000000000..ca812f327
--- /dev/null
+++ b/api/_lib/x402/fresh-workers/wallets.js
@@ -0,0 +1,210 @@
+// api/_lib/x402/fresh-workers/wallets.js
+//
+// The x402_fresh_wallets store: mint a brand-new keypair with its secret
+// encrypted at rest, walk it through its states, hand stranded work to the
+// next tick, and answer the public stats the /data-desk page shows.
+//
+// Every state change bumps updated_at, which is also the reclaim lock: a
+// reclaim pass only claims rows nobody has touched for the configured window,
+// so two instances never sweep the same wallet at once.
+
+import { Keypair, PublicKey } from '@solana/web3.js';
+
+import { encryptSecret, decryptSecret } from '../../secret-box.js';
+import { sql as defaultSql } from '../../db.js';
+import { usdcAtaOf } from './chain.js';
+
+let _schemaReady = false;
+/** Idempotent DDL guard mirroring the migration, so a first tick before the migration lands still works. */
+export async function ensureFreshSchema(sql = defaultSql) {
+ if (_schemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS x402_fresh_wallets (
+ id bigserial PRIMARY KEY,
+ pubkey text NOT NULL UNIQUE,
+ usdc_ata text NOT NULL,
+ encrypted_secret text NOT NULL,
+ state text NOT NULL DEFAULT 'minted',
+ job_kind text NOT NULL,
+ job_slug text NOT NULL,
+ job_title text,
+ sol_funded_lamports bigint NOT NULL DEFAULT 0,
+ usdc_funded_atomic bigint NOT NULL DEFAULT 0,
+ fund_sig text,
+ pay_sig text,
+ amount_atomic bigint NOT NULL DEFAULT 0,
+ sweep_sig text,
+ sol_reclaimed_lamports bigint NOT NULL DEFAULT 0,
+ usdc_returned_atomic bigint NOT NULL DEFAULT 0,
+ rent_reclaimed_lamports bigint NOT NULL DEFAULT 0,
+ attempts int NOT NULL DEFAULT 0,
+ error text,
+ run_id uuid,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ funded_at timestamptz,
+ paid_at timestamptz,
+ closed_at timestamptz
+ )`;
+ await sql`CREATE INDEX IF NOT EXISTS x402_fresh_wallets_state_updated ON x402_fresh_wallets (state, updated_at)`;
+ await sql`CREATE INDEX IF NOT EXISTS x402_fresh_wallets_created ON x402_fresh_wallets (created_at DESC)`;
+ _schemaReady = true;
+}
+
+function decodeKeypair(secretB64) {
+ const raw = Buffer.from(secretB64, 'base64');
+ if (raw.length !== 64) throw new Error(`fresh wallet key decode: expected 64 bytes, got ${raw.length}`);
+ return Keypair.fromSecretKey(Uint8Array.from(raw));
+}
+
+/**
+ * Mint one never-used wallet for a job and record it as 'minted'. The secret is
+ * encrypted before it is written and the plaintext keypair lives only in the
+ * returned object for the tick that uses it.
+ */
+export async function mintWallet({ sql = defaultSql, job, mint, runId }) {
+ const keypair = Keypair.generate();
+ const pubkey = keypair.publicKey.toBase58();
+ const ata = usdcAtaOf(keypair.publicKey, mint).toBase58();
+ const encrypted = await encryptSecret(Buffer.from(keypair.secretKey).toString('base64'));
+ const rows = await sql`
+ INSERT INTO x402_fresh_wallets (pubkey, usdc_ata, encrypted_secret, state, job_kind, job_slug, job_title, run_id)
+ VALUES (${pubkey}, ${ata}, ${encrypted}, 'minted', ${job.kind}, ${job.slug}, ${job.title}, ${runId})
+ RETURNING id`;
+ return { id: rows[0].id, pubkey, ata, keypair, job };
+}
+
+export async function recoverKeypair(encryptedSecret) {
+ return decodeKeypair(await decryptSecret(encryptedSecret));
+}
+
+const clip = (s) => (s == null ? null : String(s).slice(0, 400));
+
+export async function markFunded(sql, ids, { fundSig, solLamports, usdcAtomicById }) {
+ for (const id of ids) {
+ await sql`
+ UPDATE x402_fresh_wallets
+ SET state = 'funded', fund_sig = ${fundSig}, sol_funded_lamports = ${solLamports},
+ usdc_funded_atomic = ${Number(usdcAtomicById.get(id) ?? 0)},
+ funded_at = now(), updated_at = now()
+ WHERE id = ${id}`;
+ }
+}
+
+export async function markFundFailed(sql, ids, error) {
+ for (const id of ids) {
+ await sql`UPDATE x402_fresh_wallets SET state = 'fund_failed', error = ${clip(error)}, updated_at = now() WHERE id = ${id}`;
+ }
+}
+
+export async function markPaid(sql, id, { paySig, amountAtomic }) {
+ await sql`
+ UPDATE x402_fresh_wallets
+ SET state = 'paid', pay_sig = ${paySig || null}, amount_atomic = ${Number(amountAtomic || 0)},
+ paid_at = now(), updated_at = now(), error = NULL
+ WHERE id = ${id}`;
+}
+
+export async function markPayFailed(sql, id, error) {
+ await sql`UPDATE x402_fresh_wallets SET state = 'pay_failed', error = ${clip(error)}, updated_at = now() WHERE id = ${id}`;
+}
+
+export async function markClosed(sql, id, { sweepSig, solLamports, usdcAtomic, rentLamports }) {
+ await sql`
+ UPDATE x402_fresh_wallets
+ SET state = 'closed', sweep_sig = ${sweepSig || null},
+ sol_reclaimed_lamports = ${Number(solLamports || 0)},
+ usdc_returned_atomic = ${Number(usdcAtomic || 0)},
+ rent_reclaimed_lamports = ${Number(rentLamports || 0)},
+ closed_at = now(), updated_at = now(), error = NULL
+ WHERE id = ${id}`;
+}
+
+export async function markSweepFailed(sql, id, error) {
+ await sql`UPDATE x402_fresh_wallets SET state = 'sweep_failed', error = ${clip(error)}, updated_at = now() WHERE id = ${id}`;
+}
+
+export async function markStranded(sql, id, error) {
+ await sql`UPDATE x402_fresh_wallets SET state = 'stranded', error = ${clip(error)}, updated_at = now() WHERE id = ${id}`;
+}
+
+/**
+ * Claim wallets a previous tick left mid-flight: funded but never paid, paid
+ * but never swept, or whose sweep failed. The claim bumps attempts and
+ * updated_at in the same statement, so a concurrent instance sees them as
+ * freshly touched and leaves them alone.
+ */
+export async function claimReclaimable({ sql = defaultSql, reclaimAfterS, limit }) {
+ return sql`
+ UPDATE x402_fresh_wallets
+ SET attempts = attempts + 1, updated_at = now()
+ WHERE id IN (
+ SELECT id FROM x402_fresh_wallets
+ WHERE state IN ('funded', 'paid', 'pay_failed', 'sweep_failed')
+ AND updated_at < now() - make_interval(secs => ${reclaimAfterS})
+ ORDER BY updated_at ASC
+ LIMIT ${limit}
+ FOR UPDATE SKIP LOCKED
+ )
+ RETURNING id, pubkey, usdc_ata, encrypted_secret, state, attempts, pay_sig, job_kind, job_slug`;
+}
+
+/** USDC the lane has spent so far this UTC day, from the shared call log. */
+export async function dailySpentAtomic(sql = defaultSql) {
+ const rows = await sql`
+ SELECT COALESCE(SUM(amount_atomic), 0)::bigint AS spent
+ FROM x402_autonomous_log
+ WHERE pipeline = 'fresh-workers' AND ts >= date_trunc('day', now())`;
+ return Number(rows[0]?.spent || 0);
+}
+
+/** Public, key-free lane statistics for the last 24 hours and all time. */
+export async function laneStats(sql = defaultSql) {
+ const [day] = await sql`
+ SELECT count(*)::int AS minted,
+ count(*) FILTER (WHERE state = 'closed')::int AS closed,
+ count(*) FILTER (WHERE state IN ('paid', 'closed') AND pay_sig IS NOT NULL)::int AS paid,
+ count(*) FILTER (WHERE job_kind = 'forge' AND pay_sig IS NOT NULL)::int AS forge_jobs,
+ count(*) FILTER (WHERE job_kind = 'data' AND pay_sig IS NOT NULL)::int AS data_jobs,
+ count(*) FILTER (WHERE state IN ('funded', 'paid', 'pay_failed', 'sweep_failed'))::int AS in_flight,
+ count(*) FILTER (WHERE state = 'stranded')::int AS stranded,
+ coalesce(sum(amount_atomic), 0)::bigint AS spent_atomic,
+ coalesce(sum(sol_funded_lamports) FILTER (WHERE state = 'closed'), 0)::bigint AS sol_out,
+ coalesce(sum(sol_reclaimed_lamports) FILTER (WHERE state = 'closed'), 0)::bigint AS sol_back,
+ coalesce(sum(rent_reclaimed_lamports), 0)::bigint AS rent_back,
+ max(closed_at) AS last_closed_at
+ FROM x402_fresh_wallets
+ WHERE created_at > now() - interval '24 hours'`;
+ const [all] = await sql`
+ SELECT count(*)::int AS minted,
+ count(*) FILTER (WHERE state = 'closed')::int AS closed,
+ count(*) FILTER (WHERE pay_sig IS NOT NULL)::int AS paid,
+ coalesce(sum(amount_atomic), 0)::bigint AS spent_atomic
+ FROM x402_fresh_wallets`;
+ const toNum = (v) => Number(v || 0);
+ return {
+ last_24h: {
+ wallets_minted: day.minted,
+ wallets_closed: day.closed,
+ jobs_paid: day.paid,
+ forge_jobs: day.forge_jobs,
+ data_jobs: day.data_jobs,
+ in_flight: day.in_flight,
+ stranded: day.stranded,
+ spent_usdc: toNum(day.spent_atomic) / 1e6,
+ // SOL the closed wallets burned as network fees: what they were given
+ // minus what came back. Rent is excluded because it round-trips.
+ sol_fees: Math.max(0, toNum(day.sol_out) - toNum(day.sol_back)) / 1e9,
+ rent_recycled_sol: toNum(day.rent_back) / 1e9,
+ last_closed_at: day.last_closed_at,
+ },
+ all_time: {
+ wallets_minted: all.minted,
+ wallets_closed: all.closed,
+ jobs_paid: all.paid,
+ spent_usdc: toNum(all.spent_atomic) / 1e6,
+ },
+ };
+}
+
+export { PublicKey };
diff --git a/api/_lib/x402/pipelines/forge-content.js b/api/_lib/x402/pipelines/forge-content.js
index 009a0e767..d4279a566 100644
--- a/api/_lib/x402/pipelines/forge-content.js
+++ b/api/_lib/x402/pipelines/forge-content.js
@@ -95,6 +95,21 @@ export function nextForgeProp(now = Date.now()) {
return { category, prompt: `${subject}, ${style}, ${finish}, 3D prop` };
}
+// The same walk keyed by an arbitrary seed instead of the wall clock. The
+// fresh-wallet workers lane buys several props an hour, each from a different
+// brand-new wallet, and keys this on its tick counter so consecutive purchases
+// land on unrelated (category, subject, style) combinations rather than all
+// repeating the hour's prop.
+export function forgePropForSeed(seed) {
+ const n = Math.floor(Number(seed) || 0) >>> 0;
+ const category = CATEGORIES[mix(n, 11) % CATEGORIES.length];
+ const subjects = PROP_CATALOG[category];
+ const subject = subjects[mix(n, 12) % subjects.length];
+ const style = STYLES[mix(n, 13) % STYLES.length];
+ const finish = FINISHES[mix(n, 14) % FINISHES.length];
+ return { category, prompt: `${subject}, ${style}, ${finish}, 3D prop` };
+}
+
// ── Embedding ──────────────────────────────────────────────────────────────────
// Signed feature hashing (FNV-1a → bucket, top bit → sign). A real, deterministic
@@ -178,7 +193,7 @@ async function scoreDiversity(embedder, vector) {
// ── Schema ──────────────────────────────────────────────────────────────────────
-async function ensureSchema() {
+export async function ensureSchema() {
// forge_autonomous_props: the public asset-library + diversity table for
// autonomously-forged props. glb_url is the renderable asset; novelty +
// cluster_id are the embedding-clustering diversity metric.
@@ -222,7 +237,7 @@ async function ensureSchema() {
// public gallery converges on renderable assets without a dedicated cron.
// Never throws: a poll hiccup just retries on the next run.
const RESOLVE_BATCH = 5;
-async function resolveQueuedJobs(origin) {
+export async function resolveQueuedJobs(origin) {
let rows = [];
try {
rows = await sql`
@@ -280,7 +295,7 @@ async function recordCall(runId, { endpointUrl, amountAtomic, txSig, responseDat
// Embed, score diversity, and insert the generated prop. Returns the compact
// summary used as value_extracted. Never throws: a DB/embedding hiccup returns a
// summary carrying the error so the call is still recorded.
-async function persistProp({ runId, prompt, category, response, txSig = null, payer = null, amountAtomic = null }) {
+export async function persistProp({ runId, prompt, category, response, txSig = null, payer = null, amountAtomic = null }) {
const r = response && typeof response === 'object' ? response : {};
const tier = r.tier || 'draft';
const mode = r.mode || 'text_to_3d';
diff --git a/api/_lib/x402/ring-allowlist.js b/api/_lib/x402/ring-allowlist.js
index 6146891a4..c748326be 100644
--- a/api/_lib/x402/ring-allowlist.js
+++ b/api/_lib/x402/ring-allowlist.js
@@ -44,6 +44,7 @@ import { env } from '../env.js';
import { SOLANA_SIGNERS, resolveSignerPubkey, decodeSecretKey } from '../solana-signers.js';
import { sendOpsAlert } from '../alerts.js';
import { resolveSolanaFacilitator, selfFacilitatorEnabled } from './ring-config.js';
+import { freshWorkersConfig } from './fresh-workers/plan.js';
// ── Controlled-wallet set ─────────────────────────────────────────────────────
@@ -111,10 +112,24 @@ export async function ringAllowedAddresses(deps = {}) {
for (const pk of Object.values(roles)) if (pk) owners.add(pk);
// x402_ring_wallets registry (task 03 provisioning writes it).
+ const knownAtas = new Set();
try {
const sql = deps.sql || (await import('../db.js')).sql;
const rows = await sql`SELECT pubkey FROM x402_ring_wallets WHERE enabled = true`;
for (const r of rows) if (r?.pubkey) owners.add(r.pubkey);
+ // Fresh worker wallets (fresh-workers/): each one is funded by the master,
+ // pays once, and is emptied within minutes, so it never joins the registry.
+ // It still has to be a member for the window in which the leak scanner can
+ // meet its funding leg, or the master's transfer to it reads as a LEAK. The
+ // row already carries the wallet's USDC ATA, so nothing is re-derived here.
+ const hours = freshWorkersConfig().membershipWindowHours;
+ const fresh = await sql`
+ SELECT pubkey, usdc_ata FROM x402_fresh_wallets
+ WHERE created_at > now() - make_interval(hours => ${hours})`;
+ for (const r of fresh) {
+ if (r?.pubkey) owners.add(r.pubkey);
+ if (r?.usdc_ata) knownAtas.add(r.usdc_ata);
+ }
} catch { /* no DB / table absent → env-derived set stands */ }
// Every platform fee-paying signer is a controlled wallet.
@@ -137,6 +152,7 @@ export async function ringAllowedAddresses(deps = {}) {
const ata = await usdcAtaOf(owner);
if (ata) out.add(ata);
}
+ for (const ata of knownAtas) out.add(ata);
return out;
}
diff --git a/api/cron/economy-tick.js b/api/cron/economy-tick.js
index 23fc01da7..87a21d4a9 100644
--- a/api/cron/economy-tick.js
+++ b/api/cron/economy-tick.js
@@ -50,6 +50,8 @@ const TARGETS = [
{ label: 'ring-tick', path: '/api/cron/x402-ring-tick', method: 'GET' },
{ label: 'x402-seed', path: '/api/cron/x402-seed-cron', method: 'GET' },
{ label: 'x402-autonomous', path: '/api/cron/x402-autonomous-loop', method: 'GET' },
+ // Fresh-wallet workers: brand-new payer wallets buying real work every minute.
+ { label: 'fresh-workers', path: '/api/cron/x402-fresh-workers', method: 'GET' },
{ label: 'ring-leak-scan', path: '/api/cron/x402-ring-leak-scan', method: 'GET' },
{ label: 'wallets-leak-scan', path: '/api/cron/wallets-leak-scan', method: 'GET' },
{ label: 'distribute-payments', path: '/api/cron/run-distribute-payments', method: 'GET' },
diff --git a/api/cron/x402-fresh-workers.js b/api/cron/x402-fresh-workers.js
new file mode 100644
index 000000000..0dc43e7f2
--- /dev/null
+++ b/api/cron/x402-fresh-workers.js
@@ -0,0 +1,70 @@
+// GET/POST /api/cron/x402-fresh-workers
+//
+// Per-minute driver of the fresh-wallet workers lane: every tick mints a few
+// brand-new Solana wallets, funds each with exactly one job's worth of USDC
+// plus its own fees, has each pay a real three.ws x402 endpoint for useful
+// work (a 3D prop for the /forged library, or a dataset for /data-desk), then
+// empties and closes every wallet so nothing strands. Fired by the economy
+// heartbeat (economy-tick.js) like every other engine.
+//
+// Safety, in check order:
+// • X402_AUTONOMOUS_ENABLED=false (global) or X402_FRESH_WORKERS_ENABLED=false
+// (this lane) → clean skip.
+// • assertRingSpendInvariants(): external spend off, no charity split, the
+// facilitator resolves to self. Any violation no-ops the tick (fail closed).
+// • validateRingConfig(): an ERROR finding (settlement would not route
+// in-house) blocks the tick; warnings are logged.
+// • Inside run(): the SOL funder never dips under the sponsor floor, the
+// daily USDC cap holds, every payTo is checked against the controlled set
+// before a single signature, and every wallet's state is written before
+// money moves so the next tick can finish an interrupted one.
+//
+// Real on-chain payments only. Every job is a real generation or a real data
+// fetch; nothing is mocked.
+
+import { randomUUID } from 'node:crypto';
+
+import { json, method, wrapCron } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { getRedis } from '../_lib/redis.js';
+import { sql } from '../_lib/db.js';
+import { logger } from '../_lib/usage.js';
+import { validateRingConfig } from '../_lib/x402/ring-config.js';
+import { gateOnRingConfig } from '../_lib/x402/ring-tick-plan.js';
+import { assertRingSpendInvariants } from '../_lib/x402/ring-allowlist.js';
+import { freshWorkersConfig } from '../_lib/x402/fresh-workers/plan.js';
+import { run } from '../_lib/x402/fresh-workers/run.js';
+import { requireCron } from '../_lib/cron-auth.js';
+
+const log = logger('x402-fresh-workers-cron');
+
+const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ if (process.env.X402_AUTONOMOUS_ENABLED === 'false') {
+ return json(res, 200, { ok: true, skipped: true, reason: 'X402_AUTONOMOUS_ENABLED=false' });
+ }
+ if (!freshWorkersConfig().enabled) {
+ return json(res, 200, { ok: true, skipped: true, reason: 'X402_FRESH_WORKERS_ENABLED=false' });
+ }
+
+ const invariants = await assertRingSpendInvariants({ context: 'x402-fresh-workers' });
+ if (!invariants.ok) {
+ return json(res, 200, { ok: false, skipped: true, reason: 'ring_invariant_violation', violations: invariants.violations.map((v) => v.flag) });
+ }
+ const gate = gateOnRingConfig(validateRingConfig());
+ if (gate.blocked) {
+ log.warn('fresh_workers_config_blocked', { errors: gate.errors.map((e) => e.code || e.message) });
+ return json(res, 200, { ok: false, skipped: true, reason: 'ring_config_error', errors: gate.errors });
+ }
+ if (gate.warnings.length) log.info('fresh_workers_config_warnings', { warnings: gate.warnings.map((w) => w.code || w.message) });
+
+ const runId = randomUUID();
+ let redis = null;
+ try { redis = getRedis(); } catch { redis = null; }
+ const out = await run({ sql, redis, origin: ORIGIN(), runId });
+ return json(res, out.ok === false && !out.skipped ? 502 : 200, out);
+});
diff --git a/api/data-desk.js b/api/data-desk.js
new file mode 100644
index 000000000..240fd504d
--- /dev/null
+++ b/api/data-desk.js
@@ -0,0 +1,117 @@
+// GET /api/data-desk: the public feed behind the /data-desk page.
+//
+// Every dataset here was BOUGHT: a brand-new agent wallet, minted minutes
+// earlier by the fresh-wallet workers lane, paid a three.ws x402 market-data
+// or intel endpoint in real USDC on Solana, and the response was stored with
+// its receipt (the paying wallet, the price, the settlement signature). The
+// feed returns the newest purchase of every dataset, the most recent
+// purchases as a ledger, and the lane's own statistics. No synthetic rows: if
+// nothing has been bought yet the feed is honestly empty.
+//
+// Views:
+// GET /api/data-desk : latest row per dataset + recent purchases + stats
+// GET /api/data-desk?slug=market-gas: history for one dataset (newest first)
+// GET /api/data-desk?limit=50 : ledger page size (max 100)
+
+import { sql, isDbUnavailableError } from './_lib/db.js';
+import { cors, json, method, serverError, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { cacheGet, cacheSet } from './_lib/cache.js';
+import { explorerTxUrl } from './_lib/avatar-wallet.js';
+import { DATA_JOBS, DATA_JOB_SLUGS } from './_lib/x402/fresh-workers/jobs.js';
+import { laneStats } from './_lib/x402/fresh-workers/wallets.js';
+
+const FEED_TTL_S = 15;
+const DEFAULT_LIMIT = 30;
+const MAX_LIMIT = 100;
+const SLUGS = new Set(DATA_JOB_SLUGS);
+
+function shortAddr(a) {
+ if (!a || typeof a !== 'string') return null;
+ return a.length > 12 ? `${a.slice(0, 6)}…${a.slice(-4)}` : a;
+}
+
+function toItem(row, { withPayload }) {
+ const meta = DATA_JOBS.find((j) => j.slug === row.slug);
+ return {
+ id: Number(row.id),
+ ts: row.ts,
+ slug: row.slug,
+ title: row.title || meta?.title || row.slug,
+ blurb: meta?.blurb || null,
+ endpoint_path: row.endpoint_path,
+ price_usdc: row.amount_atomic != null ? Number(row.amount_atomic) / 1e6 : null,
+ payer: row.payer,
+ payer_short: shortAddr(row.payer),
+ tx_sig: row.tx_sig,
+ explorer_url: row.tx_sig ? explorerTxUrl(row.tx_sig) : null,
+ ...(withPayload ? { payload: row.payload } : {}),
+ };
+}
+
+export default async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://localhost');
+ const slug = url.searchParams.get('slug');
+ const limit = Math.min(MAX_LIMIT, Math.max(1, Number(url.searchParams.get('limit')) || DEFAULT_LIMIT));
+ if (slug && !SLUGS.has(slug)) {
+ return json(res, 400, { error: 'invalid_slug', error_description: `slug must be one of: ${DATA_JOB_SLUGS.join(', ')}` });
+ }
+
+ const cacheKey = `data-desk:${slug || 'all'}:${limit}`;
+ const cached = await cacheGet(cacheKey);
+ if (cached) return json(res, 200, cached, { 'cache-control': `public, max-age=${FEED_TTL_S}` });
+
+ try {
+ let payload;
+ if (slug) {
+ const rows = await sql`
+ SELECT id, ts, slug, title, endpoint_path, payload, payer, tx_sig, amount_atomic
+ FROM x402_data_desk WHERE slug = ${slug} ORDER BY ts DESC LIMIT ${limit}`;
+ payload = { slug, items: rows.map((r) => toItem(r, { withPayload: true })) };
+ } else {
+ const [latest, recent, stats] = await Promise.all([
+ sql`
+ SELECT DISTINCT ON (slug) id, ts, slug, title, endpoint_path, payload, payer, tx_sig, amount_atomic
+ FROM x402_data_desk ORDER BY slug, ts DESC`,
+ sql`
+ SELECT id, ts, slug, title, endpoint_path, payer, tx_sig, amount_atomic
+ FROM x402_data_desk ORDER BY ts DESC LIMIT ${limit}`,
+ laneStats(sql),
+ ]);
+ const order = new Map(DATA_JOB_SLUGS.map((s, i) => [s, i]));
+ const datasets = latest
+ .map((r) => toItem(r, { withPayload: true }))
+ .sort((a, b) => (order.get(a.slug) ?? 999) - (order.get(b.slug) ?? 999));
+ const [desk] = await sql`
+ SELECT count(*)::int AS purchases_24h, coalesce(sum(amount_atomic), 0)::bigint AS spent_atomic_24h,
+ count(distinct payer)::int AS payers_24h, max(ts) AS latest_ts
+ FROM x402_data_desk WHERE ts > now() - interval '24 hours'`;
+ payload = {
+ datasets,
+ recent: recent.map((r) => toItem(r, { withPayload: false })),
+ catalog: DATA_JOBS.map((j) => ({ slug: j.slug, title: j.title, blurb: j.blurb })),
+ stats: {
+ datasets_live: datasets.length,
+ purchases_24h: desk?.purchases_24h ?? 0,
+ payers_24h: desk?.payers_24h ?? 0,
+ spent_usdc_24h: Number(desk?.spent_atomic_24h ?? 0) / 1e6,
+ latest_ts: desk?.latest_ts ?? null,
+ lane: stats,
+ },
+ };
+ }
+ await cacheSet(cacheKey, payload, FEED_TTL_S);
+ return json(res, 200, payload, { 'cache-control': `public, max-age=${FEED_TTL_S}` });
+ } catch (err) {
+ if (isDbUnavailableError(err)) {
+ return json(res, 503, { error: 'db_unavailable', error_description: 'The data desk database is briefly unavailable. Retry shortly.' }, { 'cache-control': 'no-store', 'retry-after': '5' });
+ }
+ return serverError(res, 500, 'data_desk_feed_error', err);
+ }
+}
diff --git a/api/forged.js b/api/forged.js
index 0db561bbd..70c58a9a9 100644
--- a/api/forged.js
+++ b/api/forged.js
@@ -21,8 +21,9 @@
// Response: { props: [...], stats: { total, done, queued, spent_usdc,
// categories: {...}, latest_ts } }
// Each prop: { id, ts, prompt, category, tier, status, glb_url, novelty,
-// cluster_id, price_usdc, payer, payer_short, tx_sig, explorer_url,
-// viewer_url }
+// cluster_id, price_usdc, payer, payer_short, payer_kind, tx_sig,
+// explorer_url, viewer_url }. payer_kind is 'fresh' when a
+// never-used wallet from the fresh-wallet workers lane bought it.
import { sql, isDbUnavailableError } from './_lib/db.js';
import { cors, json, method, serverError, rateLimited } from './_lib/http.js';
@@ -58,6 +59,7 @@ function toProp(row) {
price_usdc: priceUsdc,
payer: row.payer,
payer_short: shortAddr(row.payer),
+ payer_kind: row.payer_kind || 'agent',
tx_sig: row.tx_sig,
explorer_url: row.tx_sig ? explorerTxUrl(row.tx_sig) : null,
viewer_url: row.glb_url ? `/app?src=${encodeURIComponent(row.glb_url)}` : null,
@@ -93,12 +95,14 @@ export default async function handler(req, res) {
try {
const rows = await sql`
- SELECT id, ts, prompt, category, tier, status, glb_url, novelty,
- cluster_id, tx_sig, payer, amount_atomic
- FROM forge_autonomous_props
- WHERE (${includeAll} OR (status = 'done' AND glb_url IS NOT NULL))
- AND (${category || null}::text IS NULL OR category = ${category || null})
- ORDER BY ts DESC
+ SELECT p.id, p.ts, p.prompt, p.category, p.tier, p.status, p.glb_url, p.novelty,
+ p.cluster_id, p.tx_sig, p.payer, p.amount_atomic,
+ CASE WHEN f.pubkey IS NOT NULL THEN 'fresh' ELSE 'agent' END AS payer_kind
+ FROM forge_autonomous_props p
+ LEFT JOIN x402_fresh_wallets f ON f.pubkey = p.payer
+ WHERE (${includeAll} OR (p.status = 'done' AND p.glb_url IS NOT NULL))
+ AND (${category || null}::text IS NULL OR p.category = ${category || null})
+ ORDER BY p.ts DESC
LIMIT ${limit}
`;
const [stats] = await sql`
diff --git a/api/fresh-workers.js b/api/fresh-workers.js
new file mode 100644
index 000000000..14361f07e
--- /dev/null
+++ b/api/fresh-workers.js
@@ -0,0 +1,72 @@
+// GET /api/fresh-workers: public statistics for the fresh-wallet workers lane.
+//
+// How many never-used wallets were minted, paid and closed in the last day,
+// what they bought (3D props vs datasets), the USDC that recirculated, the SOL
+// actually burned as network fees, the rent that round-tripped, and the most
+// recent wallets with their funding, payment and sweep signatures. Public and
+// key-free by design: the whole point of the lane is that every purchase is
+// verifiable on chain.
+
+import { sql, isDbUnavailableError } from './_lib/db.js';
+import { cors, json, method, serverError, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { cacheGet, cacheSet } from './_lib/cache.js';
+import { explorerTxUrl } from './_lib/avatar-wallet.js';
+import { laneStats } from './_lib/x402/fresh-workers/wallets.js';
+import { freshWorkersConfig } from './_lib/x402/fresh-workers/plan.js';
+
+const TTL_S = 15;
+const DEFAULT_LIMIT = 20;
+const MAX_LIMIT = 100;
+
+export default async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://localhost');
+ const limit = Math.min(MAX_LIMIT, Math.max(1, Number(url.searchParams.get('limit')) || DEFAULT_LIMIT));
+ const cacheKey = `fresh-workers:${limit}`;
+ const cached = await cacheGet(cacheKey);
+ if (cached) return json(res, 200, cached, { 'cache-control': `public, max-age=${TTL_S}` });
+
+ try {
+ const [stats, rows] = await Promise.all([
+ laneStats(sql),
+ sql`
+ SELECT id, pubkey, state, job_kind, job_slug, job_title, amount_atomic, fund_sig, pay_sig, sweep_sig,
+ sol_funded_lamports, sol_reclaimed_lamports, rent_reclaimed_lamports, error, created_at, closed_at
+ FROM x402_fresh_wallets ORDER BY created_at DESC LIMIT ${limit}`,
+ ]);
+ const cfg = freshWorkersConfig();
+ const payload = {
+ enabled: cfg.enabled,
+ cadence: { wallets_per_minute: cfg.perTick, forge_every_n_ticks: cfg.forgeEveryNTicks, daily_cap_usdc: cfg.dailyCapAtomic / 1e6 },
+ ...stats,
+ wallets: rows.map((r) => ({
+ pubkey: r.pubkey,
+ state: r.state,
+ job_kind: r.job_kind,
+ job_slug: r.job_slug,
+ job_title: r.job_title,
+ price_usdc: Number(r.amount_atomic || 0) / 1e6,
+ sol_fees: r.state === 'closed' ? Math.max(0, Number(r.sol_funded_lamports || 0) - Number(r.sol_reclaimed_lamports || 0)) / 1e9 : null,
+ rent_recycled_sol: Number(r.rent_reclaimed_lamports || 0) / 1e9,
+ fund_tx: r.fund_sig ? explorerTxUrl(r.fund_sig) : null,
+ pay_tx: r.pay_sig ? explorerTxUrl(r.pay_sig) : null,
+ sweep_tx: r.sweep_sig ? explorerTxUrl(r.sweep_sig) : null,
+ error: r.error,
+ created_at: r.created_at,
+ closed_at: r.closed_at,
+ })),
+ };
+ await cacheSet(cacheKey, payload, TTL_S);
+ return json(res, 200, payload, { 'cache-control': `public, max-age=${TTL_S}` });
+ } catch (err) {
+ if (isDbUnavailableError(err)) {
+ return json(res, 503, { error: 'db_unavailable', error_description: 'Briefly unavailable. Retry shortly.' }, { 'cache-control': 'no-store', 'retry-after': '5' });
+ }
+ return serverError(res, 500, 'fresh_workers_error', err);
+ }
+}
diff --git a/data/changelog.json b/data/changelog.json
index 1c0384104..7e56e012b 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$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-22",
+ "title": "Agents now buy real work from brand-new wallets, and you can watch it",
+ "summary": "The platform's agent economy used to prove the payment rail from a few long-lived wallets buying test calls. It now mints a fresh Solana wallet for every purchase: each one is created, given exactly one job's worth of USDC, pays a three.ws endpoint, and is emptied and closed within the minute. Every purchase does something useful. Some buy a 3D generation that lands in the Agent-Forged Gallery, where a new fresh wallet badge marks it. The rest buy live market data, which now has its own page, the Data Desk, showing each dataset with the wallet that paid, the price, and the Solana receipt. Both feeds are public JSON as well, and a new stats endpoint lists every wallet with its three transactions.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/data-desk"
+ },
{
"date": "2026-09-21",
"title": "Forge now asks what your model is for",
diff --git a/data/pages.json b/data/pages.json
index 22cf3ec1c..ae6aadd04 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -116,6 +116,15 @@
"added": "2026-07-21",
"showcase": true
},
+ {
+ "path": "/data-desk",
+ "title": "Data Desk",
+ "description": "Live market data bought minute by minute by brand-new agent wallets over x402. Every dataset carries its receipt: the wallet that paid, the price, and the Solana settlement transaction.",
+ "priority": 0.7,
+ "changefreq": "hourly",
+ "added": "2026-09-22",
+ "showcase": true
+ },
{
"path": "/forged",
"title": "Agent-Forged Gallery",
@@ -5339,6 +5348,14 @@
"priority": 0.6,
"changefreq": "monthly"
},
+ {
+ "path": "/docs/x402-fresh-workers",
+ "title": "Docs · Fresh-wallet workers",
+ "description": "How the platform mints a brand-new Solana wallet for every x402 purchase, what those wallets buy (3D props for the library, datasets for the data desk), how each wallet is emptied and closed so nothing strands, and where to watch it.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-09-22"
+ },
{
"path": "/docs/three-microbuy",
"title": "Docs · The $THREE micro-buy loop",
diff --git a/docs/api-reference.md b/docs/api-reference.md
index dcc5636f6..d518c7639 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -2039,6 +2039,85 @@ Every row is a real settled generation — no synthetic entries.
Written by the hourly autonomous forge-content pipeline
(`api/_lib/x402/pipelines/forge-content.js`); the paid generation endpoint it
buys from is documented under `POST /api/x402/forge` in the x402 section.
+Props also arrive from the fresh-wallet workers lane (below); those carry
+`"payer_kind": "fresh"`, meaning a wallet minted for that one purchase and
+closed right after paid for them. Every other prop reports `"agent"`.
+
+### Data desk feed: `GET /api/data-desk`
+
+```
+GET /api/data-desk → newest purchase of every dataset + recent ledger + lane stats
+GET /api/data-desk?slug=market-gas → one dataset's purchase history, newest first (payload included)
+GET /api/data-desk?limit=50 → ledger page size (default 30, max 100)
+```
+
+The public feed behind [/data-desk](https://three.ws/data-desk): datasets the
+fresh-wallet workers bought from the paid market-data and intel endpoints
+(`/api/x402/market-*`, `news-pulse`, `defi-radar`, `crypto-intel`, `three-intel`),
+each with the receipt that paid for it. Free, cached ~15s, rate-limited per
+IP. No synthetic rows.
+
+**Response**
+
+```json
+{
+ "datasets": [
+ {
+ "id": 918,
+ "ts": "2026-09-22T09:14:03.000Z",
+ "slug": "market-global",
+ "title": "Global market snapshot",
+ "blurb": "Total market cap, 24h volume, largest-coin dominance and the Fear & Greed index.",
+ "endpoint_path": "/api/x402/market-global",
+ "price_usdc": 0.001,
+ "payer": "<fresh wallet address>",
+ "payer_short": "9xQeWv…3kLm",
+ "tx_sig": "<solana settlement signature>",
+ "explorer_url": "https://solscan.io/tx/<sig>",
+ "payload": { "market": { "total_market_cap": 3920000000000 }, "fear_greed": { "value": 72, "label": "Greed" } }
+ }
+ ],
+ "recent": [ { "id": 918, "ts": "…", "slug": "market-global", "title": "…", "price_usdc": 0.001, "payer_short": "…", "explorer_url": "…" } ],
+ "catalog": [ { "slug": "market-global", "title": "Global market snapshot", "blurb": "…" } ],
+ "stats": {
+ "datasets_live": 18, "purchases_24h": 4102, "payers_24h": 4102, "spent_usdc_24h": 5.31,
+ "latest_ts": "2026-09-22T09:14:03.000Z",
+ "lane": { "last_24h": { "wallets_minted": 4320, "wallets_closed": 4311, "jobs_paid": 4290, "forge_jobs": 144, "data_jobs": 4146, "spent_usdc": 26.9, "sol_fees": 0.065, "rent_recycled_sol": 8.79 } }
+ }
+}
+```
+
+`payload` is the endpoint's response, with arrays trimmed to their first 40
+items so a row stays small; buy the endpoint directly for the full answer.
+
+### Fresh-wallet workers: `GET /api/fresh-workers`
+
+```
+GET /api/fresh-workers → lane stats + the 20 newest wallets
+GET /api/fresh-workers?limit=100 → up to 100 wallets
+```
+
+Public statistics for the lane that mints a brand-new Solana wallet for every
+purchase (docs: [x402-fresh-workers.md](./x402-fresh-workers.md)): wallets
+minted, paid and closed over the last 24 hours and all time, what they bought,
+the USDC that recirculated, the SOL actually burned as network fees, the ATA
+rent that round-tripped, and each recent wallet's funding, payment and sweep
+transactions on Solscan. Free, cached ~15s, rate-limited per IP.
+
+```json
+{
+ "enabled": true,
+ "cadence": { "wallets_per_minute": 3, "forge_every_n_ticks": 10, "daily_cap_usdc": 40 },
+ "last_24h": { "wallets_minted": 4320, "wallets_closed": 4311, "jobs_paid": 4290, "forge_jobs": 144, "data_jobs": 4146, "in_flight": 6, "stranded": 0, "spent_usdc": 26.9, "sol_fees": 0.065, "rent_recycled_sol": 8.79, "last_closed_at": "…" },
+ "all_time": { "wallets_minted": 4320, "wallets_closed": 4311, "jobs_paid": 4290, "spent_usdc": 26.9 },
+ "wallets": [
+ { "pubkey": "…", "state": "closed", "job_kind": "data", "job_slug": "market-gas", "job_title": "Gas oracle",
+ "price_usdc": 0.001, "sol_fees": 0.000015, "rent_recycled_sol": 0.00203928,
+ "fund_tx": "https://solscan.io/tx/…", "pay_tx": "https://solscan.io/tx/…", "sweep_tx": "https://solscan.io/tx/…",
+ "error": null, "created_at": "…", "closed_at": "…" }
+ ]
+}
+```
---
diff --git a/docs/start-here.md b/docs/start-here.md
index 124cc7d44..b9f3079c5 100644
--- a/docs/start-here.md
+++ b/docs/start-here.md
@@ -198,6 +198,7 @@ Deeper references that don't fit a track above but answer real questions:
- [Filming the product demo](./product-demo.md): the narrated walkthrough of every feature on the live site, how the route is generated from the Feature Tour curriculum so a new page films itself, and how to re-shoot a single chapter
- [three.ws on iOS](./ios-app.md): the App Store app, what it adds on top of the website (native share sheet, universal links, wallet deep links, offline shell), and how the web half of it ships on every deploy
- [Free LLM providers](./free-llm-providers.md): the failover chain of a dozen free AI providers behind every text completion, what each free tier gives, and how to add the next rung
+- [Fresh-wallet workers](./x402-fresh-workers.md): how the platform mints a brand-new Solana wallet for every x402 purchase, what those wallets buy (3D props for the library, datasets for the data desk), why nothing strands, and where to watch it
- [Tokens API on three.ws](./tokens-xyz.md): the Solana Foundation asset layer that tells us which mints are the same asset, why it sits second in the market-data cascade, and the one env var that turns it on
- [NVIDIA Inception membership](./nvidia-inception.md): what the platform already runs on NVIDIA silicon and what the program adds on top
- [NVIDIA visibility map](./nvidia-visibility-map.md): every NVIDIA surface worth being on (Showcase, GTC, NGC, ACE, the forums, social), the verified intake route for each, and the member benefits nobody has claimed yet
diff --git a/docs/x402-fresh-workers.md b/docs/x402-fresh-workers.md
new file mode 100644
index 000000000..d8d9d562d
--- /dev/null
+++ b/docs/x402-fresh-workers.md
@@ -0,0 +1,206 @@
+# Fresh-wallet workers: x402 volume from wallets that never existed before
+
+The ring economy proves the x402 rail continuously, but it does so from a
+handful of long-lived wallets, and most of what it buys is a canary: a $1
+settlement that returns a receipt and nothing else. The fresh-wallet workers
+lane changes both halves of that.
+
+- **Every payment comes from a brand-new wallet.** A keypair is generated for
+ one job, funded with exactly that job's price plus its own fees, pays once,
+ and is emptied and closed within the same minute. It never pays twice.
+- **Every payment buys real work.** A job is either a paid text-to-3D
+ generation that lands in the public [/forged](https://three.ws/forged)
+ library, or a paid dataset from the market-data storefront that lands on
+ the [/data-desk](https://three.ws/data-desk) page with its receipt.
+
+Both are the platform buying from itself, and both are labeled internal in
+every log row, the same way the ring is. What is new is that the money does
+something on the way round.
+
+Code: [api/_lib/x402/fresh-workers/](../api/_lib/x402/fresh-workers/) (four
+modules: `plan.js` pure planning, `chain.js` on-chain legs, `jobs.js` the job
+catalog and its sinks, `wallets.js` the lifecycle store, `run.js` the tick),
+driver [api/cron/x402-fresh-workers.js](../api/cron/x402-fresh-workers.js),
+fired every minute by the economy heartbeat
+([api/cron/economy-tick.js](../api/cron/economy-tick.js)).
+
+## One wallet's life
+
+```
+mint ──▶ fund ──▶ pay ──▶ sweep + close
+ keypair 1 tx 1 tx 1 tx (self-paid)
+ encrypted SOL+ATA USDC USDC leftover → treasury
+ at rest +USDC to the ATA rent → funder
+ treasury every lamport but 5,000 → funder
+```
+
+1. **Mint.** `Keypair.generate()`, secret-box encrypted with
+ `WALLET_ENCRYPTION_KEY` (the same scheme as custodial agent wallets and the
+ ring payer pool), stored in `x402_fresh_wallets` as `minted`. The row also
+ carries the wallet's USDC associated token account (ATA) address so nothing
+ downstream has to derive it.
+2. **Fund.** One transaction per tick funds every wallet the tick minted:
+ a system transfer of `rent-exempt minimum + worst-case pay fee + sweep fee`
+ lamports from the SOL funder (`X402_FEE_PAYER_SECRET_BASE58`, the sponsor
+ and economy master), an idempotent ATA create paid by the funder, and a
+ USDC transfer of the job's exact price from the treasury
+ (`X402_TREASURY_SECRET_BASE58`). Both funders sign; the treasury only as
+ token authority. State `funded`.
+3. **Pay.** The wallet calls its endpoint through the shared `payX402` client
+ with `selfPay: true`: one signature, its own fee, no sponsor co-sign. The
+ `onAccept` hook refuses any 402 whose `payTo` is outside the controlled
+ wallet set before a byte is signed. On success the response goes to its
+ sink and the wallet is `paid`; otherwise `pay_failed`. Either way the call
+ is a row in `x402_autonomous_log` tagged `pipeline='fresh-workers'`.
+4. **Sweep.** One self-paid transaction: leftover USDC to the treasury,
+ `closeAccount` on the ATA with the funder as rent destination, and a system
+ transfer of `balance - 5,000` lamports to the funder. The compute price is
+ zero so the fee is exactly the base fee and the wallet ends at exactly
+ zero. State `closed`.
+
+Net cost per job: three base fees, roughly 15,000 lamports. The ATA rent
+(2,039,280 lamports) leaves the funder in step 2 and comes back in step 4.
+The USDC leaves the treasury in step 2 and returns as the endpoint's revenue
+in step 3, so the treasury's USDC position is flat across a job.
+
+### Nothing strands
+
+Every stage writes the wallet's state before it moves money, so an
+interrupted tick leaves a row that says exactly where it stopped. The next
+tick's **reclaim pass** claims rows that are `funded`, `paid`, `pay_failed`
+or `sweep_failed` and untouched for `X402_FRESH_WORKERS_RECLAIM_AFTER_S`
+(default 90 s), waits for a pending payment to confirm, and sweeps them. The
+claim is a single `UPDATE ... FOR UPDATE SKIP LOCKED` that bumps `attempts`
+and `updated_at`, so two instances never sweep the same wallet at once.
+
+A wallet whose sweep keeps failing is marked `stranded` after
+`X402_FRESH_WORKERS_MAX_SWEEP_ATTEMPTS` (default 20) and raises one ops
+alert naming the pubkey. Its key is still in the table; a manual reclaim is
+`node scripts/x402-fresh-workers-run.mjs 1` once the cause (usually RPC) is
+fixed, because the reclaim pass runs at the top of every tick.
+
+`fund_failed` rows (the funding transaction never confirmed) are left alone
+by the reclaim pass on purpose: nothing was moved. If a slow funding
+transaction lands after the tick gave up, the row's balances are non-zero
+but its state is terminal, so the on-chain leak scanner still sees the
+wallet as internal (below) and the money sits under a key the platform
+holds; `npm run audit:wallet-flows` surfaces it and the run script's next
+tick sweeps any row you flip back to `funded`.
+
+## What gets bought
+
+Planned per tick by `planTickJobs()`: on every
+`X402_FRESH_WORKERS_FORGE_EVERY_N_TICKS`-th tick (default 10) the first job
+is a Forge generation; every other slot is the next dataset in rotation.
+
+| Kind | Endpoint | Price | Where it lands |
+| --- | --- | --- | --- |
+| forge | `POST /api/x402/forge`, standard tier, prompt from the same prop catalog the hourly forge pipeline walks, keyed by the tick counter so consecutive props differ | $0.15 | `forge_autonomous_props` via the forge pipeline's own `persistProp`, so the prop appears on [/forged](https://three.ws/forged) with the fresh wallet as payer and a **fresh wallet** badge on the card. Queued (async) generations are resolved to `done` by the same `resolveQueuedJobs` poll the lane runs at the top of every tick. |
+| data | the 18 datasets in `DATA_JOBS` (`jobs.js`): global snapshot, trending, gas, DeFi TVL, stablecoins, news pulse, fees, DEX volumes, mood, hacks, yields, DeFi radar, chains, crypto intel, market pulse, heatmap, $THREE intel, coin markets | $0.001 to $0.01 | `x402_data_desk`, one row per purchase with the trimmed payload, payer, price and settlement signature. `/api/data-desk` serves the newest row per dataset; [/data-desk](https://three.ws/data-desk) renders each with a slug-specific layout and its receipt. |
+
+Every data job's request contract (path, method, query, body, default price)
+is read from the ring catalog ([api/_lib/x402/ring-catalog.js](../api/_lib/x402/ring-catalog.js)),
+which is derived from the handlers themselves, so a purchase never pays for
+a request the endpoint would reject. `tests/x402-fresh-workers.test.js`
+fails if a listed dataset is missing from the catalog.
+
+At the defaults (3 wallets a minute, a prop every 10 ticks) a full day is
+about 4,300 fresh wallets, 144 new library props and 4,100 datasets, for
+roughly $26 of USDC that recirculates to the treasury and about 0.07 SOL of
+network fees. `X402_FRESH_WORKERS_DAILY_CAP_ATOMIC` (default $40) is the hard
+ceiling on the USDC side.
+
+## Safety
+
+The lane inherits every guard the ring has, in this order:
+
+- **Kill switches.** `X402_AUTONOMOUS_ENABLED=false` (global) or
+ `X402_FRESH_WORKERS_ENABLED=false` (this lane) skip cleanly.
+- **Spend invariants.** `assertRingSpendInvariants()`: external spending off,
+ no charity split, the facilitator resolves to self. A violation no-ops the
+ tick and raises the same CRITICAL alert the ring raises.
+- **Config gate.** `validateRingConfig()` errors block the tick.
+- **Funder headroom.** The SOL funder must cover every wallet's SOL plus one
+ ATA rent each plus the funding fee *above* `X402_SPONSOR_SOL_FLOOR_LAMPORTS`.
+ Below that the tick skips with `funder_headroom`, one throttled alert, and
+ resumes on its own once the master is funded. The treasury must hold the
+ tick's USDC or the tick skips with `treasury_usdc_short`.
+- **Recipient gate.** `payX402`'s `onAccept` hook refuses a `payTo` outside
+ `ringAllowedAddresses()` before signing.
+- **Time budget.** `X402_FRESH_WORKERS_TICK_BUDGET_MS` (default 50 s, under
+ the heartbeat's 60 s abort). Stages that would not finish in time are
+ deferred to the reclaim pass instead of racing the clock.
+
+### The controlled-wallet set
+
+The on-chain leak scanner classifies every debit from a ring wallet by its
+counterparty, and the master's funding transfer to a fresh wallet is exactly
+such a debit. Fresh wallets are therefore members of `ringAllowedAddresses()`
+for `X402_FRESH_WORKERS_MEMBERSHIP_HOURS` (default 36) after minting: the
+allowlist reads `pubkey` and `usdc_ata` straight from `x402_fresh_wallets`,
+so the set grows by a bounded window rather than forever, and no ATA is
+re-derived per call. Fresh wallets are deliberately **not** mirrored into
+`x402_ring_wallets`, so the scanner never enumerates thousands of dead
+wallets and treasury sweepback never sees them.
+
+Because a fresh wallet self-pays, the facilitator's wallet fee governor
+sees it as a governed wallet with the heartbeat budget, which is far above
+one fee, and the sponsor floor does not apply to it (the sponsor is not the
+fee payer of a self-paid settle).
+
+## Watching it
+
+- [/data-desk](https://three.ws/data-desk): the datasets, the ledger of
+ recent purchases, and the lane's 24 h numbers.
+- [/forged](https://three.ws/forged): props with the **fresh wallet** badge.
+- `GET /api/fresh-workers`: wallets minted, paid and closed (24 h and all
+ time), USDC recirculated, SOL actually burned as fees, rent recycled, and
+ the newest wallets with their fund, pay and sweep signatures on Solscan.
+- `GET /api/data-desk`: the feed behind the page; `?slug=<dataset>` for one
+ dataset's purchase history.
+- Logs: `fresh_tick_complete` per tick, `fresh_funder_headroom` when the
+ lane paused for SOL, `fresh_fund_failed` / `fresh_reclaim_claim_failed`
+ for chain and DB faults.
+- DB: `x402_fresh_wallets` (every wallet, every state), `x402_data_desk`
+ (every dataset bought), `x402_autonomous_log WHERE pipeline='fresh-workers'`
+ (every call), `x402_ring_ledger` rows of kind `fund` and `sweep` for the
+ USDC legs.
+
+## Running it
+
+```bash
+# What a tick would buy and what the funders must hold. No I/O.
+node scripts/x402-fresh-workers-run.mjs --plan
+
+# One real tick against production endpoints from this machine (needs the
+# ring env: funders, WALLET_ENCRYPTION_KEY, DATABASE_URL).
+X402_FRESH_WORKERS_PER_TICK=1 node scripts/x402-fresh-workers-run.mjs 1
+```
+
+Production needs nothing beyond the ring env it already has: the lane is on
+by default, fired by the economy heartbeat, and the tables are created by
+migration `20260922100000_x402_fresh_workers.sql` (with an idempotent guard
+in code for a tick that runs first).
+
+## Env
+
+| Var | Default | Meaning |
+| --- | --- | --- |
+| `X402_FRESH_WORKERS_ENABLED` | `true` | `false` pauses the lane |
+| `X402_FRESH_WORKERS_PER_TICK` | `3` | fresh wallets minted and jobs bought per minute |
+| `X402_FRESH_WORKERS_FORGE_EVERY_N_TICKS` | `10` | one Forge generation every N ticks; the rest are datasets |
+| `X402_FRESH_WORKERS_DAILY_CAP_ATOMIC` | `40000000` ($40) | USDC the lane may spend per UTC day |
+| `X402_FRESH_WORKERS_TICK_BUDGET_MS` | `50000` | wall-clock budget per tick |
+| `X402_FRESH_WORKERS_RECLAIM_AFTER_S` | `90` | how long a mid-flight wallet is left to its tick before reclaim |
+| `X402_FRESH_WORKERS_MAX_SWEEP_ATTEMPTS` | `20` | sweep retries before a wallet is stranded and alerted |
+| `X402_FRESH_WORKERS_MEMBERSHIP_HOURS` | `36` | how long a fresh wallet stays in the controlled-wallet set |
+| `X402_FRESH_WORKERS_RECLAIM_BATCH` | `12` | reclaims attempted per tick |
+
+## Related
+
+- [x402 ring economy](./x402-ring-economy.md): the closed loop this lane
+ runs inside, its governors, and the payer pool it complements
+- [Autonomous x402](./autonomous-x402.md): the catalog sweeper and the
+ hourly forge pipeline whose sink this lane shares
+- [Economy wallet rotation](./ops/economy-wallet-rotation.md): the funders
+- [STRUCTURE.md](../STRUCTURE.md): surface map
diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.md
index 029fd2078..1a7933662 100644
--- a/docs/x402-ring-economy.md
+++ b/docs/x402-ring-economy.md
@@ -1196,3 +1196,6 @@ activation runbook above is the fix.
controlled-wallet set + spend invariants
- [api/cron/x402-ring-leak-scan.js](../api/cron/x402-ring-leak-scan.js) — the
on-chain leak scanner
+- [Fresh-wallet workers](./x402-fresh-workers.md): the lane that runs beside
+ the ring, paying from a brand-new wallet per job and buying real work (3D
+ props for /forged, datasets for /data-desk) instead of canaries
diff --git a/pages/data-desk.html b/pages/data-desk.html
new file mode 100644
index 000000000..05009d75b
--- /dev/null
+++ b/pages/data-desk.html
@@ -0,0 +1,301 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <script>/* three.ws theme boot: no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title data-i18n="data_desk.meta_title">Data Desk · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
+ <meta
+ name="description"
+ content="Live market data bought minute by minute by brand-new agent wallets over x402. Every dataset carries its receipt: the wallet that paid, the price, and the Solana settlement transaction."
+ data-i18n-attr="content:data_desk.meta_description"/>
+ <meta name="theme-color" content="#000000" />
+ <link rel="canonical" href="https://three.ws/data-desk" />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:title" content="Data Desk · three.ws" data-i18n-attr="content:data_desk.meta_og_title"/>
+ <meta property="og:description" content="Live market data bought by brand-new agent wallets over x402, each with its on-chain receipt." data-i18n-attr="content:data_desk.meta_og_description"/>
+ <meta property="og:url" content="https://three.ws/data-desk" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Data+Desk&amp;d=Live+market+data+bought+minute+by+minute+by+brand-new+agent+wallets+over+x402.+Every+dataset+carries+its+receipt.&amp;p=%2Fdata-desk" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="Data Desk · three.ws" data-i18n-attr="content:data_desk.meta_twitter_title"/>
+ <meta name="twitter:description" content="Live market data bought by brand-new agent wallets over x402." data-i18n-attr="content:data_desk.meta_twitter_description"/>
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Data+Desk&amp;d=Live+market+data+bought+minute+by+minute+by+brand-new+agent+wallets+over+x402.+Every+dataset+carries+its+receipt.&amp;p=%2Fdata-desk" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+ <meta property="og:locale" content="en_US" />
+ <meta property="og:image:alt" content="Data Desk, three.ws" />
+
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"Dataset","name":"three.ws Data Desk","description":"Live market data bought minute by minute by brand-new agent wallets over x402, each purchase carrying its Solana settlement receipt.","url":"https://three.ws/data-desk","isAccessibleForFree":true,"creator":{"@type":"Organization","name":"three.ws","url":"https://three.ws"}}</script>
+
+ <style>
+ .dd-main { max-width: 1320px; margin: 0 auto; padding: 0 clamp(16px, 4vw, 40px) 80px; }
+
+ .dd-hero { padding: clamp(36px, 6vw, 72px) 0 clamp(20px, 3vw, 28px); }
+ .dd-chip {
+ display: inline-flex; align-items: center; gap: 8px;
+ padding: 5px 12px; border: 1px solid var(--stroke); border-radius: 999px;
+ background: var(--surface-1); font-size: 12px; letter-spacing: .04em;
+ text-transform: uppercase; color: var(--ink-dim); font-family: var(--font-mono);
+ }
+ .dd-dot { width: 7px; height: 7px; border-radius: 50%; background: #38d39f; box-shadow: 0 0 0 3px rgba(56,211,159,.18); }
+ .dd-dot--live { animation: dd-pulse 2.4s ease-in-out infinite; }
+ @keyframes dd-pulse { 0%, 100% { box-shadow: 0 0 0 3px rgba(56,211,159,.18); } 50% { box-shadow: 0 0 0 6px rgba(56,211,159,.06); } }
+ @media (prefers-reduced-motion: reduce) { .dd-dot--live { animation: none; } }
+ .dd-hero h1 { font-size: clamp(30px, 5vw, 52px); line-height: 1.04; margin: 18px 0 12px; letter-spacing: -.02em; }
+ .dd-hero p { max-width: 64ch; color: var(--ink-dim); font-size: clamp(15px, 1.4vw, 17px); line-height: 1.6; margin: 0; }
+ .dd-hero-actions { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin-top: 22px; }
+ .dd-hbtn {
+ display: inline-flex; align-items: center; gap: 6px; padding: 9px 14px; border-radius: 10px;
+ font-size: 14px; font-weight: 600; text-decoration: none; border: 1px solid var(--stroke);
+ transition: border-color .15s ease, background .15s ease, transform .15s ease;
+ }
+ .dd-hbtn:hover { transform: translateY(-1px); }
+ .dd-hbtn:active { transform: translateY(0); }
+ .dd-hbtn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .dd-hbtn--primary { background: var(--accent); color: var(--accent-ink, #0b0b0f); border-color: transparent; }
+ .dd-hbtn--secondary { background: var(--surface-1); color: var(--ink); }
+ .dd-hbtn--secondary:hover { border-color: var(--stroke-strong); }
+
+ .dd-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin: 18px 0 26px; }
+ .dd-stat {
+ padding: 14px 16px; border: 1px solid var(--stroke); border-radius: 12px; background: var(--surface-1);
+ transition: border-color .15s ease;
+ }
+ .dd-stat:hover { border-color: var(--stroke-strong); }
+ .dd-stat-label { font-size: 11px; letter-spacing: .06em; text-transform: uppercase; color: var(--ink-dim); font-family: var(--font-mono); }
+ .dd-stat-value { font-size: clamp(20px, 2.2vw, 26px); font-weight: 700; margin-top: 6px; letter-spacing: -.01em; font-variant-numeric: tabular-nums; }
+ .dd-stat-sub { font-size: 12px; color: var(--ink-dim); margin-top: 2px; }
+ .dd-stat--skeleton .dd-stat-value { height: 26px; width: 60%; border-radius: 6px; background: linear-gradient(90deg, var(--surface-2, var(--surface-1)) 25%, var(--stroke) 50%, var(--surface-2, var(--surface-1)) 75%); background-size: 200% 100%; animation: dd-shimmer 1.4s linear infinite; }
+
+ .dd-toolbar {
+ position: sticky; top: 0; z-index: 5;
+ display: flex; flex-wrap: wrap; gap: 12px; align-items: center;
+ padding: 14px 0; margin-bottom: 8px;
+ background: color-mix(in srgb, var(--surface-1) 60%, transparent);
+ backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
+ }
+ .dd-search-wrap { position: relative; flex: 1 1 260px; max-width: 420px; }
+ .dd-search-icon { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: var(--ink-dim); pointer-events: none; }
+ .dd-search {
+ width: 100%; padding: 10px 36px 10px 34px; border-radius: 10px; border: 1px solid var(--stroke);
+ background: var(--surface-1); color: var(--ink); font-size: 14px;
+ transition: border-color .15s ease, box-shadow .15s ease;
+ }
+ .dd-search:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
+ .dd-search-kbd { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); font-size: 11px; color: var(--ink-dim); border: 1px solid var(--stroke); border-radius: 5px; padding: 1px 6px; font-family: var(--font-mono); }
+ .dd-count { color: var(--ink-dim); font-size: 13px; font-family: var(--font-mono); margin-left: auto; }
+
+ .dd-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 14px; }
+ .dd-card {
+ display: flex; flex-direction: column; gap: 10px; padding: 16px;
+ border: 1px solid var(--stroke); border-radius: 14px; background: var(--surface-1);
+ transition: border-color .15s ease, transform .15s ease, box-shadow .15s ease;
+ animation: dd-enter .28s ease both;
+ }
+ .dd-card:hover { border-color: var(--stroke-strong); transform: translateY(-2px); box-shadow: 0 10px 30px rgba(0,0,0,.14); }
+ .dd-card:focus-within { border-color: var(--accent); }
+ @keyframes dd-enter { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
+ @media (prefers-reduced-motion: reduce) { .dd-card { animation: none; } .dd-card:hover { transform: none; } }
+ .dd-card-head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
+ .dd-card-title { font-size: 16px; font-weight: 700; margin: 0; letter-spacing: -.01em; }
+ .dd-card-age { font-size: 12px; color: var(--ink-dim); font-family: var(--font-mono); white-space: nowrap; }
+ .dd-card-blurb { font-size: 13px; color: var(--ink-dim); margin: 0; line-height: 1.45; }
+ .dd-kv { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px 12px; margin: 2px 0; }
+ .dd-kv--3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
+ .dd-k { font-size: 11px; letter-spacing: .05em; text-transform: uppercase; color: var(--ink-dim); font-family: var(--font-mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .dd-v { font-size: 17px; font-weight: 700; font-variant-numeric: tabular-nums; letter-spacing: -.01em; margin-top: 2px; }
+ .dd-v small { font-size: 12px; font-weight: 500; color: var(--ink-dim); margin-left: 4px; }
+ .dd-up { color: #38d39f; } .dd-down { color: #ff6b6b; }
+ .dd-rows { display: flex; flex-direction: column; gap: 6px; margin: 2px 0; }
+ .dd-row { display: flex; align-items: center; gap: 10px; font-size: 13px; }
+ .dd-row-rank { flex: none; width: 18px; color: var(--ink-dim); font-family: var(--font-mono); font-size: 11px; }
+ .dd-row-name { flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .dd-row-val { flex: none; font-family: var(--font-mono); font-variant-numeric: tabular-nums; font-size: 12px; }
+ .dd-row-delta { flex: none; width: 56px; text-align: right; font-family: var(--font-mono); font-size: 12px; }
+ .dd-bar { height: 6px; border-radius: 999px; background: var(--stroke); overflow: hidden; }
+ .dd-bar > i { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg, #ff6b6b, #f6c945 50%, #38d39f); transition: width .4s ease; }
+ .dd-receipt {
+ display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: auto; padding-top: 10px;
+ border-top: 1px solid var(--stroke); font-size: 12px; font-family: var(--font-mono); color: var(--ink-dim);
+ }
+ .dd-receipt-amount { color: #38d39f; font-weight: 600; }
+ .dd-receipt-payer { overflow: hidden; text-overflow: ellipsis; }
+ .dd-receipt-fresh {
+ flex: none; padding: 1px 7px; border-radius: 999px; font-size: 10px; letter-spacing: .04em;
+ text-transform: uppercase; color: #38d39f; border: 1px solid rgba(56,211,159,.35); background: rgba(56,211,159,.08);
+ }
+ .dd-receipt-tx { margin-left: auto; color: var(--ink); text-decoration: none; border-bottom: 1px dotted var(--stroke-strong); }
+ .dd-receipt-tx:hover { color: var(--accent); border-bottom-color: var(--accent); }
+ .dd-receipt-tx:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 3px; }
+ .dd-card-actions { display: flex; gap: 8px; }
+ .dd-btn {
+ display: inline-flex; align-items: center; padding: 6px 10px; border-radius: 8px; font-size: 12px; font-weight: 600;
+ text-decoration: none; border: 1px solid var(--stroke); color: var(--ink); background: transparent;
+ transition: border-color .15s ease, background .15s ease; cursor: pointer;
+ }
+ .dd-btn:hover { border-color: var(--stroke-strong); background: var(--surface-2, var(--surface-1)); }
+ .dd-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+
+ .dd-section { margin-top: 40px; }
+ .dd-section h2 { font-size: 20px; margin: 0 0 6px; letter-spacing: -.01em; }
+ .dd-section-lede { color: var(--ink-dim); font-size: 14px; margin: 0 0 14px; max-width: 70ch; line-height: 1.5; }
+ .dd-ledger { display: flex; flex-direction: column; border: 1px solid var(--stroke); border-radius: 12px; overflow: hidden; }
+ .dd-ledger-row {
+ display: grid; grid-template-columns: 70px minmax(0, 1.4fr) minmax(0, 1fr) 80px 90px; gap: 10px; align-items: center;
+ padding: 10px 14px; font-size: 13px; border-top: 1px solid var(--stroke); background: var(--surface-1);
+ transition: background .15s ease;
+ }
+ .dd-ledger-row:first-child { border-top: 0; }
+ .dd-ledger-row:hover { background: var(--surface-2, var(--surface-1)); }
+ .dd-ledger-head { font-size: 11px; letter-spacing: .05em; text-transform: uppercase; color: var(--ink-dim); font-family: var(--font-mono); }
+ .dd-ledger-cell { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .dd-mono { font-family: var(--font-mono); font-size: 12px; }
+ .dd-ledger-tx { text-align: right; }
+ .dd-ledger-tx a { color: var(--ink); text-decoration: none; border-bottom: 1px dotted var(--stroke-strong); }
+ .dd-ledger-tx a:hover { color: var(--accent); }
+ @media (max-width: 720px) {
+ .dd-ledger-row { grid-template-columns: 60px minmax(0, 1fr) 70px; }
+ .dd-ledger-row > :nth-child(3), .dd-ledger-row > :nth-child(5) { display: none; }
+ }
+
+ .dd-skeleton-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 14px; }
+ .dd-skeleton { height: 220px; border-radius: 14px; border: 1px solid var(--stroke);
+ background: linear-gradient(90deg, var(--surface-1) 25%, var(--stroke) 50%, var(--surface-1) 75%);
+ background-size: 200% 100%; animation: dd-shimmer 1.4s linear infinite; }
+ @keyframes dd-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
+ @media (prefers-reduced-motion: reduce) { .dd-skeleton, .dd-stat--skeleton .dd-stat-value { animation: none; } }
+
+ .dd-state { text-align: center; padding: 56px 20px; border: 1px dashed var(--stroke); border-radius: 14px; }
+ .dd-state-icon { font-size: 34px; margin-bottom: 10px; }
+ .dd-state h2 { margin: 0 0 8px; font-size: 20px; }
+ .dd-state p { color: var(--ink-dim); max-width: 56ch; margin: 0 auto 16px; line-height: 1.55; }
+ .dd-state-detail { font-family: var(--font-mono); font-size: 12px; }
+
+ .dd-explain { margin-top: 44px; padding: 22px; border: 1px solid var(--stroke); border-radius: 14px; background: var(--surface-1); }
+ .dd-explain h2 { font-size: 18px; margin: 0 0 10px; }
+ .dd-explain ol { margin: 0; padding-left: 20px; color: var(--ink-dim); line-height: 1.6; font-size: 14px; }
+ .dd-explain li { margin: 4px 0; }
+ .dd-explain a { color: var(--ink); }
+
+ @media (max-width: 560px) {
+ .dd-grid, .dd-skeleton-grid { grid-template-columns: 1fr; }
+ .dd-kv--3 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+ }
+ </style>
+ </head>
+ <body>
+ <header>
+ <div id="nav-container"></div>
+ </header>
+ <script src="/nav.js"></script>
+
+ <main class="dd-main">
+ <section class="dd-hero">
+ <div class="dd-chip">
+ <span class="dd-dot dd-dot--live" aria-hidden="true"></span>
+ <span data-i18n="data_desk.chip">Data Desk · bought live</span>
+ </div>
+ <h1 data-i18n="data_desk.title">Market data bought by brand-new agent wallets, receipts included</h1>
+ <p data-i18n="data_desk.lede">
+ Every minute the platform mints a few Solana wallets that have never existed before, gives each one
+ exactly one job's worth of USDC, and lets it buy a real dataset from the three.ws market-data storefront
+ over the x402 payment protocol. The answer lands here with its receipt: the wallet that paid, the price,
+ and the settlement transaction. Then the wallet is emptied and closed. No curation, no mocks: this is
+ the agent economy doing real work, one paid call at a time.
+ </p>
+ <div class="dd-hero-actions">
+ <a href="/forged" class="dd-hbtn dd-hbtn--primary" data-i18n="data_desk.see_props">See the 3D props they bought</a>
+ <a href="/api/data-desk" class="dd-hbtn dd-hbtn--secondary" data-i18n="data_desk.json_feed">JSON feed</a>
+ <a href="/economy-lab" class="dd-hbtn dd-hbtn--secondary" data-i18n="data_desk.runway_lab">Runway Lab</a>
+ <a href="/x402" class="dd-hbtn dd-hbtn--secondary" data-i18n="data_desk.about_x402">About x402</a>
+ </div>
+ </section>
+
+ <div class="dd-stats" data-role="stats" aria-live="polite">
+ <div class="dd-stat dd-stat--skeleton"><div class="dd-stat-label" data-i18n="data_desk.stat_datasets">Datasets live</div><div class="dd-stat-value"></div></div>
+ <div class="dd-stat dd-stat--skeleton"><div class="dd-stat-label" data-i18n="data_desk.stat_purchases">Purchases, 24h</div><div class="dd-stat-value"></div></div>
+ <div class="dd-stat dd-stat--skeleton"><div class="dd-stat-label" data-i18n="data_desk.stat_wallets">Fresh wallets, 24h</div><div class="dd-stat-value"></div></div>
+ <div class="dd-stat dd-stat--skeleton"><div class="dd-stat-label" data-i18n="data_desk.stat_usdc">USDC recirculated, 24h</div><div class="dd-stat-value"></div></div>
+ <div class="dd-stat dd-stat--skeleton"><div class="dd-stat-label" data-i18n="data_desk.stat_sol">SOL burned in fees, 24h</div><div class="dd-stat-value"></div></div>
+ </div>
+
+ <div class="dd-toolbar" role="toolbar" aria-label="Filter datasets">
+ <div class="dd-search-wrap">
+ <svg class="dd-search-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
+ <input type="search" class="dd-search" placeholder="Filter datasets…" aria-label="Filter datasets" autocomplete="off" data-role="search" />
+ <kbd class="dd-search-kbd" aria-hidden="true">/</kbd>
+ </div>
+ <span class="dd-count" data-role="count" aria-live="polite"></span>
+ </div>
+
+ <div data-role="loading" class="dd-skeleton-grid" role="status" aria-label="Loading bought datasets">
+ <div class="dd-skeleton"></div><div class="dd-skeleton"></div><div class="dd-skeleton"></div>
+ <div class="dd-skeleton"></div><div class="dd-skeleton"></div><div class="dd-skeleton"></div>
+ </div>
+
+ <div data-role="grid" class="dd-grid" hidden></div>
+
+ <div data-role="empty" class="dd-state" hidden>
+ <div class="dd-state-icon">🪙</div>
+ <h2 data-i18n="data_desk.empty_title">Nothing has been bought yet</h2>
+ <p data-i18n="data_desk.empty_body">
+ The fresh-wallet workers buy a dataset roughly every minute and a 3D prop every few minutes.
+ The first purchases will appear here with their receipts as soon as they settle on Solana.
+ </p>
+ <a href="/forged" class="dd-hbtn dd-hbtn--primary" data-i18n="data_desk.empty_cta">See the agent-forged gallery</a>
+ </div>
+
+ <div data-role="empty-search" class="dd-state" hidden>
+ <div class="dd-state-icon">🔍</div>
+ <h2 data-i18n="data_desk.no_matches">No matches</h2>
+ <p data-i18n="data_desk.no_matches_body">No dataset matches your filter.</p>
+ <button class="dd-hbtn dd-hbtn--secondary" data-role="clear-search" data-i18n="data_desk.clear_filter">Clear filter</button>
+ </div>
+
+ <div data-role="error" class="dd-state" hidden>
+ <div class="dd-state-icon">⚠️</div>
+ <h2 data-i18n="data_desk.error_title">Couldn't load the data desk</h2>
+ <p data-i18n="data_desk.error_body">Something went wrong loading the bought datasets.</p>
+ <!-- The specific reason is written by the page script and must NOT carry a
+ data-i18n key: the translation pass would overwrite it. -->
+ <p class="dd-state-detail" data-role="error-msg"></p>
+ <button class="dd-hbtn dd-hbtn--secondary" data-role="retry" data-i18n="data_desk.try_again">Try again</button>
+ </div>
+
+ <section class="dd-section" data-role="ledger-section" hidden aria-labelledby="dd-ledger-h">
+ <h2 id="dd-ledger-h" data-i18n="data_desk.ledger_title">Recent purchases</h2>
+ <p class="dd-section-lede" data-i18n="data_desk.ledger_lede">
+ Every row is one wallet's single purchase. The wallet did not exist before the minute it paid and was
+ closed right after; the receipt link opens the settlement on Solscan.
+ </p>
+ <div class="dd-ledger" data-role="ledger" role="table" aria-label="Recent purchases"></div>
+ </section>
+
+ <section class="dd-explain" aria-labelledby="dd-how-h">
+ <h2 id="dd-how-h" data-i18n="data_desk.how_title">How a purchase works</h2>
+ <ol>
+ <li data-i18n="data_desk.how_1">A brand-new keypair is generated and stored encrypted. It has never appeared on chain.</li>
+ <li data-i18n="data_desk.how_2">One funding transaction gives it the exact USDC price of its job plus enough SOL to stay rent-exempt and pay two network fees.</li>
+ <li data-i18n="data_desk.how_3">The wallet calls the paid endpoint, receives the 402 challenge, signs one USDC transfer and gets the data back. The settlement is a normal Solana transaction anyone can verify.</li>
+ <li data-i18n="data_desk.how_4">The wallet sends any leftover USDC to the treasury, closes its token account so the rent goes back to the funder, and sends every remaining lamport home. It ends at zero and is never used again.</li>
+ </ol>
+ <p class="dd-section-lede" style="margin: 12px 0 0">
+ <span data-i18n="data_desk.how_more">Lane statistics and every wallet's three signatures are public at</span>
+ <a href="/api/fresh-workers">/api/fresh-workers</a>.
+ </p>
+ </section>
+ </main>
+
+ <script src="/footer.js" defer></script>
+ <script type="module" src="/src/data-desk.js"></script>
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/pages/forged.html b/pages/forged.html
index 9657cff09..f03ade35e 100644
--- a/pages/forged.html
+++ b/pages/forged.html
@@ -155,6 +155,10 @@
}
.fg-receipt-amount { color: #38d39f; font-weight: 600; }
.fg-receipt-payer { overflow: hidden; text-overflow: ellipsis; }
+ .fg-receipt-fresh {
+ flex: none; padding: 1px 7px; border-radius: 999px; font-size: 10px; letter-spacing: .04em;
+ text-transform: uppercase; color: #38d39f; border: 1px solid rgba(56,211,159,.35); background: rgba(56,211,159,.08);
+ }
.fg-receipt-tx { margin-left: auto; color: var(--ink); text-decoration: none; border-bottom: 1px dotted var(--stroke-strong); }
.fg-receipt-tx:hover { color: var(--accent); border-bottom-color: var(--accent); }
.fg-receipt-tx:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 3px; }
diff --git a/public/changelog-recent.json b/public/changelog-recent.json
index 65e29544c..132f415f8 100644
--- a/public/changelog-recent.json
+++ b/public/changelog-recent.json
@@ -1,14 +1,44 @@
{
- "generated_at": "2026-09-21T22:46:08.594Z",
+ "generated_at": "2026-09-22T04:19:11.095Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
- "total": 3744,
+ "total": 3747,
"complete": false,
"full_feed": "/changelog.json",
"entries": [
+ {
+ "date": "2026-09-22",
+ "type": "launch",
+ "title": "Data Desk",
+ "summary": "Live market data bought minute by minute by brand-new agent wallets over x402. Every dataset carries its receipt: the wallet that paid, the price, and the Solana settlement transaction.",
+ "link": "/data-desk",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-09-22",
+ "type": "launch",
+ "title": "Docs · Fresh-wallet workers",
+ "summary": "How the platform mints a brand-new Solana wallet for every x402 purchase, what those wallets buy (3D props for the library, datasets for the data desk), how each wallet is emptied and closed so nothing strands, and where to watch it.",
+ "link": "/docs/x402-fresh-workers",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-09-22",
+ "type": "update",
+ "title": "Agents now buy real work from brand-new wallets, and you can watch it",
+ "summary": "The platform's agent economy used to prove the payment rail from a few long-lived wallets buying test calls. It now mints a fresh Solana wallet for every purchase: each one is created, given exactly one job's worth of USDC, pays a three.ws endpoint, and is emptied and closed within the minute. Every purchase does something useful. Some buy a 3D generation that lands in the Agent-Forged Gallery, where a new fresh wallet badge marks it. The rest buy live market data, which now has its own page, the Data Desk, showing each dataset with the wallet that paid, the price, and the Solana receipt. Both feeds are public JSON as well, and a new stats endpoint lists every wallet with its three transactions.",
+ "link": "/data-desk",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-09-21",
"type": "update",
@@ -1581,39 +1611,6 @@
"fix",
"infra"
]
- },
- {
- "date": "2026-09-09",
- "type": "update",
- "title": "The pitch deck now shows the whole character, and says so when the 3D cannot load",
- "summary": "The live 3D figure on the deck at /pitch was framed by a camera that cut it off above the chest and pointed at its back, so the slide that says \"give your AI a face\" showed neither a head nor a face. Both stages now frame the full character from the front. Each stage also ships a still frame rendered from the same glTF file: it fills the panel while the model streams instead of leaving an empty box, and if the 3D runtime is blocked or fails outright the panel says so in the open, drops the \"Live\" badge that used to sit over nothing, and offers a retry. Navigation got the same pass: the slide dots are now full-size tap targets and step out of the way on a phone, the language picker no longer lands on the slide counter, slide copy no longer runs underneath the nav bar on a tablet, links on hidden slides are out of the keyboard tab order, and every button and link has a visible focus ring.",
- "link": "/pitch",
- "tags": [
- "fix",
- "improvement"
- ]
- },
- {
- "date": "2026-09-09",
- "type": "update",
- "title": "The press kit reads in the three.ws typeface, fits a phone, and quotes every mark at its true size",
- "summary": "Every paragraph on the press kit was rendering in the browser default serif on a bare white-ish ground: the page styled its own cards and headings but never applied the site typeface, colour, or background to the document itself, so the one page a journalist opens looked nothing like the rest of three.ws. It now uses the platform design tokens throughout, in both light and dark mode. On a 320px phone the two OpenAI announcement cards were sliced off at the right edge, taking their Download PNG buttons with them, and because the page clips rather than scrolls sideways there was no way to reach what was cut; both card grids now fold to a single full-width column instead. The pixel dimensions printed under each mark were also all slightly wrong, off by a pixel or two from the artwork they labelled, which is the number a designer laying out a conference programme actually acts on. They are corrected, and the brand asset renderer now writes them back from the PNG headers on every build the way it already did for the archive size, so they cannot drift again. Last, the Copy buttons beside the boilerplate did nothing at all when the browser withheld clipboard access; they now select the passage in place and tell you which keys to press.",
- "link": "/press",
- "tags": [
- "fix",
- "improvement"
- ]
- },
- {
- "date": "2026-09-09",
- "type": "update",
- "title": "The Pump Visualizer's live counters stopped freezing a few seconds after the page opened",
- "summary": "A full audit of /pump-visualizer, the 3D scene of live pump.fun mints. The status bar across the top counts the tokens in the scene, the mint rate per minute and the total market cap, and about fifteen seconds into every visit all three froze: the counter sat at 0 and the rate and total sat at a dash while the scene behind them kept filling with new coins. The cause was the page's own translation pass. Those three numbers were written inside blocks of translated copy, so the moment the language file arrived the browser rebuilt that copy and threw away the very elements the page was writing into. The numbers now live beside their labels instead of inside them, so the labels still translate into all 85 languages and the values keep counting for as long as the page is open. The per-minute and per-hour units now translate too, which they never did once the page switched between live mints and migrations. The page also gained a heading and a labelled search box for screen readers, and its browser tab now reads Pump.fun Visualizer, three.ws instead of a retired product name.",
- "link": "/pump-visualizer",
- "tags": [
- "fix",
- "improvement"
- ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index 93fbe2b7e..e264809ea 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,41 @@
{
- "generated_at": "2026-09-21T22:46:08.566Z",
+ "generated_at": "2026-09-22T04:19:11.069Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-09-22",
+ "type": "launch",
+ "title": "Data Desk",
+ "summary": "Live market data bought minute by minute by brand-new agent wallets over x402. Every dataset carries its receipt: the wallet that paid, the price, and the Solana settlement transaction.",
+ "link": "/data-desk",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-09-22",
+ "type": "launch",
+ "title": "Docs · Fresh-wallet workers",
+ "summary": "How the platform mints a brand-new Solana wallet for every x402 purchase, what those wallets buy (3D props for the library, datasets for the data desk), how each wallet is emptied and closed so nothing strands, and where to watch it.",
+ "link": "/docs/x402-fresh-workers",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-09-22",
+ "type": "update",
+ "title": "Agents now buy real work from brand-new wallets, and you can watch it",
+ "summary": "The platform's agent economy used to prove the payment rail from a few long-lived wallets buying test calls. It now mints a fresh Solana wallet for every purchase: each one is created, given exactly one job's worth of USDC, pays a three.ws endpoint, and is emptied and closed within the minute. Every purchase does something useful. Some buy a 3D generation that lands in the Agent-Forged Gallery, where a new fresh wallet badge marks it. The rest buy live market data, which now has its own page, the Data Desk, showing each dataset with the wallet that paid, the price, and the Solana receipt. Both feeds are public JSON as well, and a new stats endpoint lists every wallet with its three transactions.",
+ "link": "/data-desk",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-09-21",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index d5d3a5028..a96a6a298 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,30 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws: features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Data Desk</title>
+ <link>https://three.ws/data-desk</link>
+ <guid isPermaLink="false">2026-09-22:Data Desk</guid>
+ <pubDate>Tue, 22 Sep 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Live market data bought minute by minute by brand-new agent wallets over x402. Every dataset carries its receipt: the wallet that paid, the price, and the Solana settlement transaction.</description>
+ </item>
+ <item>
+ <title>Docs · Fresh-wallet workers</title>
+ <link>https://three.ws/docs/x402-fresh-workers</link>
+ <guid isPermaLink="false">2026-09-22:Docs · Fresh-wallet workers</guid>
+ <pubDate>Tue, 22 Sep 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>How the platform mints a brand-new Solana wallet for every x402 purchase, what those wallets buy (3D props for the library, datasets for the data desk), how each wallet is emptied and closed so nothing strands, and where to watch it.</description>
+ </item>
+ <item>
+ <title>Agents now buy real work from brand-new wallets, and you can watch it</title>
+ <link>https://three.ws/data-desk</link>
+ <guid isPermaLink="false">2026-09-22:Agents now buy real work from brand-new wallets, and you can watch it</guid>
+ <pubDate>Tue, 22 Sep 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The platform's agent economy used to prove the payment rail from a few long-lived wallets buying test calls. It now mints a fresh Solana wallet for every purchase: each one is created, given exactly one job's worth of USDC, pays a three.ws endpoint, and is emptied and closed within the minute. Every purchase does something useful. Some buy a 3D generation that lands in the Agent-Forged Gallery, where a new fresh wallet badge marks it. The rest buy live market data, which now has its own page, the Data Desk, showing each dataset with the wallet that paid, the price, and the Solana receipt. Both feeds are public JSON as well, and a new stats endpoint lists every wallet with its three transactions.</description>
+ </item>
<item>
<title>Forge now asks what your model is for</title>
<link>https://three.ws/forge</link>
diff --git a/public/features.json b/public/features.json
index aab79f6f7..a0bef147f 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-21T05:41:11.217Z",
+ "generated_at": "2026-09-22T04:19:11.057Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -136,6 +136,16 @@
"tags": [],
"showcase": true
},
+ {
+ "path": "/data-desk",
+ "title": "Data Desk",
+ "description": "Live market data bought minute by minute by brand-new agent wallets over x402. Every dataset carries its receipt: the wallet that paid, the price, and the Solana settlement transaction.",
+ "added": "2026-09-22",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": true
+ },
{
"path": "/forged",
"title": "Agent-Forged Gallery",
@@ -6878,6 +6888,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/docs/x402-fresh-workers",
+ "title": "Docs · Fresh-wallet workers",
+ "description": "How the platform mints a brand-new Solana wallet for every x402 purchase, what those wallets buy (3D props for the library, datasets for the data desk), how each wallet is emptied and closed so nothing strands, and where to watch it.",
+ "added": "2026-09-22",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/docs/three-microbuy",
"title": "Docs · The $THREE micro-buy loop",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index cfec8c5a2..046daca27 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -86,6 +86,12 @@ URL: https://three.ws/objects
Hundreds of free CC0 3D objects and props: furniture, lighting, electronics, decor. Public domain, no attribution required. Preview live, place it in your room with AR, or download the GLB.
+### Data Desk
+
+URL: https://three.ws/data-desk
+
+Live market data bought minute by minute by brand-new agent wallets over x402. Every dataset carries its receipt: the wallet that paid, the price, and the Solana settlement transaction.
+
### Agent-Forged Gallery
URL: https://three.ws/forged
@@ -4174,6 +4180,12 @@ URL: 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 · Fresh-wallet workers
+
+URL: https://three.ws/docs/x402-fresh-workers
+
+How the platform mints a brand-new Solana wallet for every x402 purchase, what those wallets buy (3D props for the library, datasets for the data desk), how each wallet is emptied and closed so nothing strands, and where to watch it.
+
### Docs · The $THREE micro-buy loop
URL: https://three.ws/docs/three-microbuy
diff --git a/public/llms.txt b/public/llms.txt
index 50cffa079..996632d89 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -45,6 +45,7 @@ Entry points into the product.
- [ASL Alphabet](https://three.ws/asl-alphabet): The American manual alphabet on a live 3D avatar: every letter and number, what to look for, the look-alikes it is confused with, spell any word, and a drill for reading fingerspelling.
- [Sign Mirror](https://three.ws/sign-mirror): Learn the ASL alphabet by making it: the avatar forms the letter, your camera watches your hand, and the page grades the handshape live, naming the finger that is off. Fully on-device; no video ever uploaded.
- [Object Library](https://three.ws/objects): Hundreds of free CC0 3D objects and props: furniture, lighting, electronics, decor. Public domain, no attribution required. Preview live, place it in your room with AR, or download the GLB.
+- [Data Desk](https://three.ws/data-desk): Live market data bought minute by minute by brand-new agent wallets over x402. Every dataset carries its receipt: the wallet that paid, the price, and the Solana settlement transaction.
- [Agent-Forged Gallery](https://three.ws/forged): 3D props bought by autonomous AI agents with real USDC over x402. Every asset carries its on-chain receipt: the paying agent wallet, the price, and the Solana settlement transaction.
- [Wardrobe](https://three.ws/wardrobe): The open garment catalog for 3D avatars: browse every wearable, inspect it in 3D, and generate new pieces from a text prompt. Every piece binds to any humanoid avatar at runtime.
- [Diorama](https://three.ws/diorama): Speak a little world into being: describe a scene and watch it assemble into an explorable 3D diorama you can walk through, then take it into AR.
@@ -713,6 +714,7 @@ Docs, tutorials, and reference.
- [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 · Fresh-wallet workers](https://three.ws/docs/x402-fresh-workers): How the platform mints a brand-new Solana wallet for every x402 purchase, what those wallets buy (3D props for the library, datasets for the data desk), how each wallet is emptied and closed so nothing strands, and where to watch it.
- [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.
- [Docs · IBM Granite pay-per-call MCP](https://three.ws/docs/ibm-x402-mcp): A menu of IBM AI capabilities (chat, code, embeddings, document analysis, forecasting) that any agent or MCP client can use by paying a few cents per call, with no account and no subscription.
diff --git a/public/locales/en.json b/public/locales/en.json
index 920275e01..f4ba2f811 100644
--- a/public/locales/en.json
+++ b/public/locales/en.json
@@ -4359,6 +4359,43 @@
"x402": "x402",
"your_skus": "Your SKUs"
},
+ "data_desk": {
+ "about_x402": "About x402",
+ "chip": "Data Desk · bought live",
+ "clear_filter": "Clear filter",
+ "empty_body": "The fresh-wallet workers buy a dataset roughly every minute and a 3D prop every few minutes. The first purchases will appear here with their receipts as soon as they settle on Solana.",
+ "empty_cta": "See the agent-forged gallery",
+ "empty_title": "Nothing has been bought yet",
+ "error_body": "Something went wrong loading the bought datasets.",
+ "error_title": "Couldn't load the data desk",
+ "how_1": "A brand-new keypair is generated and stored encrypted. It has never appeared on chain.",
+ "how_2": "One funding transaction gives it the exact USDC price of its job plus enough SOL to stay rent-exempt and pay two network fees.",
+ "how_3": "The wallet calls the paid endpoint, receives the 402 challenge, signs one USDC transfer and gets the data back. The settlement is a normal Solana transaction anyone can verify.",
+ "how_4": "The wallet sends any leftover USDC to the treasury, closes its token account so the rent goes back to the funder, and sends every remaining lamport home. It ends at zero and is never used again.",
+ "how_more": "Lane statistics and every wallet's three signatures are public at",
+ "how_title": "How a purchase works",
+ "json_feed": "JSON feed",
+ "lede": "Every minute the platform mints a few Solana wallets that have never existed before, gives each one exactly one job's worth of USDC, and lets it buy a real dataset from the three.ws market-data storefront over the x402 payment protocol. The answer lands here with its receipt: the wallet that paid, the price, and the settlement transaction. Then the wallet is emptied and closed. No curation, no mocks: this is the agent economy doing real work, one paid call at a time.",
+ "ledger_lede": "Every row is one wallet's single purchase. The wallet did not exist before the minute it paid and was closed right after; the receipt link opens the settlement on Solscan.",
+ "ledger_title": "Recent purchases",
+ "meta_description": "Live market data bought minute by minute by brand-new agent wallets over x402. Every dataset carries its receipt: the wallet that paid, the price, and the Solana settlement transaction.",
+ "meta_og_description": "Live market data bought by brand-new agent wallets over x402, each with its on-chain receipt.",
+ "meta_og_title": "Data Desk · three.ws",
+ "meta_title": "Data Desk · three.ws",
+ "meta_twitter_description": "Live market data bought by brand-new agent wallets over x402.",
+ "meta_twitter_title": "Data Desk · three.ws",
+ "no_matches": "No matches",
+ "no_matches_body": "No dataset matches your filter.",
+ "runway_lab": "Runway Lab",
+ "see_props": "See the 3D props they bought",
+ "stat_datasets": "Datasets live",
+ "stat_purchases": "Purchases, 24h",
+ "stat_sol": "SOL burned in fees, 24h",
+ "stat_usdc": "USDC recirculated, 24h",
+ "stat_wallets": "Fresh wallets, 24h",
+ "title": "Market data bought by brand-new agent wallets, receipts included",
+ "try_again": "Try again"
+ },
"defi": {
"all_categories": "All categories",
"category": "Category",
diff --git a/public/locales/localized-pages.json b/public/locales/localized-pages.json
index 6cdd73199..3f7358af5 100644
--- a/public/locales/localized-pages.json
+++ b/public/locales/localized-pages.json
@@ -1,6 +1,6 @@
{
"generated": true,
- "count": 357,
+ "count": 358,
"paths": [
"/",
"/3d",
@@ -76,6 +76,7 @@
"/daily",
"/daily-match",
"/dashboard",
+ "/data-desk",
"/defi",
"/demos",
"/demos/agents",
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 702d9fb60..61bbb7803 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 948 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 950 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 948 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 950 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,22 @@
<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="/data-desk">
+ <span class="sm-new-date">Sep 22, 2026</span>
+ <span class="sm-title">Data Desk</span>
+ <span class="sm-path">/data-desk</span>
+ <span class="sm-desc">Live market data bought minute by minute by brand-new agent wallets over x402. Every dataset carries its receipt: the wallet that paid, the price, and the Solana settlement transaction.</span>
+ </a>
+ </li>
+ <li>
+ <a href="/docs/x402-fresh-workers">
+ <span class="sm-new-date">Sep 22, 2026</span>
+ <span class="sm-title">Docs · Fresh-wallet workers</span>
+ <span class="sm-path">/docs/x402-fresh-workers</span>
+ <span class="sm-desc">How the platform mints a brand-new Solana wallet for every x402 purchase, what those wallets buy (3D props for the library, datasets for the data desk), how each wallet is emptied and closed so nothing strands, and where to watch it.</span>
+ </a>
+ </li>
<li>
<a href="/prompts">
<span class="sm-new-date">Sep 20, 2026</span>
@@ -172,22 +188,6 @@
<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>
- <span class="sm-title">Agent Wallet Agreement</span>
- <span class="sm-path">/legal/agent-wallet</span>
- <span class="sm-desc">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.</span>
- </a>
- </li>
- <li>
- <a href="/legal/agreements">
- <span class="sm-new-date">Sep 17, 2026</span>
- <span class="sm-title">Real-Funds Agreements</span>
- <span class="sm-path">/legal/agreements</span>
- <span class="sm-desc">Sign, and review your signatures on, the Terms of Service, Risk Disclosure, and Agent Wallet Agreement required before any real-funds action.</span>
- </a>
- </li>
</ul>
</section>
<nav class="sm-toc" aria-label="Sections">
@@ -205,7 +205,7 @@
</nav>
<section class="sm-section" id="main">
<header>
- <h2>Main<span class="sm-count" data-count>60</span></h2>
+ <h2>Main<span class="sm-count" data-count>61</span></h2>
<p class="sm-section-desc">Entry points into the product.</p>
</header>
<ul class="sm-list">
@@ -293,6 +293,13 @@
<span class="sm-desc">Hundreds of free CC0 3D objects and props: furniture, lighting, electronics, decor. Public domain, no attribution required. Preview live, place it in your room with AR, or download the GLB.</span>
</a>
</li>
+ <li>
+ <a href="/data-desk">
+ <span class="sm-title">Data Desk</span>
+ <span class="sm-path">/data-desk</span>
+ <span class="sm-desc">Live market data bought minute by minute by brand-new agent wallets over x402. Every dataset carries its receipt: the wallet that paid, the price, and the Solana settlement transaction.</span>
+ </a>
+ </li>
<li>
<a href="/forged">
<span class="sm-title">Agent-Forged Gallery</span>
@@ -2597,7 +2604,7 @@
<section class="sm-section" id="learn">
<header>
- <h2>Learn<span class="sm-count" data-count>438</span></h2>
+ <h2>Learn<span class="sm-count" data-count>439</span></h2>
<p class="sm-section-desc">Docs, tutorials, and reference.</p>
</header>
<ul class="sm-list">
@@ -5037,6 +5044,13 @@
<span class="sm-desc">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.</span>
</a>
</li>
+ <li>
+ <a href="/docs/x402-fresh-workers">
+ <span class="sm-title">Docs · Fresh-wallet workers</span>
+ <span class="sm-path">/docs/x402-fresh-workers</span>
+ <span class="sm-desc">How the platform mints a brand-new Solana wallet for every x402 purchase, what those wallets buy (3D props for the library, datasets for the data desk), how each wallet is emptied and closed so nothing strands, and where to watch it.</span>
+ </a>
+ </li>
<li>
<a href="/docs/three-microbuy">
<span class="sm-title">Docs · The $THREE micro-buy loop</span>
diff --git a/scripts/x402-fresh-workers-run.mjs b/scripts/x402-fresh-workers-run.mjs
new file mode 100755
index 000000000..a384605c3
--- /dev/null
+++ b/scripts/x402-fresh-workers-run.mjs
@@ -0,0 +1,80 @@
+#!/usr/bin/env node
+// scripts/x402-fresh-workers-run.mjs
+//
+// Drive the fresh-wallet workers lane locally for N ticks: the same run(ctx)
+// the cron invokes, so what you observe here is exactly what production does.
+// Each tick mints brand-new wallets, funds them from the ring funders, has each
+// pay one real three.ws x402 endpoint, and sweeps every wallet back to zero.
+//
+// It is REAL end to end (no mocks): with the ring env present it moves real
+// USDC and SOL inside the closed loop; without it each tick degrades to a
+// clean, named skip. Use --plan to print what a tick WOULD buy and what the
+// funders must hold, without touching the chain or the database.
+//
+// Usage:
+// node scripts/x402-fresh-workers-run.mjs --plan # no I/O
+// node scripts/x402-fresh-workers-run.mjs [ticks] # default 1 tick
+// X402_FRESH_WORKERS_PER_TICK=1 node scripts/x402-fresh-workers-run.mjs 1
+//
+// Never prints a secret; never funds anything outside the ring.
+
+import { randomUUID } from 'node:crypto';
+
+const args = process.argv.slice(2);
+const plan = args.includes('--plan');
+const ticks = Math.max(1, Number(args.find((a) => /^\d+$/.test(a)) || 1));
+
+function line(s = '') { console.log(s); }
+
+const {
+ freshWorkersConfig, planTickJobs, fundingRequirement, walletSolLamports, RENT_EXEMPT_FALLBACK_LAMPORTS,
+} = await import('../api/_lib/x402/fresh-workers/plan.js');
+const { DATA_JOB_SLUGS, resolveJob } = await import('../api/_lib/x402/fresh-workers/jobs.js');
+
+const cfg = freshWorkersConfig();
+line(`\n=== three.ws x402 fresh-wallet workers (${plan ? 'plan only' : `${ticks} tick(s)`}) ===\n`);
+line(` per tick ${cfg.perTick} wallet(s), forge every ${cfg.forgeEveryNTicks} tick(s), daily cap $${(cfg.dailyCapAtomic / 1e6).toFixed(2)}, tick budget ${cfg.tickBudgetMs} ms`);
+
+if (plan) {
+ const solPerWallet = walletSolLamports({ rentExemptLamports: RENT_EXEMPT_FALLBACK_LAMPORTS, maxPayFeeLamports: cfg.maxPayFeeLamports });
+ for (let t = 1; t <= 3; t++) {
+ const jobs = planTickJobs({ tickSeq: t * cfg.forgeEveryNTicks, perTick: cfg.perTick, forgeEveryNTicks: cfg.forgeEveryNTicks, dataSlugs: DATA_JOB_SLUGS, cursor: (t - 1) * cfg.perTick })
+ .map((p) => resolveJob(p, t));
+ const need = fundingRequirement({ jobs, priceOf: (j) => j.priceAtomic, solPerWalletLamports: solPerWallet });
+ line(`\n forge tick example ${t}:`);
+ for (const j of jobs) line(` ${j.kind.padEnd(5)} ${j.slug.padEnd(20)} $${(j.priceAtomic / 1e6).toFixed(3)} ${j.method} ${j.path}`);
+ line(` funder sends ${(need.solLamports / 1e9).toFixed(6)} SOL (${(solPerWallet / 1e9).toFixed(6)} per wallet + ATA rent, all but ~3 base fees returned) and $${(need.usdcAtomic / 1e6).toFixed(3)} USDC`);
+ }
+ line('');
+ process.exit(0);
+}
+
+let sql = null;
+try {
+ ({ sql } = await import('../api/_lib/db.js'));
+ await sql`SELECT 1`;
+} catch (e) {
+ line(` DB unreachable (${e.message}); the tick cannot record wallets, so it will not fund any.\n`);
+ process.exit(1);
+}
+
+const { run } = await import('../api/_lib/x402/fresh-workers/run.js');
+for (let t = 1; t <= ticks; t++) {
+ const runId = randomUUID();
+ const t0 = Date.now();
+ const out = await run({ sql, origin: process.env.APP_ORIGIN || 'https://three.ws', runId });
+ line(`\n tick ${t}/${ticks} ${Date.now() - t0} ms run ${runId}`);
+ if (out.skipped) {
+ line(` skipped: ${out.reason}${out.error ? ` (${out.error})` : ''}`);
+ continue;
+ }
+ line(` wallets ${out.wallets} paid ${out.paid} failed ${out.failed} closed ${out.closed} sweep_failed ${out.sweep_failed} deferred ${out.deferred} spent $${out.spent_usdc}`);
+ line(` fund tx ${out.fund_signature}`);
+ for (const j of out.jobs || []) {
+ line(` ${j.kind.padEnd(5)} ${j.slug.padEnd(20)} payer ${j.payer}`);
+ line(` paid ${j.paid} $${j.amount_usdc} tx ${j.tx || '-'} stored ${j.stored} state ${j.state} sweep ${j.sweep_tx || '-'}${j.error ? ` error ${j.error}` : ''}`);
+ }
+ if (out.reclaim?.claimed) line(` reclaim: ${JSON.stringify(out.reclaim)}`);
+}
+line('');
+process.exit(0);
diff --git a/src/data-desk.js b/src/data-desk.js
new file mode 100644
index 000000000..7ca9bd6b5
--- /dev/null
+++ b/src/data-desk.js
@@ -0,0 +1,341 @@
+// /data-desk: market data BOUGHT by brand-new agent wallets over x402, each
+// dataset shown with the receipt that paid for it.
+//
+// Feed: GET /api/data-desk (x402_data_desk, newest purchase per dataset plus a
+// ledger of recent purchases and the fresh-wallet lane's statistics). Every
+// card renders the dataset's payload with a renderer chosen by slug, and its
+// provenance: price paid, the paying wallet (always a fresh wallet: minted for
+// this one purchase and closed after), and the Solana settlement signature.
+//
+// The feed is honest by design: no synthetic entries, so before the first
+// purchase settles the page shows the designed empty state instead.
+
+const FEED_URL = '/api/data-desk';
+const REFRESH_MS = 60_000;
+
+const els = {
+ stats: document.querySelector('[data-role="stats"]'),
+ grid: document.querySelector('[data-role="grid"]'),
+ loading: document.querySelector('[data-role="loading"]'),
+ empty: document.querySelector('[data-role="empty"]'),
+ emptySearch: document.querySelector('[data-role="empty-search"]'),
+ error: document.querySelector('[data-role="error"]'),
+ errorMsg: document.querySelector('[data-role="error-msg"]'),
+ search: document.querySelector('[data-role="search"]'),
+ count: document.querySelector('[data-role="count"]'),
+ clearSearch: document.querySelector('[data-role="clear-search"]'),
+ retry: document.querySelector('[data-role="retry"]'),
+ ledgerSection: document.querySelector('[data-role="ledger-section"]'),
+ ledger: document.querySelector('[data-role="ledger"]'),
+};
+
+const state = { datasets: [], recent: [], stats: null, query: '', timer: null };
+
+function escapeHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+const escapeAttr = escapeHtml;
+function show(el, on) { if (el) el.hidden = !on; }
+
+// ── Formatting ────────────────────────────────────────────────────────────────
+
+function fmtUsd(n, { compact = true } = {}) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return null;
+ if (compact && Math.abs(v) >= 1e12) return `$${(v / 1e12).toFixed(2)}T`;
+ if (compact && Math.abs(v) >= 1e9) return `$${(v / 1e9).toFixed(2)}B`;
+ if (compact && Math.abs(v) >= 1e6) return `$${(v / 1e6).toFixed(1)}M`;
+ if (compact && Math.abs(v) >= 1e4) return `$${(v / 1e3).toFixed(0)}K`;
+ if (Math.abs(v) >= 1) return `$${v.toLocaleString(undefined, { maximumFractionDigits: 2 })}`;
+ return `$${v.toPrecision(3)}`;
+}
+function fmtNum(n, digits = 1) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return null;
+ if (Math.abs(v) >= 1e9) return `${(v / 1e9).toFixed(digits)}B`;
+ if (Math.abs(v) >= 1e6) return `${(v / 1e6).toFixed(digits)}M`;
+ if (Math.abs(v) >= 1e3) return `${(v / 1e3).toFixed(digits)}K`;
+ return v.toLocaleString(undefined, { maximumFractionDigits: digits });
+}
+function fmtPct(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return '';
+ const cls = v > 0 ? 'dd-up' : v < 0 ? 'dd-down' : '';
+ return `<span class="${cls}">${v > 0 ? '+' : ''}${v.toFixed(1)}%</span>`;
+}
+function fmtUsdc(n) {
+ if (n == null || !Number.isFinite(Number(n))) return null;
+ const v = Number(n);
+ return v < 0.01 ? `$${v.toFixed(3)}` : `$${v.toFixed(2)}`;
+}
+function fmtWhen(ts) {
+ const d = new Date(ts);
+ if (Number.isNaN(d.getTime())) return '';
+ const mins = Math.round((Date.now() - d.getTime()) / 60000);
+ if (mins < 1) return 'just now';
+ if (mins < 60) return `${mins}m ago`;
+ if (mins < 1440) return `${Math.round(mins / 60)}h ago`;
+ return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+}
+function fmtTime(ts) {
+ const d = new Date(ts);
+ return Number.isNaN(d.getTime()) ? '' : d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
+}
+
+// ── Payload renderers (one per dataset, generic fallback) ────────────────────
+
+const kv = (pairs, cols = 2) => `<div class="dd-kv${cols === 3 ? ' dd-kv--3' : ''}">${pairs
+ .filter(([, v]) => v != null && v !== '')
+ .map(([k, v]) => `<div><div class="dd-k">${escapeHtml(k)}</div><div class="dd-v">${v}</div></div>`)
+ .join('')}</div>`;
+
+const rows = (items, { name, value, delta, max = 5 }) => {
+ const list = (Array.isArray(items) ? items : []).slice(0, max);
+ if (!list.length) return '';
+ return `<div class="dd-rows">${list.map((it, i) => `
+ <div class="dd-row">
+ <span class="dd-row-rank">${i + 1}</span>
+ <span class="dd-row-name" title="${escapeAttr(name(it))}">${escapeHtml(name(it))}</span>
+ ${value ? `<span class="dd-row-val">${value(it) ?? ''}</span>` : ''}
+ ${delta ? `<span class="dd-row-delta">${delta(it) ?? ''}</span>` : ''}
+ </div>`).join('')}</div>`;
+};
+
+const pick = (o, ...keys) => { for (const k of keys) if (o && o[k] != null) return o[k]; return null; };
+
+const RENDERERS = {
+ 'market-global': (p) => {
+ const m = p.market || p.global || p;
+ const fg = p.fear_greed || {};
+ const fgv = Number(fg.value);
+ return kv([
+ ['Market cap', fmtUsd(pick(m, 'total_market_cap', 'market_cap'))],
+ ['24h volume', fmtUsd(pick(m, 'total_volume_24h', 'volume_24h'))],
+ ['Top-coin dominance', m.btc_dominance != null ? `${Number(m.btc_dominance).toFixed(1)}%` : null],
+ ['Fear & Greed', Number.isFinite(fgv) ? `${fgv}<small>${escapeHtml(fg.label || '')}</small>` : null],
+ ]) + (Number.isFinite(fgv) ? `<div class="dd-bar" title="Fear & Greed ${fgv}"><i style="width:${Math.max(2, Math.min(100, fgv))}%"></i></div>` : '');
+ },
+ 'market-pulse': (p) => {
+ const g = p.global || {};
+ const fg = p.fear_greed || {};
+ return kv([
+ ['Market cap', fmtUsd(g.total_market_cap)],
+ ['Top-coin dominance', g.btc_dominance != null ? `${Number(g.btc_dominance).toFixed(1)}%` : null],
+ ['Fear & Greed', fg.value != null ? `${escapeHtml(fg.value)}<small>${escapeHtml(fg.label || '')}</small>` : null],
+ ['DeFi TVL', fmtUsd(p.defi?.total_tvl)],
+ ['Stablecoins', fmtUsd(p.stablecoins?.total_mcap)],
+ ['Gas, standard', p.gas?.standard_gwei != null ? `${Number(p.gas.standard_gwei).toFixed(1)}<small>gwei</small>` : null],
+ ], 3) + rows(p.top_coins, { name: (c) => `${c.symbol || c.id}`, value: (c) => fmtUsd(c.price, { compact: false }), delta: (c) => fmtPct(c.change_24h) });
+ },
+ 'market-trending': (p) => rows(p.coins, {
+ name: (c) => `${c.symbol || c.id}${c.name ? ` · ${c.name}` : ''}`,
+ value: (c) => fmtUsd(pick(c, 'price_usd', 'price'), { compact: false }),
+ delta: (c) => fmtPct(pick(c, 'change_24h_pct', 'change_24h')),
+ }) + (Array.isArray(p.categories) && p.categories.length
+ ? `<div class="dd-k" style="margin-top:6px">Trending categories</div>` + rows(p.categories, { name: (c) => c.name || c.slug, delta: (c) => fmtPct(pick(c, 'mcap_change_1h_pct', 'change_1h')), max: 3 })
+ : ''),
+ 'market-gas': (p) => {
+ const tiers = Array.isArray(p.tiers) ? p.tiers : [];
+ const tier = (k) => tiers.find((t) => t.key === k);
+ const gwei = (t) => (t && t.gas_price_gwei != null ? `${Number(t.gas_price_gwei).toFixed(2)}<small>gwei</small>` : null);
+ const swap = tier('standard')?.actions?.find((a) => a.key === 'swap');
+ return kv([
+ ['Slow', gwei(tier('slow'))], ['Standard', gwei(tier('standard'))], ['Fast', gwei(tier('fast'))],
+ ['Native coin price', fmtUsd(p.eth_price_usd, { compact: false })],
+ ['DEX swap', swap?.usd != null ? fmtUsd(swap.usd, { compact: false }) : null],
+ ], 3);
+ },
+ 'market-defi': (p) => kv([['Total TVL', fmtUsd(pick(p, 'total_tvl', 'totalTvl'))], ['Protocols', p.protocols?.length ?? null]])
+ + rows(p.protocols, { name: (x) => x.name, value: (x) => fmtUsd(x.tvl), delta: (x) => fmtPct(pick(x, 'change_7d', 'change_1d')) }),
+ 'market-stablecoins': (p) => kv([['Total supply', fmtUsd(p.total_mcap)], ['Tracked', p.stablecoins?.length ?? null]])
+ + rows(p.stablecoins, { name: (x) => `${x.symbol || x.name}`, value: (x) => fmtUsd(x.circulating_usd), delta: (x) => (x.price != null ? `<span class="${Math.abs(Number(x.price) - 1) > 0.005 ? 'dd-down' : 'dd-up'}">$${Number(x.price).toFixed(4)}</span>` : '') }),
+ 'market-fees': (p) => kv([['24h fees', fmtUsd(p.total24h)], ['Kind', escapeHtml(p.type || 'fees')]])
+ + rows(p.protocols, { name: (x) => x.name, value: (x) => fmtUsd(x.total24h), delta: (x) => (x.total30d != null ? `<small>30d ${fmtUsd(x.total30d)}</small>` : '') }),
+ 'market-dex-volumes': (p) => kv([['24h DEX volume', fmtUsd(p.total24h)], ['Venues', p.protocols?.length ?? null]])
+ + rows(p.protocols, { name: (x) => x.name, value: (x) => fmtUsd(x.total24h), delta: (x) => (x.share_pct != null ? `${Number(x.share_pct).toFixed(1)}%` : '') }),
+ 'market-hacks': (p) => kv([['Stolen, all time', fmtUsd(p.stats?.total_stolen_all_time)], ['Incidents, 12mo', p.stats?.incidents_12mo ?? null]])
+ + rows(p.hacks, { name: (x) => `${x.name}${x.technique ? ` · ${x.technique}` : ''}`, value: (x) => fmtUsd(x.amount_usd), max: 3 }),
+ 'market-yields': (p) => kv([['Median APY', p.stats?.median_apy != null ? `${Number(p.stats.median_apy).toFixed(2)}%` : null], ['Pools', p.total ?? p.pools?.length ?? null]])
+ + rows(p.pools || p.yields, { name: (x) => `${x.project || x.protocol || ''} ${x.symbol || x.pool || ''}`.trim(), value: (x) => fmtUsd(x.tvl || x.tvlUsd), delta: (x) => (x.apy != null ? `${Number(x.apy).toFixed(1)}%` : '') }),
+ 'market-chains': (p) => rows(p.chains, { name: (x) => x.name, value: (x) => fmtUsd(x.tvl), delta: (x) => fmtPct(pick(x, 'change_7d', 'change_1d')) }),
+ 'market-coins': (p) => rows(p.coins, { name: (c) => `${c.symbol}${c.name ? ` · ${c.name}` : ''}`, value: (c) => fmtUsd(c.price, { compact: false }), delta: (c) => fmtPct(c.change_24h), max: 6 }),
+};
+
+// Generic renderer for datasets without a bespoke layout: the first few scalar
+// fields as tiles and the first array as ranked rows, labels guessed from the
+// usual field names. It never throws and never renders an empty box.
+function renderGeneric(p) {
+ if (p == null || typeof p !== 'object') return kv([['Value', escapeHtml(String(p))]]);
+ const scalars = [];
+ let firstArray = null;
+ for (const [k, v] of Object.entries(p)) {
+ if (v == null) continue;
+ if (Array.isArray(v)) { if (!firstArray && v.length && typeof v[0] === 'object') firstArray = v; continue; }
+ if (typeof v === 'object') {
+ for (const [k2, v2] of Object.entries(v)) {
+ if (['number', 'string', 'boolean'].includes(typeof v2) && scalars.length < 6) scalars.push([`${k} ${k2}`, v2]);
+ }
+ continue;
+ }
+ if (scalars.length < 6) scalars.push([k, v]);
+ }
+ const fmt = (k, v) => {
+ if (typeof v === 'number') return /usd|cap|volume|tvl|price|fees|amount/i.test(k) ? fmtUsd(v) : /pct|percent|change|dominance/i.test(k) ? fmtPct(v) : fmtNum(v, 2);
+ if (typeof v === 'boolean') return v ? 'yes' : 'no';
+ return escapeHtml(String(v).slice(0, 40));
+ };
+ const tiles = kv(scalars.map(([k, v]) => [k.replace(/_/g, ' '), fmt(k, v)]));
+ const list = firstArray
+ ? rows(firstArray, {
+ name: (x) => String(pick(x, 'name', 'title', 'headline', 'symbol', 'id', 'slug', 'label', 'protocol') ?? JSON.stringify(x).slice(0, 40)),
+ value: (x) => { const v = pick(x, 'price', 'value', 'score', 'tvl', 'amount_usd', 'total24h', 'volume_24h', 'market_cap'); return typeof v === 'number' ? fmtUsd(v) : v != null ? escapeHtml(String(v).slice(0, 18)) : ''; },
+ delta: (x) => { const v = pick(x, 'change_24h', 'change_24h_pct', 'change_7d', 'sentiment'); return typeof v === 'number' ? fmtPct(v) : v != null ? escapeHtml(String(v).slice(0, 10)) : ''; },
+ })
+ : '';
+ return tiles + list || kv([['Fields', escapeHtml(Object.keys(p).slice(0, 6).join(', '))]]);
+}
+
+function renderPayload(slug, payload) {
+ try {
+ const out = RENDERERS[slug] ? RENDERERS[slug](payload || {}) : '';
+ return out && out.replace(/<div class="dd-kv[^"]*"><\/div>/g, '').trim() ? out : renderGeneric(payload);
+ } catch {
+ return renderGeneric(payload);
+ }
+}
+
+// ── Cards, stats, ledger ──────────────────────────────────────────────────────
+
+function renderCard(d) {
+ const card = document.createElement('article');
+ card.className = 'dd-card';
+ card.dataset.slug = d.slug;
+ const price = fmtUsdc(d.price_usdc);
+ card.innerHTML = `
+ <div class="dd-card-head">
+ <h3 class="dd-card-title">${escapeHtml(d.title)}</h3>
+ <span class="dd-card-age" title="${escapeAttr(new Date(d.ts).toLocaleString())}">${escapeHtml(fmtWhen(d.ts))}</span>
+ </div>
+ ${d.blurb ? `<p class="dd-card-blurb">${escapeHtml(d.blurb)}</p>` : ''}
+ ${renderPayload(d.slug, d.payload)}
+ <div class="dd-receipt" title="This dataset was bought by a brand-new agent wallet with real USDC on Solana">
+ <span class="dd-receipt-amount">${price ? `${escapeHtml(price)} USDC` : 'settling'}</span>
+ <span class="dd-receipt-payer" title="${escapeAttr(d.payer || '')}">${escapeHtml(d.payer_short || 'fresh wallet')}</span>
+ <span class="dd-receipt-fresh" title="Minted for this one purchase and closed right after">fresh wallet</span>
+ ${d.explorer_url ? `<a class="dd-receipt-tx" href="${escapeAttr(d.explorer_url)}" target="_blank" rel="noopener noreferrer" title="View the settlement transaction on Solscan">receipt ↗</a>` : ''}
+ </div>
+ <div class="dd-card-actions">
+ <a class="dd-btn" href="${escapeAttr(`${FEED_URL}?slug=${encodeURIComponent(d.slug)}`)}" title="Every purchase of this dataset, newest first, as JSON">History</a>
+ <a class="dd-btn" href="${escapeAttr(`/api/x402${d.endpoint_path.replace(/^\/api\/x402/, '')}`)}" title="The paid endpoint this was bought from (answers 402 without payment)">Endpoint</a>
+ </div>
+ `;
+ return card;
+}
+
+function renderStats() {
+ if (!els.stats) return;
+ const s = state.stats;
+ if (!s) return;
+ const lane = s.lane?.last_24h || {};
+ const tiles = [
+ ['Datasets live', String(s.datasets_live ?? 0), 'newest purchase of each'],
+ ['Purchases, 24h', String(s.purchases_24h ?? 0), s.latest_ts ? `latest ${fmtWhen(s.latest_ts)}` : ''],
+ ['Fresh wallets, 24h', String(lane.wallets_closed ?? 0), `${lane.jobs_paid ?? 0} paid · ${lane.forge_jobs ?? 0} props`],
+ ['USDC recirculated, 24h', fmtUsdc(lane.spent_usdc ?? 0) || '$0', 'back to the treasury'],
+ ['SOL burned in fees, 24h', `${Number(lane.sol_fees ?? 0).toFixed(4)} SOL`, `rent recycled ${Number(lane.rent_recycled_sol ?? 0).toFixed(3)} SOL`],
+ ];
+ els.stats.innerHTML = tiles.map(([label, value, sub]) => `
+ <div class="dd-stat">
+ <div class="dd-stat-label">${escapeHtml(label)}</div>
+ <div class="dd-stat-value">${escapeHtml(value)}</div>
+ ${sub ? `<div class="dd-stat-sub">${escapeHtml(sub)}</div>` : ''}
+ </div>`).join('');
+}
+
+function renderLedger() {
+ if (!els.ledger) return;
+ const list = state.recent.slice(0, 30);
+ show(els.ledgerSection, list.length > 0);
+ if (!list.length) return;
+ els.ledger.innerHTML = `
+ <div class="dd-ledger-row dd-ledger-head" role="row">
+ <span role="columnheader">Time</span><span role="columnheader">Dataset</span><span role="columnheader">Wallet</span><span role="columnheader">Price</span><span class="dd-ledger-tx" role="columnheader">Receipt</span>
+ </div>` + list.map((r) => `
+ <div class="dd-ledger-row" role="row">
+ <span class="dd-ledger-cell dd-mono" role="cell" title="${escapeAttr(new Date(r.ts).toLocaleString())}">${escapeHtml(fmtTime(r.ts))}</span>
+ <span class="dd-ledger-cell" role="cell">${escapeHtml(r.title)}</span>
+ <span class="dd-ledger-cell dd-mono" role="cell" title="${escapeAttr(r.payer || '')}">${escapeHtml(r.payer_short || '')}</span>
+ <span class="dd-ledger-cell dd-mono" role="cell">${escapeHtml(fmtUsdc(r.price_usdc) || '')}</span>
+ <span class="dd-ledger-cell dd-ledger-tx" role="cell">${r.explorer_url ? `<a href="${escapeAttr(r.explorer_url)}" target="_blank" rel="noopener noreferrer">Solscan ↗</a>` : ''}</span>
+ </div>`).join('');
+}
+
+function filtered() {
+ const q = state.query.trim().toLowerCase();
+ if (!q) return state.datasets;
+ return state.datasets.filter((d) => `${d.title} ${d.blurb || ''} ${d.slug}`.toLowerCase().includes(q));
+}
+
+function render() {
+ const list = filtered();
+ show(els.loading, false);
+ show(els.error, false);
+ if (!state.datasets.length) {
+ show(els.grid, false); show(els.emptySearch, false); show(els.empty, true);
+ if (els.count) els.count.textContent = '';
+ return;
+ }
+ show(els.empty, false);
+ show(els.emptySearch, list.length === 0);
+ show(els.grid, list.length > 0);
+ els.grid.replaceChildren(...list.map(renderCard));
+ if (els.count) els.count.textContent = state.query ? `${list.length} of ${state.datasets.length} datasets` : `${state.datasets.length} datasets`;
+}
+
+async function load({ silent = false } = {}) {
+ if (!silent) {
+ show(els.loading, true); show(els.grid, false); show(els.empty, false); show(els.emptySearch, false); show(els.error, false);
+ }
+ try {
+ const res = await fetch(FEED_URL, { headers: { accept: 'application/json' } });
+ if (!res.ok) {
+ let detail = `HTTP ${res.status}`;
+ try { const body = await res.json(); detail = body?.error_description || body?.error || detail; } catch { /* keep the status */ }
+ throw new Error(detail);
+ }
+ const body = await res.json();
+ state.datasets = Array.isArray(body.datasets) ? body.datasets : [];
+ state.recent = Array.isArray(body.recent) ? body.recent : [];
+ state.stats = body.stats || null;
+ renderStats();
+ render();
+ renderLedger();
+ } catch (err) {
+ if (silent && state.datasets.length) return;
+ show(els.loading, false); show(els.grid, false); show(els.empty, false); show(els.emptySearch, false);
+ if (els.errorMsg) els.errorMsg.textContent = err?.message || 'network error';
+ show(els.error, true);
+ }
+}
+
+function schedule() {
+ clearInterval(state.timer);
+ state.timer = setInterval(() => { if (!document.hidden) load({ silent: true }); }, REFRESH_MS);
+}
+
+els.search?.addEventListener('input', () => { state.query = els.search.value; render(); });
+els.clearSearch?.addEventListener('click', () => { if (els.search) els.search.value = ''; state.query = ''; render(); els.search?.focus(); });
+els.retry?.addEventListener('click', () => load());
+document.addEventListener('keydown', (e) => {
+ if (e.key === '/' && document.activeElement !== els.search && !/input|textarea|select/i.test(document.activeElement?.tagName || '')) {
+ e.preventDefault();
+ els.search?.focus();
+ } else if (e.key === 'Escape' && document.activeElement === els.search) {
+ els.search.value = ''; state.query = ''; render();
+ }
+});
+document.addEventListener('visibilitychange', () => { if (!document.hidden) load({ silent: true }); });
+
+load();
+schedule();
diff --git a/src/forged-gallery.js b/src/forged-gallery.js
index 98ac68d75..b9a3e0fb2 100644
--- a/src/forged-gallery.js
+++ b/src/forged-gallery.js
@@ -96,6 +96,7 @@ function renderCard(p) {
<div class="fg-receipt" title="This asset was bought by an autonomous agent with real USDC on Solana">
<span class="fg-receipt-amount">${price ? `${escapeHtml(price)} USDC` : 'settling'}</span>
<span class="fg-receipt-payer">${escapeHtml(p.payer_short || 'agent wallet')}</span>
+ ${p.payer_kind === 'fresh' ? '<span class="fg-receipt-fresh" title="Bought by a wallet minted for this one purchase and closed right after">fresh wallet</span>' : ''}
${p.explorer_url ? `<a class="fg-receipt-tx" href="${escapeAttr(p.explorer_url)}" target="_blank" rel="noopener noreferrer" title="View the settlement transaction on Solscan">receipt ↗</a>` : ''}
</div>
${previewUrl ? `
diff --git a/tests/x402-fresh-workers.test.js b/tests/x402-fresh-workers.test.js
new file mode 100644
index 000000000..e73535484
--- /dev/null
+++ b/tests/x402-fresh-workers.test.js
@@ -0,0 +1,187 @@
+// Tests for the x402 fresh-wallet workers lane: the pure planning module
+// (api/_lib/x402/fresh-workers/plan.js), the job catalog's binding to the ring
+// catalog (jobs.js), and the wiring that makes the lane actually run
+// (economy-tick TARGETS, the direct cron handler file). No DB, no chain.
+//
+// What these lock down:
+// • config gates: defaults, the kill switch, junk-tolerant parsing.
+// • the SOL a fresh wallet is given is exactly rent-exemption + two fees.
+// • the tick plan: a forge job on every Nth tick, datasets in rotation,
+// per-tick zero buys nothing, the daily cap trims in order.
+// • funding math + funder headroom never dip under the sponsor floor.
+// • the sweep drains a wallet to exactly zero.
+// • reclaim verdicts: wait / sweep / stranded / skip.
+// • every data job resolves against the ring catalog with a positive price.
+// • the forge prompt walk changes with the seed.
+// • the lane is fired by the economy heartbeat and has a routable handler.
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { readFileSync, existsSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+import {
+ freshWorkersConfig, walletSolLamports, planTickJobs, fitJobsToBudget, fundingRequirement,
+ funderHeadroom, sweepAmountLamports, classifyReclaim, trimPayload,
+ RENT_EXEMPT_FALLBACK_LAMPORTS, ATA_RENT_LAMPORTS, BASE_FEE_LAMPORTS,
+} from '../api/_lib/x402/fresh-workers/plan.js';
+import { DATA_JOBS, DATA_JOB_SLUGS, resolveDataJob, resolveForgeJob, resolveJob } from '../api/_lib/x402/fresh-workers/jobs.js';
+import { forgePropForSeed } from '../api/_lib/x402/pipelines/forge-content.js';
+import { bySlug } from '../api/_lib/x402/ring-catalog.js';
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+const ENV_KEYS = [
+ 'X402_FRESH_WORKERS_ENABLED', 'X402_FRESH_WORKERS_PER_TICK', 'X402_FRESH_WORKERS_FORGE_EVERY_N_TICKS',
+ 'X402_FRESH_WORKERS_DAILY_CAP_ATOMIC', 'X402_FRESH_WORKERS_TICK_BUDGET_MS', 'X402_FRESH_WORKERS_RECLAIM_AFTER_S',
+ 'X402_FRESH_WORKERS_MAX_SWEEP_ATTEMPTS', 'X402_FRESH_WORKERS_MEMBERSHIP_HOURS', 'X402_RING_MAX_FEE_PER_TX_LAMPORTS',
+];
+
+describe('fresh workers config', () => {
+ const saved = {};
+ beforeEach(() => { for (const k of ENV_KEYS) { saved[k] = process.env[k]; delete process.env[k]; } });
+ afterEach(() => { for (const k of ENV_KEYS) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } });
+
+ it('is on by default and only "false" turns it off', () => {
+ expect(freshWorkersConfig({}).enabled).toBe(true);
+ expect(freshWorkersConfig({ X402_FRESH_WORKERS_ENABLED: 'FALSE' }).enabled).toBe(false);
+ expect(freshWorkersConfig({ X402_FRESH_WORKERS_ENABLED: '0' }).enabled).toBe(true);
+ });
+
+ it('has sane defaults and tolerates junk', () => {
+ const d = freshWorkersConfig({});
+ expect(d.perTick).toBe(3);
+ expect(d.forgeEveryNTicks).toBe(10);
+ expect(d.dailyCapAtomic).toBe(40_000_000);
+ expect(d.tickBudgetMs).toBe(50_000);
+ expect(d.reclaimAfterS).toBe(90);
+ expect(d.maxSweepAttempts).toBe(20);
+ expect(d.membershipWindowHours).toBe(36);
+ const j = freshWorkersConfig({ X402_FRESH_WORKERS_PER_TICK: 'abc', X402_FRESH_WORKERS_FORGE_EVERY_N_TICKS: '0', X402_FRESH_WORKERS_TICK_BUDGET_MS: '1' });
+ expect(j.perTick).toBe(3);
+ expect(j.forgeEveryNTicks).toBe(1);
+ expect(j.tickBudgetMs).toBe(10_000);
+ });
+});
+
+describe('wallet SOL budget', () => {
+ it('is rent exemption plus the worst-case pay fee plus the sweep fee', () => {
+ expect(walletSolLamports({ rentExemptLamports: RENT_EXEMPT_FALLBACK_LAMPORTS, maxPayFeeLamports: 10_000 }))
+ .toBe(890_880 + 10_000 + BASE_FEE_LAMPORTS);
+ });
+});
+
+describe('tick plan', () => {
+ const slugs = ['a', 'b', 'c', 'd'];
+ it('puts the forge job first on every Nth tick and fills with datasets in rotation', () => {
+ expect(planTickJobs({ tickSeq: 10, perTick: 3, forgeEveryNTicks: 10, dataSlugs: slugs, cursor: 0 }))
+ .toEqual([{ kind: 'forge', slug: 'forge' }, { kind: 'data', slug: 'a' }, { kind: 'data', slug: 'b' }]);
+ expect(planTickJobs({ tickSeq: 11, perTick: 3, forgeEveryNTicks: 10, dataSlugs: slugs, cursor: 2 }))
+ .toEqual([{ kind: 'data', slug: 'c' }, { kind: 'data', slug: 'd' }, { kind: 'data', slug: 'a' }]);
+ });
+ it('buys nothing at per-tick zero and never exceeds per-tick', () => {
+ expect(planTickJobs({ tickSeq: 10, perTick: 0, forgeEveryNTicks: 10, dataSlugs: slugs, cursor: 0 })).toEqual([]);
+ expect(planTickJobs({ tickSeq: 10, perTick: 1, forgeEveryNTicks: 10, dataSlugs: slugs, cursor: 0 })).toEqual([{ kind: 'forge', slug: 'forge' }]);
+ });
+ it('trims to the daily cap in order and reports what it dropped', () => {
+ const jobs = [{ p: 150_000 }, { p: 1_000 }, { p: 1_000 }];
+ const fit = fitJobsToBudget({ jobs, priceOf: (j) => j.p, dailySpentAtomic: 39_900_000, dailyCapAtomic: 40_000_000 });
+ expect(fit.kept).toEqual([{ p: 1_000 }, { p: 1_000 }]);
+ expect(fit.dropped).toEqual([{ p: 150_000 }]);
+ expect(fit.remainingAtomic).toBe(98_000);
+ });
+});
+
+describe('funding math', () => {
+ it('sums one job price per wallet in USDC and per-wallet SOL plus ATA rent plus one tx fee', () => {
+ const need = fundingRequirement({ jobs: [{ p: 1_000 }, { p: 150_000 }], priceOf: (j) => j.p, solPerWalletLamports: 905_880 });
+ expect(need.wallets).toBe(2);
+ expect(need.usdcAtomic).toBe(151_000);
+ expect(need.solLamports).toBe(2 * (905_880 + ATA_RENT_LAMPORTS) + BASE_FEE_LAMPORTS);
+ expect(fundingRequirement({ jobs: [], priceOf: () => 0, solPerWalletLamports: 1 }).solLamports).toBe(0);
+ });
+ it('never lets the funder dip under the sponsor floor', () => {
+ expect(funderHeadroom({ balanceLamports: 10_000_000, floorLamports: 2_000_000, needLamports: 8_000_000 })).toEqual({ ok: true, spendable: 8_000_000, shortfall: 0 });
+ expect(funderHeadroom({ balanceLamports: 10_000_000, floorLamports: 2_000_000, needLamports: 8_000_001 })).toEqual({ ok: false, spendable: 8_000_000, shortfall: 1 });
+ expect(funderHeadroom({ balanceLamports: 1_000_000, floorLamports: 2_000_000, needLamports: 1 }).ok).toBe(false);
+ });
+ it('the sweep sends everything but the base fee, ending at zero', () => {
+ expect(sweepAmountLamports({ balanceLamports: 900_880 })).toBe(895_880);
+ expect(sweepAmountLamports({ balanceLamports: 4_000 })).toBe(0);
+ });
+});
+
+describe('reclaim verdicts', () => {
+ const base = { attempts: 0, nowMs: 1_000_000, reclaimAfterS: 90, maxSweepAttempts: 20 };
+ it('skips terminal and just-minted rows', () => {
+ for (const state of ['closed', 'fund_failed', 'stranded', 'minted']) {
+ expect(classifyReclaim({ ...base, state, updatedAtMs: 0 })).toBe('skip');
+ }
+ });
+ it('waits on rows a live tick still owns, sweeps stale ones, strands exhausted ones', () => {
+ expect(classifyReclaim({ ...base, state: 'paid', updatedAtMs: 1_000_000 - 30_000 })).toBe('wait');
+ expect(classifyReclaim({ ...base, state: 'paid', updatedAtMs: 1_000_000 - 120_000 })).toBe('sweep');
+ expect(classifyReclaim({ ...base, state: 'sweep_failed', updatedAtMs: 0, attempts: 20 })).toBe('stranded');
+ });
+});
+
+describe('payload trimming', () => {
+ it('bounds arrays and keeps scalars', () => {
+ const big = { total: 1, items: Array.from({ length: 200 }, (_, i) => ({ i })), nested: { list: Array.from({ length: 100 }, (_, i) => i) } };
+ const t = trimPayload(big, { maxItems: 40 });
+ expect(t.total).toBe(1);
+ expect(t.items).toHaveLength(40);
+ expect(t.nested.list).toHaveLength(40);
+ });
+ it('falls back to a key list when even the trimmed form is too large', () => {
+ const huge = { blob: 'x'.repeat(100_000) };
+ expect(trimPayload(huge, { maxBytes: 1_000 })).toEqual({ truncated: true, keys: ['blob'] });
+ expect(trimPayload(null)).toEqual({ value: null });
+ });
+});
+
+describe('job catalog', () => {
+ it('every data job is a real ring-catalog entry with a positive price and a resolvable request', () => {
+ expect(new Set(DATA_JOB_SLUGS).size).toBe(DATA_JOB_SLUGS.length);
+ for (const j of DATA_JOBS) {
+ expect(bySlug(j.slug), `ring catalog lacks ${j.slug}`).toBeTruthy();
+ const r = resolveDataJob(j.slug);
+ expect(['GET', 'POST']).toContain(r.method);
+ expect(r.path.startsWith('/api/x402/')).toBe(true);
+ expect(r.priceAtomic).toBeGreaterThan(0);
+ expect(r.title).toBe(j.title);
+ if (r.method === 'GET') expect(r.body).toBeNull();
+ }
+ expect(() => resolveDataJob('no-such-job')).toThrow(/unknown data job/);
+ });
+ it('the forge job buys a standard-tier generation with a seed-dependent prompt', () => {
+ const a = resolveForgeJob(1);
+ const b = resolveForgeJob(2);
+ expect(a.kind).toBe('forge');
+ expect(a.path).toBe('/api/x402/forge');
+ expect(a.body.tier).toBe('standard');
+ expect(a.priceAtomic).toBe(150_000);
+ expect(a.body.prompt).not.toBe(b.body.prompt);
+ expect(resolveForgeJob(7).body.prompt).toBe(resolveForgeJob(7).body.prompt);
+ expect(resolveJob({ kind: 'data', slug: 'market-global' }, 1).slug).toBe('market-global');
+ });
+ it('the seeded prop walk covers more than one category', () => {
+ const cats = new Set(Array.from({ length: 40 }, (_, i) => forgePropForSeed(i).category));
+ expect(cats.size).toBeGreaterThan(1);
+ });
+});
+
+describe('wiring', () => {
+ it('the economy heartbeat fires the lane and the handler file exists', () => {
+ const tick = readFileSync(join(ROOT, 'api/cron/economy-tick.js'), 'utf8');
+ expect(tick).toMatch(/path: '\/api\/cron\/x402-fresh-workers'/);
+ expect(existsSync(join(ROOT, 'api/cron/x402-fresh-workers.js'))).toBe(true);
+ });
+ it('the migration and the code-side DDL guard declare the same tables', () => {
+ const sql = readFileSync(join(ROOT, 'api/_lib/migrations/20260922100000_x402_fresh_workers.sql'), 'utf8');
+ expect(sql).toMatch(/CREATE TABLE IF NOT EXISTS x402_fresh_wallets/);
+ expect(sql).toMatch(/CREATE TABLE IF NOT EXISTS x402_data_desk/);
+ const wallets = readFileSync(join(ROOT, 'api/_lib/x402/fresh-workers/wallets.js'), 'utf8');
+ expect(wallets).toMatch(/CREATE TABLE IF NOT EXISTS x402_fresh_wallets/);
+ });
+});
diff --git a/vite.config.js b/vite.config.js
index 3f0847830..98cf8a09b 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -793,6 +793,7 @@ const appConfig = {
mine: resolve(__dirname, 'pages/mine.html'),
pulse: resolve(__dirname, 'pages/pulse.html'),
'economy-lab': resolve(__dirname, 'pages/economy-lab.html'),
+ 'data-desk': resolve(__dirname, 'pages/data-desk.html'),
flow: resolve(__dirname, 'pages/flow.html'),
symphony: resolve(__dirname, 'pages/symphony.html'),
diorama: resolve(__dirname, 'pages/diorama.html'),