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.

chore: finish character-studio lint burndown; close ISSUES.md item

miniaturization906dac7d14ce
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 000000000..8cb85b8f5
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,82 @@
+name: CI
+
+# Merge gate for three.ws. Real money rides on this code, so every PR and every
+# push to main must clear the checks below before it can land. Jobs run in
+# parallel; the slowest (unit tests) gates the rest.
+on:
+ pull_request:
+ push:
+ branches: [main]
+
+# A newer push to the same branch/PR cancels the in-flight run — no point
+# spending CI minutes on a commit that's already superseded.
+concurrency:
+ group: ci-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+jobs:
+ lint:
+ name: Lint
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ cache: npm
+ - run: npm ci
+ # eslint exits non-zero on any error. Pre-existing warnings are allowed
+ # for now; the bar is "no new errors". Tighten with --max-warnings once
+ # the warning backlog is burned down.
+ - run: npx eslint .
+
+ test:
+ name: Unit tests
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ cache: npm
+ - run: npm ci
+ - run: npx vitest run
+
+ guards:
+ name: Source guards
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ cache: npm
+ - run: npm ci
+ # Fail if `npx vercel build` ever clobbered an api/*.js source file with
+ # an esbuild bundle (a documented footgun in this repo).
+ - run: node scripts/check-api-not-bundled.mjs
+ # Regenerates and validates the public changelog/page index; the script
+ # fails the build on a malformed changelog entry. Run as a validation
+ # gate only — the generated changelog.json is not byte-deterministic, so
+ # a committed-artifact diff check would be flaky and is intentionally
+ # omitted until the generator emits stable output.
+ - run: npm run build:pages
+
+ typecheck:
+ name: Typecheck (advisory)
+ runs-on: ubuntu-latest
+ # Advisory until the JSDoc type backlog is cleared — surfaces type signal on
+ # every PR without blocking merge. Flip `continue-on-error` to false to make
+ # it a hard gate once `npm run typecheck` is clean.
+ continue-on-error: true
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ cache: npm
+ - run: npm ci
+ - run: npm run typecheck
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3af5e7ba3..14befa826 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **$THREE holder leaderboard loads faster from a shared snapshot** — The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces. (`/leaderboard`) `[improvement, infra]`
- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice. (`/three-token`) `[feature]`
- **forge_avatar — one call turns a prompt into a rigged, animation-ready avatar** — A new forge_avatar MCP tool collapses the old two-step flow (generate a mesh, then rig it) into a single call: describe a character in text — or pass reference images — and it generates the textured model, auto-rigs it with a humanoid skeleton, and returns an animation-ready GLB that drops straight into the pose studio and plays the idle/walk library. A built-in humanoid check runs first, so a non-character prompt (furniture, a vehicle, an animal) is turned away with no charge instead of wasting a paid rig. It bundles generation and rigging at their combined price ($0.45) with no hidden markup, and you are never charged if no rigged avatar is produced. (`/docs/mcp`) `[sdk, feature]`
+- **Free photo → 3D is now a one-click engine in Forge** — Turning a photo into a 3D model is free — and now you can pick it directly. Forge's engine selector has a new 'Hunyuan3D / TRELLIS' lane marked with a FREE badge that reconstructs your uploaded photo (or 2–4 angles) into a textured GLB at no cost and with no API key, running on community GPU Spaces with automatic failover across Hunyuan3D, TRELLIS, and TripoSR. Until now the free photo lane only kicked in behind the scenes; it's a first-class choice in the picker, shows live availability, and never silently falls back to a paid engine. The FREE badge also marks every other no-cost lane so you can always see which engines cost nothing. (`/forge`) `[feature, improvement]`
- **Solana is now the default payment network** — Solana is now the default everywhere you pick a chain — the dashboard's Default payment network setting, x402 merchant settlement, and the monetization payout wallet all default to Solana for every user, with Solana listed first. Base and Polygon remain available if you prefer an EVM chain. (`/dashboard`) `[improvement]`
## 2026-06-20
diff --git a/api/_lib/avatar-wallet.js b/api/_lib/avatar-wallet.js
index 5a44cc626..84ad1291c 100644
--- a/api/_lib/avatar-wallet.js
+++ b/api/_lib/avatar-wallet.js
@@ -22,6 +22,7 @@ import {
TransactionInstruction,
} from '@solana/web3.js';
import { solanaConnection } from './solana/connection.js';
+import { confirmOrThrow } from './solana/confirm.js';
import bs58 from 'bs58';
const bs58decode = bs58.default ? bs58.default.decode : bs58.decode;
@@ -201,7 +202,7 @@ export async function sendSol({ connection, fromKeypair, to, lamports, memo }) {
skipPreflight: false,
maxRetries: 3,
});
- await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');
+ await confirmOrThrow(connection, { signature, blockhash, lastValidBlockHeight }, 'confirmed');
return signature;
}
diff --git a/api/_lib/club/payouts.js b/api/_lib/club/payouts.js
index fc37f4e20..42a10f074 100644
--- a/api/_lib/club/payouts.js
+++ b/api/_lib/club/payouts.js
@@ -21,6 +21,7 @@ import {
ComputeBudgetProgram,
} from '@solana/web3.js';
import { solanaConnection } from '../solana/connection.js';
+import { confirmOrThrow } from '../solana/confirm.js';
import {
getAssociatedTokenAddress,
createAssociatedTokenAccountInstruction,
@@ -96,7 +97,7 @@ export async function sendClubUsdcSolana({ recipient, amount }) {
async function confirmWithTimeout(connection, signature, { blockhash, lastValidBlockHeight }) {
const start = Date.now();
try {
- await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');
+ await confirmOrThrow(connection, { signature, blockhash, lastValidBlockHeight }, 'confirmed');
return;
} catch {
while (Date.now() - start < SEND_TIMEOUT_MS) {
diff --git a/api/_lib/coin/creator-fees.js b/api/_lib/coin/creator-fees.js
index 6d5ad953e..6a5af89fc 100644
--- a/api/_lib/coin/creator-fees.js
+++ b/api/_lib/coin/creator-fees.js
@@ -26,6 +26,7 @@ import {
import { NATIVE_MINT, getAssociatedTokenAddressSync, createCloseAccountInstruction } from '@solana/spl-token';
import { getConnection, getPumpSdk, solanaPubkey } from '../pump.js';
+import { confirmOrThrow } from '../solana/confirm.js';
const PRIORITY_MICRO_LAMPORTS = 100_000;
@@ -96,7 +97,7 @@ export async function claimCreatorFees({ coin, coinCreator, treasury }) {
skipPreflight: false,
maxRetries: 5,
});
- await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
+ await confirmOrThrow(connection, { signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
// Attempt the unwrap as a follow-up tx (best-effort).
if (creatorWsolAta) {
diff --git a/api/_lib/coin/treasury.js b/api/_lib/coin/treasury.js
index 926fb9741..cba9bc425 100644
--- a/api/_lib/coin/treasury.js
+++ b/api/_lib/coin/treasury.js
@@ -20,6 +20,7 @@
import { Keypair, PublicKey, SystemProgram, Transaction, ComputeBudgetProgram } from '@solana/web3.js';
import { getConnection } from '../pump.js';
+import { confirmOrThrow } from '../solana/confirm.js';
import { decryptSecret, isEncryptedSecret } from '../secret-box.js';
const SOL_LAMPORTS = 1_000_000_000n;
@@ -97,7 +98,8 @@ async function confirmWithTimeout(connection, signature, { commitment = 'confirm
// to polling getSignatureStatus.
try {
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash(commitment);
- await connection.confirmTransaction(
+ await confirmOrThrow(
+ connection,
{ signature, blockhash, lastValidBlockHeight },
commitment,
);
diff --git a/api/_lib/forge-health.js b/api/_lib/forge-health.js
index f1cd9204e..614441b77 100644
--- a/api/_lib/forge-health.js
+++ b/api/_lib/forge-health.js
@@ -105,6 +105,35 @@ async function probeNvidia() {
return result(id, 'ok', 'NVIDIA NIM accepted authentication; the free lane is live.', { latency_ms: latency });
}
+// Hugging Face Spaces (the free `huggingface` image→3D lane): a whoami-v2
+// lookup authenticates the token without touching a Space — no GPU, no queue,
+// no billable work. 200 proves the token is live; 401/403 means a submit would
+// be rejected. We can't cheaply probe Space queue depth, so an authenticated
+// token reports ok with the honest caveat that queue waits vary.
+const HF_WHOAMI_URL = 'https://huggingface.co/api/whoami-v2';
+
+async function probeHuggingFace() {
+ const id = 'huggingface';
+ const token = readEnv('HF_TOKEN');
+ if (!token) return result(id, 'unconfigured', 'HF_TOKEN is not set on this deployment.');
+ const started = Date.now();
+ const res = await probeFetch(HF_WHOAMI_URL, {
+ headers: { authorization: `Bearer ${token}` },
+ });
+ const latency = Date.now() - started;
+ if (!res) return result(id, 'down', 'Hugging Face is unreachable.', { latency_ms: latency });
+ if (res.status === 401 || res.status === 403) {
+ return result(id, 'down', 'Hugging Face rejected the platform token.', { http_status: res.status, latency_ms: latency });
+ }
+ if (res.status === 429) {
+ return result(id, 'degraded', 'Hugging Face is rate-limiting — the free Spaces may queue.', { http_status: res.status, latency_ms: latency });
+ }
+ if (res.ok) {
+ return result(id, 'ok', 'Hugging Face accepted the token; the free Spaces lane is reachable (queue waits vary).', { latency_ms: latency });
+ }
+ return result(id, 'down', `Hugging Face returned an unexpected HTTP ${res.status}.`, { http_status: res.status, latency_ms: latency });
+}
+
// Self-hosted Cloud Run workers (Hunyuan3D, TripoSG): an authenticated GET
// against the service root. Cloud Run answers anything <500 when the
// container is up and routable.
@@ -136,6 +165,7 @@ function byokResult(id) {
const PROBES = {
nvidia: probeNvidia,
+ huggingface: probeHuggingFace,
trellis: probeReplicate,
hunyuan3d: gcpWorkerProbe('hunyuan3d', 'GCP_HUNYUAN3D_URL'),
triposg: gcpWorkerProbe('triposg', 'GCP_TRIPOSG_URL'),
diff --git a/api/_lib/forge-tiers.js b/api/_lib/forge-tiers.js
index 51c069bec..fa3c303cf 100644
--- a/api/_lib/forge-tiers.js
+++ b/api/_lib/forge-tiers.js
@@ -120,6 +120,29 @@ export const BACKENDS = Object.freeze({
free: true,
blurb: 'Free TRELLIS generation on NVIDIA NIM — the default lane for text prompts at draft and standard tiers; no vendor cost. Photo input uses the standing engine.',
}),
+ huggingface: Object.freeze({
+ id: 'huggingface',
+ label: 'Hunyuan3D / TRELLIS (free)',
+ vendor: 'Hugging Face Spaces',
+ paths: Object.freeze(['image']),
+ byok: false,
+ provider: 'huggingface',
+ requiresEnv: Object.freeze(['HF_TOKEN']),
+ polyControl: false,
+ // Unlike NVIDIA's text-only hosted preview, this lane DOES take user photos —
+ // it is the free option for image→3D, the counterpart to the free text lane.
+ userImages: true,
+ // Community GPU Spaces reached over Gradio's blocking /call API, with a
+ // failover chain (Hunyuan3D 2.1 → Hunyuan3D 2 → TRELLIS → TripoSR). Queue
+ // waits + cold starts dominate, so the ETA is generous; it blocks within the
+ // 300s reconstruct budget like the Stable Fast 3D synchronous lane.
+ baseEta: 90,
+ credits: null,
+ // Free image→3D — no vendor credit cost (HF Spaces' free GPU). One HF_TOKEN
+ // unlocks the whole chain; this is what makes photo→3D free for users.
+ free: true,
+ blurb: 'Free photo→3D on community GPU Spaces — Hunyuan3D / TRELLIS / TripoSR with automatic failover. No vendor cost; queue waits vary.',
+ }),
trellis: Object.freeze({
id: 'trellis',
label: 'TRELLIS',
diff --git a/api/_lib/http.js b/api/_lib/http.js
index 08e90ec3b..0d9e91ba0 100644
--- a/api/_lib/http.js
+++ b/api/_lib/http.js
@@ -7,10 +7,28 @@ import { captureException } from './sentry.js';
import { sendOpsAlert } from './alerts.js';
import { instrument as zauthInstrument, drain as zauthDrain } from './zauth.js';
+// Secure-by-default caching: emit `no-store` UNLESS the handler already set a
+// Cache-Control header (e.g. `res.setHeader('cache-control', 'public, s-maxage=…')`
+// on a public read) or passes one via `headers`. Previously this unconditionally
+// forced `no-store`, silently overriding any cache header a handler set just
+// before calling json()/text() — so public reads like /u/:username were never
+// CDN-cacheable. Error responses must NEVER be cached, so error()/serverError()/
+// validationError() pass an explicit `cache-control: no-store` in `headers`,
+// which wins via the loop below regardless of what the success path set.
+function applyCacheControl(res, headers) {
+ const fromArg = Object.keys(headers).some((k) => k.toLowerCase() === 'cache-control');
+ // `getHeader` is always present on a real Node ServerResponse; guard so a
+ // minimal mock without it still gets the secure default rather than throwing.
+ const alreadySet = typeof res.getHeader === 'function' && res.getHeader('cache-control');
+ if (!fromArg && !alreadySet) {
+ res.setHeader('cache-control', 'no-store');
+ }
+}
+
export function json(res, status, body, headers = {}) {
res.statusCode = status;
res.setHeader('content-type', 'application/json; charset=utf-8');
- res.setHeader('cache-control', 'no-store');
+ applyCacheControl(res, headers);
res.setHeader('x-content-type-options', 'nosniff');
res.setHeader('x-frame-options', 'DENY');
res.setHeader('referrer-policy', 'strict-origin-when-cross-origin');
@@ -21,7 +39,7 @@ export function json(res, status, body, headers = {}) {
export function text(res, status, body, headers = {}) {
res.statusCode = status;
res.setHeader('content-type', 'text/plain; charset=utf-8');
- res.setHeader('cache-control', 'no-store');
+ applyCacheControl(res, headers);
res.setHeader('x-content-type-options', 'nosniff');
res.setHeader('x-frame-options', 'DENY');
res.setHeader('referrer-policy', 'strict-origin-when-cross-origin');
@@ -37,7 +55,9 @@ export function redirect(res, location, status = 302) {
}
export function error(res, status, code, message, extra = {}) {
- return json(res, status, { error: code, error_description: message, ...extra });
+ // Error responses must never be cached, even on a handler that set a permissive
+ // Cache-Control on its success path before hitting this error branch.
+ return json(res, status, { error: code, error_description: message, ...extra }, { 'cache-control': 'no-store' });
}
// Query params that can carry a user's real-world position or a bearer-style
@@ -110,7 +130,7 @@ export function serverError(res, status, code, err, extra = {}) {
error_description: `internal error — quote ref ${ref} to support`,
ref,
...extra,
- });
+ }, { 'cache-control': 'no-store' });
}
// Dispatch: client-fault (4xx) keep their descriptive message; server-fault
@@ -169,7 +189,7 @@ export function validationError(res, err) {
error: err.code || 'validation_error',
error_description: err.message || 'invalid input',
issues: err.issues || [],
- });
+ }, { 'cache-control': 'no-store' });
}
export async function readJson(req, limit = 1_000_000) {
@@ -295,7 +315,7 @@ export function wrap(handler) {
error: err.code || 'internal_error',
error_description: `internal error — quote ref ${ref} to support`,
ref,
- });
+ }, { 'cache-control': 'no-store' });
}
} else if (!res.headersSent && !res.writableEnded) {
if (err.code === 'validation_error' && Array.isArray(err.issues)) {
diff --git a/api/_lib/memory-store.js b/api/_lib/memory-store.js
index 85afeedb9..1ca433be3 100644
--- a/api/_lib/memory-store.js
+++ b/api/_lib/memory-store.js
@@ -19,7 +19,7 @@
// upserted as graph nodes and linked to their source memory. Edges between
// entities are derived at read time from co-occurrence within a memory.
-import { sql } from './db.js';
+import { sql, sqlValues } from './db.js';
import {
embeddingsConfigured,
defaultIngestEmbedderTag,
@@ -243,36 +243,91 @@ export async function ensureEntities(agentId, cap = ENTITY_CAP) {
const capped = rows.length > cap;
const batch = capped ? rows.slice(0, cap) : rows;
- let processed = 0;
+ // Mine every memory first, then write in three bulk statements instead of the
+ // 2× INSERT + UPDATE per entity-per-row the loop used to issue.
+ // 1. Upsert entities, aggregated by (kind, normalized): mention_count and the
+ // capped salience bump are summed over occurrences in this batch (net-equal
+ // to applying the per-occurrence upsert sequentially); label/meta take the
+ // last occurrence, matching the original EXCLUDED.* "last writer wins".
+ // 2. Insert the (entity, memory) links, resolving entity ids from the upsert's
+ // RETURNING, with ON CONFLICT DO NOTHING.
+ // 3. Mark the processed memories entities_extracted.
+ const byKey = new Map(); // "kindnormalized" → { kind, label, normalized, meta, count }
+ const mentions = []; // { key, memoryId } per occurrence — drives the links
for (const row of batch) {
const entities = extractEntities(row.content, row.tags || [], row.context || {});
- try {
- for (const e of entities) {
- const [ent] = await sql`
- INSERT INTO agent_memory_entities (agent_id, kind, label, normalized, mention_count, salience, meta)
- VALUES (${agentId}, ${e.kind}, ${e.label}, ${e.normalized}, 1, 0.5, ${JSON.stringify(e.meta || {})}::jsonb)
- ON CONFLICT (agent_id, kind, normalized) DO UPDATE
- SET mention_count = agent_memory_entities.mention_count + 1,
- last_seen_at = now(),
- label = EXCLUDED.label,
- salience = LEAST(1.0, agent_memory_entities.salience + 0.05)
- RETURNING id
- `;
- if (ent?.id) {
- await sql`
- INSERT INTO agent_memory_entity_links (entity_id, memory_id)
- VALUES (${ent.id}, ${row.id})
- ON CONFLICT DO NOTHING
- `;
- }
+ for (const e of entities) {
+ const key = `${e.kind}${e.normalized}`;
+ const agg = byKey.get(key);
+ if (agg) {
+ agg.count += 1;
+ agg.label = e.label;
+ agg.meta = e.meta || {};
+ } else {
+ byKey.set(key, { kind: e.kind, label: e.label, normalized: e.normalized, meta: e.meta || {}, count: 1 });
}
- await sql`UPDATE agent_memories SET entities_extracted = true WHERE id = ${row.id}`;
- processed++;
+ mentions.push({ key, memoryId: row.id });
+ }
+ }
+
+ if (!byKey.size) {
+ // No entities in any memory — still mark them processed so reads converge.
+ try {
+ const ids = batch.map((r) => r.id);
+ await sql`UPDATE agent_memories SET entities_extracted = true WHERE id = ANY(${ids}::uuid[])`;
+ return { processed: batch.length, remaining: capped ? 1 : 0 };
} catch (err) {
- console.warn('[memory-store] entity extraction failed for', row.id, err?.message);
+ console.warn('[memory-store] entity extraction failed', err?.message);
+ return { processed: 0, remaining: capped ? 1 : 0 };
+ }
+ }
+
+ try {
+ const entityRows = [...byKey.values()].map((e) => [
+ agentId, e.kind, e.label, e.normalized, e.count, JSON.stringify(e.meta || {}),
+ ]);
+ const upserted = await sql`
+ INSERT INTO agent_memory_entities (agent_id, kind, label, normalized, mention_count, salience, meta)
+ SELECT v.agent_id, v.kind, v.label, v.normalized, v.cnt, 0.5, v.meta::jsonb
+ FROM ( VALUES ${sqlValues(entityRows)} ) AS v(agent_id, kind, label, normalized, cnt, meta)
+ ON CONFLICT (agent_id, kind, normalized) DO UPDATE
+ SET mention_count = agent_memory_entities.mention_count + EXCLUDED.mention_count,
+ last_seen_at = now(),
+ label = EXCLUDED.label,
+ salience = LEAST(1.0, agent_memory_entities.salience + 0.05 * EXCLUDED.mention_count)
+ RETURNING id, kind, normalized
+ `;
+
+ const idByKey = new Map();
+ for (const r of upserted) idByKey.set(`${r.kind}${r.normalized}`, r.id);
+
+ // Dedup link pairs (the PK is (entity_id, memory_id)) before the bulk insert.
+ const linkSet = new Set();
+ const linkRows = [];
+ for (const m of mentions) {
+ const entityId = idByKey.get(m.key);
+ if (!entityId) continue;
+ const pair = `${entityId}${m.memoryId}`;
+ if (linkSet.has(pair)) continue;
+ linkSet.add(pair);
+ linkRows.push([entityId, m.memoryId]);
+ }
+ if (linkRows.length) {
+ await sql`
+ INSERT INTO agent_memory_entity_links (entity_id, memory_id)
+ SELECT v.entity_id::uuid, v.memory_id::uuid
+ FROM ( VALUES ${sqlValues(linkRows)} ) AS v(entity_id, memory_id)
+ ON CONFLICT DO NOTHING
+ `;
}
+
+ const ids = batch.map((r) => r.id);
+ await sql`UPDATE agent_memories SET entities_extracted = true WHERE id = ANY(${ids}::uuid[])`;
+ return { processed: batch.length, remaining: capped ? 1 : 0 };
+ } catch (err) {
+ console.warn('[memory-store] entity extraction failed', err?.message);
+ return { processed: 0, remaining: capped ? 1 : 0 };
}
- return { processed, remaining: capped ? 1 : 0 };
}
/**
diff --git a/api/_lib/migrations/2026-06-21-three-allowances.sql b/api/_lib/migrations/2026-06-21-three-allowances.sql
new file mode 100644
index 000000000..3e887030f
--- /dev/null
+++ b/api/_lib/migrations/2026-06-21-three-allowances.sql
@@ -0,0 +1,55 @@
+-- Migration: three_allowances — the $THREE spend-allowance registry.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-06-21-three-allowances.sql
+-- Idempotent.
+--
+-- SCALING: the allowance status/pull paths must never call getProgramAccounts —
+-- it scans the whole program account set, is rate-limited on most RPCs, and is
+-- O(program). Instead we persist each grant's deterministic delegation PDA here
+-- when the user authorizes it, so reads become a cheap getMultipleAccountsInfo on
+-- the user's own (few) PDAs, Redis-cached. This table is the index that makes the
+-- allowance rail O(user) instead of O(program) under an influx of users.
+--
+-- No secrets: only public on-chain facts (PDA, nonce, cap, expiry, signatures) and
+-- the owning user/wallet. `status` is the lifecycle the app reconciles against the
+-- chain: pending → active → (spent | expired | revoked).
+
+begin;
+
+create table if not exists three_allowances (
+ id uuid primary key default gen_random_uuid(),
+ -- Nullable: a grant may originate from a wallet not linked to a user row.
+ user_id uuid references users(id) on delete set null,
+ wallet text not null,
+ mint text not null,
+ -- The platform delegate (delegatee) authorized at grant time. Pinned so a
+ -- delegate-key rotation never silently reinterprets old grants.
+ delegate text not null,
+ -- Deterministic PDA of this fixed delegation — the read key (UNIQUE).
+ delegation_pda text not null unique,
+ subscription_authority text not null,
+ -- u64 nonce that seeds the delegation PDA.
+ nonce numeric(20, 0) not null,
+ -- Authorized cap and optional auto-expiry (unix seconds; 0 = no expiry).
+ cap_atomics numeric(40, 0) not null,
+ expiry_ts bigint not null default 0,
+ network text not null default 'mainnet',
+ -- Lifecycle: pending (built, not yet confirmed on-chain) → active → terminal.
+ status text not null default 'pending'
+ check (status in ('pending', 'active', 'revoked', 'spent', 'expired')),
+ grant_tx text,
+ revoke_tx text,
+ -- Last reconciled remaining balance + when (drives the UI without a fresh RPC).
+ last_remaining_atomics numeric(40, 0),
+ last_synced_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+-- Hot path: list a wallet's live allowances (status-filtered, newest first).
+create index if not exists three_allowances_wallet_status
+ on three_allowances (wallet, status, created_at desc);
+
+create index if not exists three_allowances_user
+ on three_allowances (user_id, created_at desc);
+
+commit;
diff --git a/api/_lib/migrations/20260621120000_revenue-integrity.sql b/api/_lib/migrations/20260621120000_revenue-integrity.sql
new file mode 100644
index 000000000..5ded04144
--- /dev/null
+++ b/api/_lib/migrations/20260621120000_revenue-integrity.sql
@@ -0,0 +1,58 @@
+-- Revenue-ledger integrity: a single on-chain payment must credit exactly once,
+-- and money columns must never go negative.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260621120000_revenue-integrity.sql
+-- Idempotent.
+--
+-- NOTE ON LOCKING: this builds a UNIQUE index on agent_revenue_events with a
+-- brief write lock. The table is small at time of writing, so this is sub-second.
+-- If it has grown large by apply time, build the index out-of-band with
+-- CREATE UNIQUE INDEX CONCURRENTLY (which cannot run inside this transaction)
+-- and skip that one statement here.
+
+begin;
+
+-- 1. Collapse any phantom duplicate credits created before the application-layer
+-- consume-claim gate landed. Keep the earliest row per intent_id (the legitimate
+-- credit); the rest are double-counts that inflated withdrawable balance. Only
+-- touches intent_ids that actually have >1 row.
+DELETE FROM agent_revenue_events a
+USING (
+ SELECT intent_id, MIN(created_at) AS keep_created_at, MIN(id::text) AS keep_id
+ FROM agent_revenue_events
+ WHERE intent_id IS NOT NULL
+ GROUP BY intent_id
+ HAVING COUNT(*) > 1
+) dup
+WHERE a.intent_id = dup.intent_id
+ AND NOT (a.created_at = dup.keep_created_at AND a.id::text = dup.keep_id);
+
+-- 2. One credit per intent_id. NULL intent_ids are allowed (legacy/direct rows
+-- predating dedupe keys) and excluded from the constraint.
+CREATE UNIQUE INDEX IF NOT EXISTS agent_revenue_events_intent_uniq
+ ON agent_revenue_events (intent_id)
+ WHERE intent_id IS NOT NULL;
+
+-- 3. Money is never negative. Added valid (these invariants hold for all
+-- correctly-recorded rows); the sum-reconciliation check is NOT VALID so it
+-- guards new writes without retroactively failing on any historical row whose
+-- legs were recorded under older split logic.
+DO $$ BEGIN
+ ALTER TABLE agent_revenue_events
+ ADD CONSTRAINT agent_revenue_events_nonneg
+ CHECK (gross_amount >= 0 AND fee_amount >= 0
+ AND net_amount >= 0 AND platform_fee_amount >= 0);
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ ALTER TABLE agent_revenue_events
+ ADD CONSTRAINT agent_revenue_events_split
+ CHECK (gross_amount = fee_amount + net_amount + platform_fee_amount) NOT VALID;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ ALTER TABLE agent_withdrawals
+ ADD CONSTRAINT agent_withdrawals_amount_pos
+ CHECK (amount > 0);
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+commit;
diff --git a/api/_lib/migrations/20260621121000_bundle-purchase-verify.sql b/api/_lib/migrations/20260621121000_bundle-purchase-verify.sql
new file mode 100644
index 000000000..7d99d20b1
--- /dev/null
+++ b/api/_lib/migrations/20260621121000_bundle-purchase-verify.sql
@@ -0,0 +1,19 @@
+-- Bundle purchases must be verified on-chain at confirm, exactly like single-skill
+-- purchases. That requires persisting the Solana-Pay reference minted at create
+-- (to locate the tx), the treasury fee wallet (to verify the fee leg), and the
+-- mint decimals (to convert atomic price → UI amount for validateTransfer).
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260621121000_bundle-purchase-verify.sql
+-- Idempotent.
+
+begin;
+
+alter table bundle_purchases add column if not exists reference text;
+alter table bundle_purchases add column if not exists platform_fee_wallet text;
+alter table bundle_purchases add column if not exists mint_decimals int not null default 6;
+
+-- The Solana-Pay reference is unique per pending purchase and is how confirm
+-- finds the on-chain tx; index it for the lookup.
+create index if not exists idx_bundle_purchases_reference
+ on bundle_purchases(reference) where reference is not null;
+
+commit;
diff --git a/api/_lib/migrations/20260621122000_subscription-payment-idempotency.sql b/api/_lib/migrations/20260621122000_subscription-payment-idempotency.sql
new file mode 100644
index 000000000..f8df0c9f2
--- /dev/null
+++ b/api/_lib/migrations/20260621122000_subscription-payment-idempotency.sql
@@ -0,0 +1,22 @@
+-- Subscription billing idempotency: at most ONE pending payment per subscription
+-- per billing period. Without this, every cron pass over an unpaid subscription
+-- mints a fresh subscription_payments row + agent_payment_intents row, so a
+-- subscriber accumulates many distinct payable intents for a single period and
+-- could pay (and be period-advanced for) more than one.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260621122000_subscription-payment-idempotency.sql
+-- Idempotent.
+
+begin;
+
+-- The period this payment is for (the subscription's current_period_end at charge
+-- time). Nullable for legacy rows; new charges always set it.
+alter table subscription_payments add column if not exists period_end timestamptz;
+
+-- One pending charge per (subscription, period). NULL period_end rows (legacy) are
+-- distinct under a unique index, so this never blocks existing data, and only
+-- 'pending' rows are constrained — succeeded/failed history is unaffected.
+create unique index if not exists subscription_payments_one_pending_per_period
+ on subscription_payments (subscription_id, period_end)
+ where status = 'pending' and period_end is not null;
+
+commit;
diff --git a/api/_lib/migrations/20260621123000_users-display-name-index.sql b/api/_lib/migrations/20260621123000_users-display-name-index.sql
new file mode 100644
index 000000000..2aad80163
--- /dev/null
+++ b/api/_lib/migrations/20260621123000_users-display-name-index.sql
@@ -0,0 +1,12 @@
+-- Case-insensitive username lookup index for the login/signup hot path.
+-- api/auth/[action].js matches on lower(display_name) = lower($1); without this
+-- index every non-email login attempt sequentially scans users — a trivial DoS
+-- amplifier as the table grows.
+--
+-- CONCURRENTLY: users is auth-critical and must not be write-locked during the
+-- build. CREATE INDEX CONCURRENTLY cannot run inside a transaction, so this file
+-- intentionally has NO begin/commit wrapper and contains only this statement.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260621123000_users-display-name-index.sql
+
+create index concurrently if not exists users_display_name_lower
+ on users (lower(display_name)) where deleted_at is null;
diff --git a/api/_lib/monetization.js b/api/_lib/monetization.js
index 40db1ba10..41c19cc55 100644
--- a/api/_lib/monetization.js
+++ b/api/_lib/monetization.js
@@ -3,6 +3,7 @@
// Used by x402 intent consumption, skill purchase confirmation, and any
// code path that needs to attribute revenue to an agent owner.
+import { randomUUID } from 'node:crypto';
import { sql } from './db.js';
import { calculateFee } from './fee.js';
@@ -43,17 +44,34 @@ export async function recordRevenueEvent({
const { fee, net } = calculateFee(grossAmount);
+ // intent_id is UNIQUE — one on-chain payment credits exactly once. A real
+ // intent/tx reuses its identifier (so a retry conflicts and no-ops); a direct
+ // call with neither gets a synthetic unique key so distinct direct credits
+ // never collide.
+ const dedupeKey = intentId ?? txHash ?? `direct_${randomUUID()}`;
const [row] = await sql`
INSERT INTO agent_revenue_events
(agent_id, intent_id, skill, gross_amount, fee_amount, net_amount,
currency_mint, chain, payer_address)
VALUES
- (${agentId}, ${intentId ?? txHash ?? 'direct'}, ${skillName}, ${grossAmount},
+ (${agentId}, ${dedupeKey}, ${skillName}, ${grossAmount},
${fee}, ${net}, ${currencyMint}, ${network}, ${callerAddress})
+ ON CONFLICT (intent_id) DO NOTHING
RETURNING id, agent_id, skill, gross_amount, fee_amount, net_amount,
currency_mint, chain, payer_address, created_at
`;
+ // Conflict → this payment was already recorded; return the existing row so
+ // callers stay idempotent rather than seeing a phantom failure.
+ if (!row) {
+ const [existing] = await sql`
+ SELECT id, agent_id, skill, gross_amount, fee_amount, net_amount,
+ currency_mint, chain, payer_address, created_at
+ FROM agent_revenue_events WHERE intent_id = ${dedupeKey} LIMIT 1
+ `;
+ return existing;
+ }
+
return row;
}
diff --git a/api/_lib/pump-launch.js b/api/_lib/pump-launch.js
index b5b945b8d..90ba6cac7 100644
--- a/api/_lib/pump-launch.js
+++ b/api/_lib/pump-launch.js
@@ -16,6 +16,7 @@
import { Keypair, PublicKey, Transaction } from '@solana/web3.js';
import { env } from './env.js';
import { solanaConnection } from './agent-pumpfun.js';
+import { confirmOrThrow } from './solana/confirm.js';
import { grindMintKeypair } from './pump-vanity.js';
const PUMP_IPFS_ENDPOINT = 'https://pump.fun/api/ipfs';
@@ -243,7 +244,7 @@ export async function launchPumpToken({
let signature;
try {
signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');
+ await confirmOrThrow(conn, { signature, blockhash, lastValidBlockHeight }, 'confirmed');
} catch (err) {
throw launchError(502, 'rpc_error', err.message || 'create-coin transaction failed');
}
diff --git a/api/_lib/purchase-confirm.js b/api/_lib/purchase-confirm.js
index b4276ba1c..c81450ec4 100644
--- a/api/_lib/purchase-confirm.js
+++ b/api/_lib/purchase-confirm.js
@@ -506,6 +506,7 @@ async function finalizeSkillConfirmation(pur, txSignature, payoutAddress, platfo
(${pur.agent_id}, ${intentId}, ${pur.skill},
${grossAmt.toString()}, ${referralAmt.toString()}, ${platformFee.toString()},
${netAmt.toString()}, ${pur.currency_mint}, ${pur.chain}, ${payoutAddress})
+ ON CONFLICT (intent_id) DO NOTHING
`;
if (pur.referrer_user_id && referralAmt > 0n) {
// Track the referrer's accrued earnings. Real payout happens via the
@@ -585,6 +586,113 @@ async function finalizeSkillConfirmation(pur, txSignature, payoutAddress, platfo
return { status: 'confirmed', tx_signature: txSignature };
}
+// ── Bundle verification ───────────────────────────────────────────────────────
+//
+// A bundle is ONE payment for the whole-bundle price. This proves that payment
+// on-chain before any skill is unlocked, reusing the exact primitives the
+// single-skill path uses (Solana-Pay reference + validateTransfer, treasury
+// fee-leg balance delta, EVM payer-binding). The caller performs the DB writes
+// (mark confirmed, unlock skills, record revenue) only on { status: 'confirmed' }.
+//
+// @param {object} b — { chain, reference, txHash, recipient, currencyMint,
+// priceAtomics, feeAtomics, feeWallet, decimals, userId }
+// @returns {Promise<{ status: 'confirmed'|'pending'|'mismatch', txSignature?: string, message?: string }>}
+export async function verifyBundlePayment(b) {
+ const recipient = await resolvePayoutAddress(b.agentId, b.chain);
+ if (!recipient) throw new Error('payout wallet not configured');
+ if (b.chain === 'solana') return verifyBundleSolana(b, recipient);
+ if (evmChainId(b.chain)) return verifyBundleEvm(b, recipient);
+ throw new Error(`chain '${b.chain}' not supported`);
+}
+
+async function verifyBundleSolana(b, payoutAddress) {
+ if (!b.reference) return { status: 'mismatch', message: 'purchase is missing its payment reference' };
+ const refKey = new PublicKey(b.reference);
+ const recipient = new PublicKey(payoutAddress);
+ const splToken = new PublicKey(b.currencyMint);
+ const pow = new BigNumber(10).pow(b.decimals ?? 6);
+ const fullAtomics = new BigNumber(b.priceAtomics);
+ const feeAtomics = new BigNumber(b.feeAtomics || 0);
+
+ let signatureInfo;
+ try {
+ signatureInfo = await rpc().withFallback((conn) =>
+ findReference(conn, refKey, { finality: 'confirmed' }),
+ );
+ } catch (e) {
+ if (/FindReferenceError|not found/i.test(e?.message || '')) return { status: 'pending' };
+ throw e;
+ }
+ const txSignature = signatureInfo.signature;
+
+ const validateLeg = (who, amountAtomics) =>
+ rpc().withFallback((conn) =>
+ validateTransfer(
+ conn,
+ txSignature,
+ { recipient: who, amount: amountAtomics.dividedBy(pow), splToken, reference: refKey },
+ { commitment: 'confirmed' },
+ ),
+ );
+
+ const attempts = [];
+ if (feeAtomics.gt(0) && b.feeWallet)
+ attempts.push({ creator: fullAtomics.minus(feeAtomics), feeTaken: feeAtomics, feeWallet: b.feeWallet });
+ attempts.push({ creator: fullAtomics, feeTaken: new BigNumber(0), feeWallet: null });
+
+ let matched = null;
+ let lastErr = null;
+ for (const a of attempts) {
+ try {
+ await validateLeg(recipient, a.creator);
+ if (a.feeTaken.gt(0)) {
+ const ok = await feeLegSatisfied(txSignature, a.feeWallet, splToken, BigInt(a.feeTaken.toFixed(0)));
+ if (!ok) throw new Error('platform fee leg missing or short');
+ }
+ matched = a;
+ break;
+ } catch (e) {
+ lastErr = e;
+ }
+ }
+ if (!matched)
+ return { status: 'mismatch', message: lastErr?.message || 'on-chain transfer did not match expected' };
+ return { status: 'confirmed', txSignature };
+}
+
+async function verifyBundleEvm(b, payoutAddress) {
+ if (!b.txHash) return { status: 'pending' };
+ const result = await verifyEvmUsdcPayment({
+ txHash: b.txHash,
+ chain: b.chain,
+ recipient: payoutAddress,
+ expectedAmount: b.priceAtomics,
+ });
+ if (result.status === 'pending') return { status: 'pending' };
+
+ // Bind the on-chain payment to the buyer — a public transfer to the seller is
+ // not proof THIS buyer paid. Mirror confirmEvmSkill: the payer must be a
+ // wallet linked to the buyer's account.
+ if (result.from) {
+ const payer = result.from.toLowerCase();
+ const [linked] = await sql`
+ SELECT 1 FROM user_wallets WHERE user_id = ${b.userId} AND lower(address) = ${payer} LIMIT 1
+ `;
+ if (!linked)
+ return {
+ status: 'mismatch',
+ message:
+ 'payment must be sent from a wallet linked to your account — link the paying wallet, then retry',
+ };
+ } else if (result.status === 'match') {
+ return { status: 'mismatch', message: 'could not determine payer address from transaction' };
+ }
+
+ if (result.status !== 'match')
+ return { status: 'mismatch', message: result.message || 'amount mismatch' };
+ return { status: 'confirmed', txSignature: b.txHash };
+}
+
async function getSellerUserId(agentId) {
const [row] = await sql`SELECT user_id FROM agent_identities WHERE id = ${agentId}`;
return row?.user_id ?? null;
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 1919fbf16..49a5a2892 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -29,6 +29,8 @@ alter table users add column if not exists privy_did text;
create unique index if not exists users_wallet_unique on users(wallet_address) where wallet_address is not null;
create unique index if not exists users_username_unique on users(lower(username)) where username is not null;
create unique index if not exists users_privy_did_unique on users(privy_did) where privy_did is not null;
+-- Case-insensitive username lookup on the login/signup hot path (auth/[action].js).
+create index if not exists users_display_name_lower on users(lower(display_name)) where deleted_at is null;
-- SAML SSO subject link (set when a user signs in via an enterprise IdP).
alter table users add column if not exists saml_name_id text;
@@ -1248,12 +1250,19 @@ create table if not exists subscription_payments (
status text not null default 'pending' check (status in ('pending','succeeded','failed')),
tx_hash text,
paid_at timestamptz,
+ period_end timestamptz,
created_at timestamptz not null default now()
);
create index if not exists subscription_payments_subscription_idx
on subscription_payments(subscription_id);
+-- At most one pending charge per (subscription, billing period) — see
+-- migration 20260621122000_subscription-payment-idempotency.sql.
+create unique index if not exists subscription_payments_one_pending_per_period
+ on subscription_payments (subscription_id, period_end)
+ where status = 'pending' and period_end is not null;
+
-- ── social_connections ────────────────────────────────────────────────────────
create table if not exists social_connections (
id uuid primary key default gen_random_uuid(),
diff --git a/api/_lib/sealed-drop-funding.js b/api/_lib/sealed-drop-funding.js
index 58e4c0e46..cc6833978 100644
--- a/api/_lib/sealed-drop-funding.js
+++ b/api/_lib/sealed-drop-funding.js
@@ -48,6 +48,7 @@ import {
import { env } from './env.js';
import { solanaConnection } from './agent-pumpfun.js';
+import { confirmOrThrow } from './solana/confirm.js';
import { SOLANA_USDC_MINT } from '../payments/_config.js';
import { recordReclaim } from './sealed-drop-store.js';
@@ -196,7 +197,7 @@ export async function fundDropAddress({ toAddress, asset, atomics }) {
tx.recentBlockhash = blockhash;
tx.sign(payer);
const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });
- await conn.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
+ await confirmOrThrow(conn, { signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
return { fundingTx: sig, atomics: amount.toString(), asset };
}
@@ -297,7 +298,7 @@ export async function sweepReclaim({ record, dropSecretKey, toAddress }) {
tx.recentBlockhash = blockhash;
tx.sign(feePayer, dropKp);
const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });
- await conn.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
+ await confirmOrThrow(conn, { signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
await recordReclaim({ id: record.id, reclaimTx: sig });
return { reclaimTx: sig, alreadyReclaimed: false };
}
diff --git a/api/_lib/secret-box.js b/api/_lib/secret-box.js
index e04d1bd4d..8ae4f7b36 100644
--- a/api/_lib/secret-box.js
+++ b/api/_lib/secret-box.js
@@ -26,16 +26,35 @@ export const V2_PREFIX = 'v2:';
const LEGACY_SALT = new TextEncoder().encode('agent-wallet-v1');
let _warnedFallback = false;
+const IS_PROD =
+ env.VERCEL_ENV === 'production' || env.NODE_ENV === 'production';
+
// Dedicated master secret for at-rest encryption, decoupled from JWT_SECRET.
+//
+// In production we FAIL CLOSED: a missing/short WALLET_ENCRYPTION_KEY must never
+// silently downgrade custodial-secret confidentiality to JWT_SECRET (the most
+// widely-handled secret on the platform — a JWT_SECRET leak would then decrypt
+// every wallet, and rotating it to invalidate sessions would brick every wallet
+// whose ciphertext used the fallback). The JWT_SECRET fallback survives only
+// outside production so local/CI/preview keep working without extra setup.
function walletMasterSecret() {
const dedicated = env.WALLET_ENCRYPTION_KEY;
+ if (dedicated && dedicated.length >= 32) return dedicated;
+ if (IS_PROD) {
+ throw new Error(
+ '[secret-box] WALLET_ENCRYPTION_KEY is required in production and must be ' +
+ '>=32 chars. Refusing to encrypt/decrypt custodial secrets under the ' +
+ 'JWT_SECRET fallback. Set a dedicated WALLET_ENCRYPTION_KEY.',
+ );
+ }
if (dedicated && dedicated.length >= 16) return dedicated;
if (!_warnedFallback) {
_warnedFallback = true;
console.warn(
'[secret-box] WALLET_ENCRYPTION_KEY is not set (or too short); falling back to ' +
'JWT_SECRET for custodial secret encryption. Set a dedicated WALLET_ENCRYPTION_KEY ' +
- '(>=16 chars) so secret confidentiality does not depend on the session secret.',
+ '(>=32 chars) so secret confidentiality does not depend on the session secret. ' +
+ '(This fallback is disabled in production.)',
);
}
return env.JWT_SECRET;
diff --git a/api/_lib/solana-transfer.js b/api/_lib/solana-transfer.js
index 78d3a9303..c23755bbd 100644
--- a/api/_lib/solana-transfer.js
+++ b/api/_lib/solana-transfer.js
@@ -1,5 +1,6 @@
import { PublicKey, Transaction, Keypair } from '@solana/web3.js';
import { solanaConnection } from './solana/connection.js';
+import { confirmOrThrow } from './solana/confirm.js';
import {
getAssociatedTokenAddress,
createAssociatedTokenAccountInstruction,
@@ -43,6 +44,6 @@ export async function transferSolanaUSDC({ fromWallet, toAddress, amount, mint }
tx.sign(kp);
const sig = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
+ await confirmOrThrow(connection, { signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
return sig;
}
diff --git a/api/_lib/solana-wallet.js b/api/_lib/solana-wallet.js
index 70b145680..ea44b804d 100644
--- a/api/_lib/solana-wallet.js
+++ b/api/_lib/solana-wallet.js
@@ -3,6 +3,7 @@
import { Connection, PublicKey, Transaction, VersionedTransaction } from '@solana/web3.js';
import { solanaConnection } from './solana/connection.js';
+import { confirmOrThrow } from './solana/confirm.js';
import { recoverSolanaAgentKeypair } from './agent-wallet.js';
/**
@@ -29,7 +30,8 @@ export async function loadWallet(encryptedSecret) {
const raw = tx.serialize();
const sig = await conn.sendRawTransaction(raw, { skipPreflight: false });
const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash();
- await conn.confirmTransaction(
+ await confirmOrThrow(
+ conn,
{ signature: sig, blockhash, lastValidBlockHeight },
'confirmed',
);
diff --git a/api/_lib/solana/confirm.js b/api/_lib/solana/confirm.js
new file mode 100644
index 000000000..f50d4a99d
--- /dev/null
+++ b/api/_lib/solana/confirm.js
@@ -0,0 +1,36 @@
+// Confirm a Solana transaction and THROW if it landed-but-reverted.
+//
+// `Connection.confirmTransaction` resolves normally for a transaction that was
+// included in a block but failed execution — the on-chain error lives in
+// `result.value.err`, not in a thrown exception. Discarding that result is the
+// single most dangerous money-path bug class: a reverted launch/buy/transfer
+// gets persisted as `confirmed`, the spend cap is charged, and the user is told
+// it succeeded. Every server-signed send path must route its confirmation
+// through this helper so a revert becomes a thrown error the caller handles.
+//
+// Drop-in: replace
+// await conn.confirmTransaction(strategy, 'confirmed')
+// with
+// await confirmOrThrow(conn, strategy, 'confirmed')
+// `strategy` is whatever confirmTransaction accepts — a bare signature string or
+// the `{ signature, blockhash, lastValidBlockHeight }` object form.
+
+/**
+ * @param {import('@solana/web3.js').Connection} conn
+ * @param {string | { signature: string, blockhash?: string, lastValidBlockHeight?: number }} strategy
+ * @param {import('@solana/web3.js').Commitment} [commitment]
+ * @returns {Promise<import('@solana/web3.js').RpcResponseAndContext<import('@solana/web3.js').SignatureResult>>}
+ */
+export async function confirmOrThrow(conn, strategy, commitment = 'confirmed') {
+ const result = await conn.confirmTransaction(strategy, commitment);
+ if (result?.value?.err) {
+ const signature = typeof strategy === 'string' ? strategy : strategy?.signature;
+ throw Object.assign(
+ new Error(
+ `transaction ${signature ?? '<unknown>'} reverted on-chain: ${JSON.stringify(result.value.err)}`,
+ ),
+ { code: 'tx_reverted', signature, onChainErr: result.value.err },
+ );
+ }
+ return result;
+}
diff --git a/api/_lib/subscription-billing.js b/api/_lib/subscription-billing.js
index bc22eff5d..180ae1019 100644
--- a/api/_lib/subscription-billing.js
+++ b/api/_lib/subscription-billing.js
@@ -70,19 +70,63 @@ export async function chargeSubscription(subscriptionId) {
return { success: false, error: 'creator_payout_wallet_missing' };
}
- // Create the pending payment record.
- const [payment] = await sql`
- INSERT INTO subscription_payments (subscription_id, amount_usd, status)
- VALUES (${subscriptionId}, ${row.price_usd}, 'pending')
+ // Create the pending payment record — idempotently. At most one pending
+ // payment may exist per (subscription, period): the partial-unique index makes
+ // a concurrent/retried cron pass conflict instead of minting a second payable
+ // intent for the same period. On conflict we REUSE the existing pending payment
+ // (and its intent) rather than creating duplicates.
+ const periodEnd = row.current_period_end;
+ let [payment] = await sql`
+ INSERT INTO subscription_payments (subscription_id, amount_usd, status, period_end)
+ VALUES (${subscriptionId}, ${row.price_usd}, 'pending', ${periodEnd})
+ ON CONFLICT (subscription_id, period_end) WHERE status = 'pending' AND period_end IS NOT NULL
+ DO NOTHING
RETURNING id, status, amount_usd
`;
+ let reusing = false;
+ if (!payment) {
+ [payment] = await sql`
+ SELECT id, status, amount_usd FROM subscription_payments
+ WHERE subscription_id = ${subscriptionId} AND period_end = ${periodEnd}
+ AND status = 'pending'
+ ORDER BY created_at DESC LIMIT 1
+ `;
+ reusing = true;
+ if (!payment) {
+ // The conflicting row left 'pending' between our insert and select — a
+ // charge is mid-flight for this period; let the next pass settle it.
+ return { success: false, error: 'charge_in_progress' };
+ }
+ }
+
+ const amountAtomics = String(BigInt(Math.round(row.price_usd * 1_000_000)));
+ const memo = `sub:${subscriptionId}:${payment.id}`;
+
+ // If we're reusing an existing pending payment that already has a live intent,
+ // hand back THAT intent — never mint a second payable intent for one period.
+ if (reusing) {
+ const [existingIntent] = await sql`
+ SELECT id FROM agent_payment_intents
+ WHERE memo = ${memo} AND status = 'pending'
+ ORDER BY start_time DESC LIMIT 1
+ `;
+ if (existingIntent) {
+ return {
+ success: false,
+ pending: true,
+ paymentId: payment.id,
+ intentId: existingIntent.id,
+ payUrl: `${APP_ORIGIN}/pay?intent=${encodeURIComponent(existingIntent.id)}`,
+ amount_usd: Number(row.price_usd),
+ reused: true,
+ };
+ }
+ }
// Create the matching payment intent so the subscriber can actually pay.
// Amount stored in canonical USDC atomics — both EVM and Solana USDC are
// 6-decimal so the conversion is identical.
- const amountAtomics = String(BigInt(Math.round(row.price_usd * 1_000_000)));
const intentId = `sub_${nanoid()}`;
- const memo = `sub:${subscriptionId}:${payment.id}`;
const now = new Date();
const expiresAt = new Date(now.getTime() + 7 * 24 * 3600 * 1000); // 7-day grace window
@@ -185,9 +229,12 @@ export async function confirmPayment(paymentId, txHash) {
if (sub) {
const periodMs = sub.interval === 'weekly' ? 7 * 24 * 3600 * 1000 : 30 * 24 * 3600 * 1000;
const nextEnd = new Date(new Date(sub.current_period_end).getTime() + periodMs).toISOString();
+ // GREATEST so an out-of-order confirm (e.g. a manual replay) can only ever
+ // move the period boundary forward, never rewind a subscriber's paid time.
await sql`
UPDATE creator_subscriptions
- SET current_period_end = ${nextEnd}, status = 'active'
+ SET current_period_end = GREATEST(current_period_end, ${nextEnd}::timestamptz),
+ status = 'active'
WHERE id = ${payment.subscription_id}
`;
}
diff --git a/api/_lib/token/allowance-registry.js b/api/_lib/token/allowance-registry.js
new file mode 100644
index 000000000..964116feb
--- /dev/null
+++ b/api/_lib/token/allowance-registry.js
@@ -0,0 +1,111 @@
+// $THREE allowance registry — the DB index that keeps the rail O(user), not
+// O(program). Every grant we build is persisted with its deterministic delegation
+// PDA, so status/pull paths read the user's own few PDAs via a batched
+// getMultipleAccountsInfo (cheap, cacheable) instead of getProgramAccounts (a
+// whole-program scan that public RPCs throttle or disable). This module is the
+// thin persistence layer; reconciliation against the chain lives in allowance-ops.
+
+import { sql } from '../db.js';
+
+/**
+ * Record a freshly-built grant as `pending` (the user hasn't signed/sent yet).
+ * Keyed by the delegation PDA. A retried build of the same PDA refreshes the
+ * intended cap/expiry rather than duplicating.
+ */
+export async function recordPendingGrant({
+ userId = null,
+ wallet,
+ mint,
+ delegate,
+ delegationPda,
+ subscriptionAuthority,
+ nonce,
+ capAtomics,
+ expiryTs = 0,
+ network = 'mainnet',
+}) {
+ const [row] = await sql`
+ insert into three_allowances
+ (user_id, wallet, mint, delegate, delegation_pda, subscription_authority,
+ nonce, cap_atomics, expiry_ts, network, status)
+ values
+ (${userId}, ${wallet}, ${mint}, ${delegate}, ${delegationPda}, ${subscriptionAuthority},
+ ${String(nonce)}, ${String(capAtomics)}, ${expiryTs}, ${network}, 'pending')
+ on conflict (delegation_pda) do update
+ set cap_atomics = excluded.cap_atomics,
+ expiry_ts = excluded.expiry_ts,
+ user_id = coalesce(three_allowances.user_id, excluded.user_id),
+ updated_at = now()
+ returning id
+ `;
+ return row?.id ?? null;
+}
+
+/** Promote a grant to `active` once its signed transaction is confirmed on-chain. */
+export async function markGrantActive({ delegationPda, grantTx = null }) {
+ const [row] = await sql`
+ update three_allowances
+ set status = 'active', grant_tx = coalesce(${grantTx}, grant_tx), updated_at = now()
+ where delegation_pda = ${delegationPda}
+ and status in ('pending', 'active')
+ returning id, wallet, network
+ `;
+ return row ?? null;
+}
+
+/** Mark a grant revoked (the on-chain account is closed; rent returned to the user). */
+export async function markRevoked({ delegationPda, revokeTx = null }) {
+ const [row] = await sql`
+ update three_allowances
+ set status = 'revoked', revoke_tx = coalesce(${revokeTx}, revoke_tx),
+ last_remaining_atomics = 0, last_synced_at = now(), updated_at = now()
+ where delegation_pda = ${delegationPda}
+ returning id, wallet, network
+ `;
+ return row ?? null;
+}
+
+/** A single allowance row (used to authorize a revoke against its owner). */
+export async function getAllowanceRow(delegationPda) {
+ const [row] = await sql`
+ select id, user_id, wallet, mint, delegate, delegation_pda, subscription_authority,
+ nonce::text as nonce, cap_atomics::text as cap_atomics, expiry_ts, network, status
+ from three_allowances
+ where delegation_pda = ${delegationPda}
+ limit 1
+ `;
+ return row ?? null;
+}
+
+/**
+ * A wallet's allowances in the given lifecycle states (default: live ones).
+ * Newest first. The hot read for status + pull candidate selection.
+ */
+export async function listWalletAllowances({ wallet, network = 'mainnet', statuses = ['pending', 'active'] }) {
+ const rows = await sql`
+ select id, delegation_pda, subscription_authority, nonce::text as nonce,
+ cap_atomics::text as cap_atomics, expiry_ts, status,
+ last_remaining_atomics::text as last_remaining_atomics
+ from three_allowances
+ where wallet = ${wallet}
+ and network = ${network}
+ and status = any(${statuses})
+ order by created_at desc
+ limit 50
+ `;
+ return rows;
+}
+
+/**
+ * Write back the reconciled on-chain state (remaining balance + lifecycle) after a
+ * chain read, so the next render can trust the DB without another RPC.
+ */
+export async function syncReconciled({ delegationPda, remainingAtomics, status }) {
+ await sql`
+ update three_allowances
+ set last_remaining_atomics = ${remainingAtomics == null ? null : String(remainingAtomics)},
+ status = coalesce(${status}, status),
+ last_synced_at = now(), updated_at = now()
+ where delegation_pda = ${delegationPda}
+ `;
+}
diff --git a/api/_lib/token/allowance.js b/api/_lib/token/allowance.js
index ff8c62dd1..c27c89a5c 100644
--- a/api/_lib/token/allowance.js
+++ b/api/_lib/token/allowance.js
@@ -45,9 +45,10 @@ export const SUBSCRIPTIONS_PROGRAM_ID = new PublicKey(
'De1egAFMkMWZSN5rYXRj9CAdheBamobVNubTsi9avR44',
);
-// Instruction discriminators (single leading u8 — see IDL). Only the three we use.
+// Instruction discriminators (single leading u8 — see IDL). Only the ones we use.
const IX_INIT_SUBSCRIPTION_AUTHORITY = 0;
const IX_CREATE_FIXED_DELEGATION = 1;
+const IX_REVOKE_DELEGATION = 3;
const IX_TRANSFER_FIXED = 4;
// On-chain account byte layouts (from the IDL `accounts` definitions). The
@@ -179,6 +180,18 @@ export function ixCreateFixedDelegation({
});
}
+/** revokeDelegation (disc 3) — the user (authority) cancels a delegation and reclaims its rent. */
+export function ixRevokeDelegation({ authority, delegationPda }) {
+ return new TransactionInstruction({
+ programId: SUBSCRIPTIONS_PROGRAM_ID,
+ keys: [
+ { pubkey: new PublicKey(authority), isSigner: true, isWritable: true },
+ { pubkey: new PublicKey(delegationPda), isSigner: false, isWritable: true },
+ ],
+ data: Buffer.from([IX_REVOKE_DELEGATION]),
+ });
+}
+
/** transferFixed (disc 4) — delegate pulls `amount` from the user to `receiver`, decrementing the cap. */
export function ixTransferFixed({ delegationPda, delegator, delegatee, receiver, amount, mint = mintPubkey() }) {
const mintPk = new PublicKey(mint);
diff --git a/api/_lib/token/buyback.js b/api/_lib/token/buyback.js
index 412173c88..3c18d5857 100644
--- a/api/_lib/token/buyback.js
+++ b/api/_lib/token/buyback.js
@@ -25,6 +25,7 @@ import {
import { sql } from '../db.js';
import { getConnection, solanaPubkey } from '../pump.js';
+import { confirmOrThrow } from '../solana/confirm.js';
import { SOLANA_USDC_MINT } from '../../payments/_config.js';
import { TOKEN_MINT, TOKEN_DECIMALS } from './config.js';
import { treasuryWallet, treasuryWalletOrNull } from './config.js';
@@ -216,8 +217,9 @@ export async function executeBuyback(signer, plan) {
buyTx.sign([signer]);
const buySig = await connection.sendRawTransaction(buyTx.serialize(), { maxRetries: 5 });
try {
- await connection.confirmTransaction(buySig, 'confirmed');
+ await confirmOrThrow(connection, buySig, 'confirmed');
} catch (waitErr) {
+ if (waitErr?.code === 'tx_reverted') throw waitErr;
throw Object.assign(
new Error(`buyback ${buySig} submitted but confirmation timed out (${waitErr?.message || waitErr})`),
{ code: 'tx_unconfirmed', status: 'pending', buySignature: buySig },
@@ -246,7 +248,7 @@ export async function executeBuyback(signer, plan) {
tx.sign(signer);
sweepSig = await connection.sendRawTransaction(tx.serialize(), { maxRetries: 5 });
try {
- await connection.confirmTransaction(sweepSig, 'confirmed');
+ await confirmOrThrow(connection, sweepSig, 'confirmed');
} catch (waitErr) {
// The buy already landed; surface a sweep-specific failure so the next
// run self-heals (it sweeps any pre-existing $THREE before buying more).
@@ -293,7 +295,7 @@ export async function sweepStrandedThree(signer) {
tx.feePayer = payer;
tx.sign(signer);
const sig = await connection.sendRawTransaction(tx.serialize(), { maxRetries: 5 });
- await connection.confirmTransaction(sig, 'confirmed');
+ await confirmOrThrow(connection, sig, 'confirmed');
return sig;
}
diff --git a/api/_lib/x402.js b/api/_lib/x402.js
index 8b77aff3f..c788cc0ae 100644
--- a/api/_lib/x402.js
+++ b/api/_lib/x402.js
@@ -169,15 +169,22 @@ export async function verifyPaid(req, { agentId, skill, expectedAmount, expected
}
/**
- * Convenience: complete a paid call. Marks the intent as `consumed` so it
- * can't be reused — paid intents are single-shot per spec.
+ * Convenience: complete a paid call. Atomically marks the intent as `consumed`
+ * so it can't be reused — paid intents are single-shot per spec. Returns true
+ * only for the caller that won the paid→consumed transition; concurrent callers
+ * racing the same intent get false. Revenue/credit side effects MUST be gated on
+ * a true return, otherwise one on-chain payment can be credited N times.
+ *
+ * @returns {Promise<boolean>} true if this call consumed the intent.
*/
export async function consumeIntent(intentId) {
- await sql`
+ const rows = await sql`
update agent_payment_intents
set status = 'consumed'
where id = ${intentId} and status = 'paid'
+ returning id
`;
+ return rows.length > 0;
}
/**
diff --git a/api/_mcpagent/tools.js b/api/_mcpagent/tools.js
index 4ee8c703b..da0a955b2 100644
--- a/api/_mcpagent/tools.js
+++ b/api/_mcpagent/tools.js
@@ -14,6 +14,7 @@
import { limits } from '../_lib/rate-limit.js';
import { env } from '../_lib/env.js';
import { sql } from '../_lib/db.js';
+import { confirmOrThrow } from '../_lib/solana/confirm.js';
import { hasScope } from '../_lib/auth.js';
import { Bazaar, filterByMaxPrice, filterByNetwork } from '../_lib/x402/bazaar-client.js';
import {
@@ -120,7 +121,7 @@ async function requestDevnetAirdrop(address) {
try {
const conn = solanaConnection('devnet');
const signature = await conn.requestAirdrop(new PublicKey(address), LAMPORTS_PER_SOL);
- await conn.confirmTransaction(signature, 'confirmed');
+ await confirmOrThrow(conn, signature, 'confirmed');
return { ok: true, signature, sol: 1 };
} catch (err) {
const rateLimited = /429|limit/i.test(err?.message || '');
diff --git a/api/admin/withdrawals/[id].js b/api/admin/withdrawals/[id].js
index 8f118754a..7313f0e8c 100644
--- a/api/admin/withdrawals/[id].js
+++ b/api/admin/withdrawals/[id].js
@@ -62,16 +62,23 @@ export default wrap(async (req, res) => {
);
}
+ // Compare-and-set on the status we validated against. Without this guard the
+ // SELECT-then-UPDATE races the cron's atomic pending→processing claim (and a
+ // second admin): both could read 'pending' and both send funds. Gating the
+ // UPDATE on the prior status means exactly one transition wins; the loser
+ // gets a clean 409 instead of a double-spend.
const [withdrawal] = await sql`
update agent_withdrawals
set
status = ${status},
tx_signature = coalesce(${tx_signature ?? null}, tx_signature),
updated_at = now()
- where id = ${id}
+ where id = ${id} and status = ${current.status}
returning id, user_id, agent_id, amount, currency_mint, chain, to_address,
status, tx_signature, created_at, updated_at
`;
+ if (!withdrawal)
+ return error(res, 409, 'conflict', 'withdrawal status changed concurrently — reload and retry');
if (status === 'completed' || status === 'failed') {
const notifType = status === 'completed' ? 'withdrawal_completed' : 'withdrawal_failed';
diff --git a/api/agents/pumpfun/[action].js b/api/agents/pumpfun/[action].js
index f4033b8b5..4d17874fa 100644
--- a/api/agents/pumpfun/[action].js
+++ b/api/agents/pumpfun/[action].js
@@ -16,6 +16,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/au
import { cors, json, method, readJson, wrap, error, rateLimited, serverError, respondError } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
+import { confirmOrThrow } from '../../_lib/solana/confirm.js';
import { reserveSpend, finalizeSpend, releaseSpend } from '../../_lib/agent-spend-policy.js';
import { grindMintKeypair } from '../../_lib/pump-vanity.js';
import { sql } from '../../_lib/db.js';
@@ -270,7 +271,7 @@ async function handleBuy(req, res, id) {
let signature;
try {
signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction(signature, 'confirmed');
+ await confirmOrThrow(conn, signature, 'confirmed');
} catch (err) {
console.error('[pumpfun/buy] send failed', err);
if (reservation) await releaseSpend(reservation.reservationId);
@@ -493,7 +494,7 @@ async function handleLaunch(req, res, id) {
let signature;
try {
signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction(signature, 'confirmed');
+ await confirmOrThrow(conn, signature, 'confirmed');
} catch (err) {
console.error('[pumpfun/launch] send failed', err);
await releaseSpend(reservation.reservationId);
@@ -727,7 +728,7 @@ async function handlePay(req, res, id) {
let signature;
try {
signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction(signature, 'confirmed');
+ await confirmOrThrow(conn, signature, 'confirmed');
} catch (err) {
console.error(`[pumpfun/pay] ${body.action} send failed`, err);
return serverError(res, 502, 'rpc_error', err);
@@ -1125,7 +1126,7 @@ async function handleSell(req, res, id) {
let signature;
try {
signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction(signature, 'confirmed');
+ await confirmOrThrow(conn, signature, 'confirmed');
} catch (err) {
console.error('[pumpfun/sell] send failed', err);
return serverError(res, 502, 'rpc_error', err);
@@ -1385,7 +1386,7 @@ async function handleSwap(req, res, id) {
let signature;
try {
signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction(signature, 'confirmed');
+ await confirmOrThrow(conn, signature, 'confirmed');
} catch (err) {
console.error('[pumpfun/swap] send failed', err);
if (reservation) await releaseSpend(reservation.reservationId);
diff --git a/api/agents/sns.js b/api/agents/sns.js
index 347e970ab..99fdd3d38 100644
--- a/api/agents/sns.js
+++ b/api/agents/sns.js
@@ -26,6 +26,7 @@
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
+import { confirmOrThrow } from '../_lib/solana/confirm.js';
import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { env } from '../_lib/env.js';
@@ -151,7 +152,7 @@ async function handleRegisterAgent(req, res, id, auth) {
tx.recentBlockhash = blockhash;
tx.sign(keypair);
const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
+ await confirmOrThrow(conn, { signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
meta = { ...meta, sns_domain: domain };
await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index 562133082..b5324d616 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -3,6 +3,7 @@
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
+import { confirmOrThrow } from '../_lib/solana/confirm.js';
import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
@@ -253,7 +254,7 @@ async function handleAirdrop(req, res, id) {
try {
const conn = solanaConnection('devnet');
signature = await conn.requestAirdrop(new PublicKey(address), AIRDROP_LAMPORTS);
- await conn.confirmTransaction(signature, 'confirmed');
+ await confirmOrThrow(conn, signature, 'confirmed');
} catch (err) {
console.error('[agents/solana/airdrop] failed', err);
return error(res, 502, 'faucet_unavailable',
diff --git a/api/agents/x402/[action].js b/api/agents/x402/[action].js
index cccfac409..9b2a2e430 100644
--- a/api/agents/x402/[action].js
+++ b/api/agents/x402/[action].js
@@ -202,22 +202,30 @@ async function handleInvoke(req, res) {
// payment still covers a retry instead of being burned on a failed call.
const result = await executeSkill(agent, body, auth, paid.payerAddress || null);
- await consumeIntent(paid.intentId);
- const gross = parseInt(paid.amount, 10);
- const { fee, net } = calculateFee(gross);
- await sql`
- insert into agent_revenue_events
- (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount, currency_mint, chain, payer_address)
- values
- (${agent.id}, ${paid.intentId}, ${body.skill}, ${gross}, ${fee}, ${net}, ${paid.currency}, ${price.chain ?? 'solana'}, ${paid.payerAddress})
- `;
- insertNotification(agent.user_id, 'payment_received', {
- agent_id: agent.id,
- agent_name: agent.name,
- skill: body.skill,
- net_amount: net,
- currency_mint: paid.currency,
- });
+ // Credit revenue ONLY for the request that atomically wins paid→consumed.
+ // Two concurrent requests can both pass verifyPaid (both see status='paid'),
+ // but only one transitions the intent to 'consumed'; gating the insert here is
+ // what prevents one on-chain payment from being credited twice. The unique
+ // index on agent_revenue_events(intent_id) is the hard backstop.
+ const claimed = await consumeIntent(paid.intentId);
+ if (claimed) {
+ const gross = parseInt(paid.amount, 10);
+ const { fee, net } = calculateFee(gross);
+ await sql`
+ insert into agent_revenue_events
+ (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount, currency_mint, chain, payer_address)
+ values
+ (${agent.id}, ${paid.intentId}, ${body.skill}, ${gross}, ${fee}, ${net}, ${paid.currency}, ${price.chain ?? 'solana'}, ${paid.payerAddress})
+ on conflict (intent_id) do nothing
+ `;
+ insertNotification(agent.user_id, 'payment_received', {
+ agent_id: agent.id,
+ agent_name: agent.name,
+ skill: body.skill,
+ net_amount: net,
+ currency_mint: paid.currency,
+ });
+ }
return json(res, 200, {
ok: true,
intent_id: paid.intentId,
diff --git a/api/auth/[action].js b/api/auth/[action].js
index 2ea3f796b..03da5ea23 100644
--- a/api/auth/[action].js
+++ b/api/auth/[action].js
@@ -39,7 +39,7 @@ async function handleLogin(req, res) {
const isEmail = body.email.includes('@');
const rows = isEmail
? await sql`select id, email, password_hash, display_name, plan, avatar_url, referral_code from users where email = ${body.email} and deleted_at is null limit 1`
- : await sql`select id, email, password_hash, display_name, plan, avatar_url, referral_code from users where display_name ilike ${body.email} and deleted_at is null limit 1`;
+ : await sql`select id, email, password_hash, display_name, plan, avatar_url, referral_code from users where lower(display_name) = lower(${body.email}) and deleted_at is null limit 1`;
const user = rows[0];
// Always run a bcrypt compare, even when the account doesn't exist, so the
// response time doesn't reveal whether the email/username is registered.
@@ -130,7 +130,7 @@ async function handleRegister(req, res) {
displayName_val = body.username;
passwordVal = body.password;
referralCode = body.referralCode;
- const existing = await sql`select id from users where display_name ilike ${body.username} and deleted_at is null limit 1`;
+ const existing = await sql`select id from users where lower(display_name) = lower(${body.username}) and deleted_at is null limit 1`;
if (existing[0]) return error(res, 409, 'conflict', 'email or username already in use');
} else {
const body = parse(registerBody, raw);
diff --git a/api/community/auth/callback.js b/api/community/auth/callback.js
index 27c975b52..779d15160 100644
--- a/api/community/auth/callback.js
+++ b/api/community/auth/callback.js
@@ -23,7 +23,7 @@ function announceSignIn(user) {
function page({ ok, user = null, message = '' }) {
// The opener verifies event.origin === APP_ORIGIN before trusting this.
- const payload = JSON.stringify({ type: 'cc-auth', ok, user, message });
+ const payload = JSON.stringify({ type: 'cc-auth', ok, user, message }).replace(/</g, '\\u003c');
return `<!doctype html><meta charset="utf-8"><title>Signing in…</title>
<body style="margin:0;display:grid;place-items:center;height:100vh;font:15px system-ui;background:#0a0e1c;color:#cdd9f5">
<div>${ok ? 'Signed in — you can close this window.' : 'Sign-in failed. You can close this window.'}</div>
diff --git a/api/cron/[name].js b/api/cron/[name].js
index 5a0fe1432..08fe39d4a 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -30,6 +30,7 @@ import { evmTransport } from '../_lib/evm/rpc.js';
import { baseSepolia, base } from 'viem/chains';
import { sql } from '../_lib/db.js';
+import { confirmOrThrow } from '../_lib/solana/confirm.js';
import { cors, error, json, method, wrap } from '../_lib/http.js';
import { env } from '../_lib/env.js';
import { llmComplete } from '../_lib/llm.js';
@@ -1770,7 +1771,7 @@ async function handleRunBuyback(req, res) {
tx.feePayer = relayer.publicKey;
tx.sign(relayer);
const sig = await connection.sendRawTransaction(tx.serialize());
- await connection.confirmTransaction(sig, 'confirmed');
+ await confirmOrThrow(connection, sig, 'confirmed');
const [run] = await sql`
insert into pump_buyback_runs
@@ -2523,7 +2524,7 @@ async function handleRunDistributePayments(req, res) {
const sig = await connection.sendRawTransaction(tx.serialize(), {
skipPreflight: false,
});
- await connection.confirmTransaction(sig, 'confirmed');
+ await confirmOrThrow(connection, sig, 'confirmed');
const balancesAfter = await agent.getBalances(currency);
const [run] = await sql`
@@ -3085,6 +3086,19 @@ async function handleProcessSubscriptions(req, res) {
}
}
+ // Page on genuine charge failures so a billing outage doesn't hide behind a
+ // green cron. 'charge_in_progress' is the benign idempotency signal (another
+ // pass already owns this period) and is intentionally not a failure.
+ const realErrors = report.errors.filter((e) => e.error !== 'charge_in_progress');
+ if (realErrors.length > 0) {
+ const { sendOpsAlert } = await import('../_lib/alerts.js');
+ await sendOpsAlert(
+ `${realErrors.length} subscription charge(s) failed this run`,
+ realErrors.slice(0, 10).map((e) => `• ${e.id}: ${e.error}`).join('\n'),
+ { signature: 'subscriptions-charge-failed' },
+ );
+ }
+
console.log(JSON.stringify({ event: 'process_subscriptions.done', ...report }));
return json(res, 200, report);
}
@@ -3205,6 +3219,30 @@ async function handleProcessWithdrawals(req, res) {
const { transferSolanaUSDC } = await import('../_lib/solana-transfer.js');
const { sendEvmUsdc, resolveEvmChainId } = await import('../_lib/evm-transfer.js');
const { insertNotification } = await import('../_lib/notify.js');
+ const { sendOpsAlert } = await import('../_lib/alerts.js');
+
+ // Reconciliation: a crash between the on-chain send and the 'completed' write
+ // strands a row in 'processing'. The main loop only claims 'pending', so it is
+ // never retried. We do NOT auto-resend — without an on-chain idempotency
+ // reference a blind retry could double-pay — we page an operator to reconcile
+ // by hand (confirm the transfer settled, then complete or re-queue the row).
+ const stranded = await sql`
+ SELECT id, amount, currency_mint, chain, updated_at
+ FROM agent_withdrawals
+ WHERE status = 'processing' AND updated_at < now() - interval '15 minutes'
+ ORDER BY updated_at ASC LIMIT 50
+ `;
+ if (stranded.length) {
+ await sendOpsAlert(
+ `${stranded.length} withdrawal(s) stranded in 'processing' >15m`,
+ stranded
+ .map((s) => `• ${s.id} — ${s.amount} ${s.currency_mint} (${s.chain})`)
+ .join('\n') +
+ '\nManual reconciliation required: verify whether the on-chain transfer ' +
+ 'settled BEFORE completing or re-queuing — a blind retry can double-pay.',
+ { signature: 'withdrawals-stranded' },
+ );
+ }
// Build the chain filter to match what we can actually process. A row whose
// chain has no treasury key configured stays 'pending' for the next pass
@@ -3259,7 +3297,7 @@ async function handleProcessWithdrawals(req, res) {
LIMIT ${WITHDRAWALS_BATCH}
`;
- const report = { processed: 0, completed: 0, failed: 0, skipped: 0, errors: [] };
+ const report = { processed: 0, completed: 0, failed: 0, skipped: 0, sendFailed: 0, errors: [] };
for (const w of pending) {
report.processed++;
@@ -3337,33 +3375,49 @@ async function handleProcessWithdrawals(req, res) {
WHERE id = ${w.user_id}
`.catch((e) => console.error('[process-withdrawals] referral deduct failed:', e.message));
- insertNotification(w.user_id, 'withdrawal_completed', {
+ await insertNotification(w.user_id, 'withdrawal_completed', {
withdrawal_id: w.id,
amount: w.amount,
currency_mint: w.currency_mint,
chain: w.chain,
tx_signature: sig,
- });
+ }).catch((e) => console.error('[process-withdrawals] notify completed failed:', e.message));
report.completed++;
} catch (err) {
const msg = err.message || String(err);
+ // The row was already claimed to 'processing'. A failure HERE may mean the
+ // on-chain send threw before broadcast (safe to fail) OR after (funds may
+ // have moved). Mark failed so the user is told, but record it as a send
+ // failure so the batch alert fires and an operator reconciles.
await sql`
UPDATE agent_withdrawals
SET status = 'failed', error_message = ${msg}, updated_at = now()
WHERE id = ${w.id}
`;
- insertNotification(w.user_id, 'withdrawal_failed', {
+ await insertNotification(w.user_id, 'withdrawal_failed', {
withdrawal_id: w.id,
amount: w.amount,
currency_mint: w.currency_mint,
reason: msg,
- });
+ }).catch((e) => console.error('[process-withdrawals] notify failed failed:', e.message));
report.failed++;
+ report.sendFailed++;
report.errors.push({ id: w.id, error: msg });
}
}
+ // A green cron with failing payouts is invisible — page on real send failures
+ // (treasury out of gas/SOL, RPC down, transfer reverted) so a payout outage
+ // doesn't sit silently. Balance-rejections above are normal and excluded.
+ if (report.sendFailed > 0) {
+ await sendOpsAlert(
+ `${report.sendFailed} withdrawal payout(s) failed on-chain this run`,
+ report.errors.slice(0, 10).map((e) => `• ${e.id}: ${e.error}`).join('\n'),
+ { signature: 'withdrawals-send-failed' },
+ );
+ }
+
return json(res, 200, { ok: true, ...report });
}
diff --git a/api/cron/copy-fanout.js b/api/cron/copy-fanout.js
index 8b93e631b..008f41f66 100644
--- a/api/cron/copy-fanout.js
+++ b/api/cron/copy-fanout.js
@@ -154,11 +154,21 @@ async function fanoutBuys(network, stats) {
const spent = new Map(spendRows.map((r) => [r.subscription_id, Number(r.spent) || 0]));
const open = new Map(openRows.map((r) => [r.subscription_id, Number(r.open) || 0]));
+ // Active subscriptions for every leader in this batch, fetched once and grouped
+ // by leader_agent_id — replaces a per-position query.
+ const leaderIds = [...new Set(positions.map((p) => p.agent_id))];
+ const subRows = await sql`
+ select * from copy_subscriptions
+ where leader_agent_id = any(${leaderIds}) and network = ${network} and status = 'active'
+ `;
+ const subsByLeader = new Map();
+ for (const s of subRows) {
+ if (!subsByLeader.has(s.leader_agent_id)) subsByLeader.set(s.leader_agent_id, []);
+ subsByLeader.get(s.leader_agent_id).push(s);
+ }
+
for (const pos of positions) {
- const subs = await sql`
- select * from copy_subscriptions
- where leader_agent_id = ${pos.agent_id} and network = ${network} and status = 'active'
- `;
+ const subs = subsByLeader.get(pos.agent_id) || [];
if (!subs.length) continue;
const score = await oracleScore(pos.mint, network);
const coin = await coinContext(pos.mint, score);
@@ -223,13 +233,25 @@ async function fanoutSells(network, stats) {
order by p.closed_at desc
limit 200
`;
+ if (!closes.length) return;
+
+ // Acted buys for every close in this batch, fetched once and grouped by the
+ // leader position they mirror — replaces a per-close query.
+ const closeIds = [...new Set(closes.map((p) => p.id))];
+ const buyRows = await sql`
+ select e.leader_position_id, e.subscription_id, e.copier_user_id, s.copy_sells, s.status as sub_status
+ from copy_executions e
+ join copy_subscriptions s on s.id = e.subscription_id
+ where e.leader_position_id = any(${closeIds}) and e.direction = 'buy' and e.status = 'acted'
+ `;
+ const buysByPosition = new Map();
+ for (const b of buyRows) {
+ if (!buysByPosition.has(b.leader_position_id)) buysByPosition.set(b.leader_position_id, []);
+ buysByPosition.get(b.leader_position_id).push(b);
+ }
+
for (const pos of closes) {
- const buys = await sql`
- select e.subscription_id, e.copier_user_id, s.copy_sells, s.status as sub_status
- from copy_executions e
- join copy_subscriptions s on s.id = e.subscription_id
- where e.leader_position_id = ${pos.id} and e.direction = 'buy' and e.status = 'acted'
- `;
+ const buys = buysByPosition.get(pos.id) || [];
for (const b of buys) {
if (!b.copy_sells || b.sub_status === 'stopped') continue;
const [inserted] = await sql`
@@ -287,11 +309,21 @@ async function fanoutOracleBuys(network, stats) {
const spent = new Map(spendRows.map((r) => [r.subscription_id, Number(r.spent) || 0]));
const open = new Map(openRows.map((r) => [r.subscription_id, Number(r.open) || 0]));
+ // Active subscriptions for every acting agent in this batch, fetched once and
+ // grouped by leader_agent_id — replaces a per-action query.
+ const leaderIds = [...new Set(actions.map((a) => a.agent_id))];
+ const subRows = await sql`
+ select * from copy_subscriptions
+ where leader_agent_id = any(${leaderIds}) and network = ${network} and status = 'active'
+ `;
+ const subsByLeader = new Map();
+ for (const s of subRows) {
+ if (!subsByLeader.has(s.leader_agent_id)) subsByLeader.set(s.leader_agent_id, []);
+ subsByLeader.get(s.leader_agent_id).push(s);
+ }
+
for (const action of actions) {
- const subs = await sql`
- select * from copy_subscriptions
- where leader_agent_id = ${action.agent_id} and network = ${network} and status = 'active'
- `;
+ const subs = subsByLeader.get(action.agent_id) || [];
if (!subs.length) continue;
// Oracle action has conviction inline — no DB lookup needed.
const coin = await coinContext(action.mint, action.conviction != null ? Number(action.conviction) : null);
diff --git a/api/cron/smart-money-rollup.js b/api/cron/smart-money-rollup.js
index 633906ce4..20048a84b 100644
--- a/api/cron/smart-money-rollup.js
+++ b/api/cron/smart-money-rollup.js
@@ -101,16 +101,26 @@ async function judgeAndFold() {
deltas.set(wallet, cur);
};
+ // Top buyers (by buy_lamports) for every candidate coin in one round trip,
+ // window-limited to TOP_WALLETS per mint — replaces a per-coin query.
+ const walletRows = await sql`
+ SELECT mint, wallet, buy_lamports, sell_lamports, is_creator, first_ts FROM (
+ SELECT mint, wallet, buy_lamports, sell_lamports, is_creator,
+ extract(epoch from first_seen_at)::bigint AS first_ts,
+ row_number() OVER (PARTITION BY mint ORDER BY buy_lamports DESC) AS rn
+ FROM pump_coin_wallets
+ WHERE mint = ANY(${mints})
+ ) t WHERE rn <= ${TOP_WALLETS}
+ `;
+ const walletsByCoin = new Map();
+ for (const w of walletRows) {
+ if (!walletsByCoin.has(w.mint)) walletsByCoin.set(w.mint, []);
+ walletsByCoin.get(w.mint).push(w);
+ }
+
for (const coin of candidates) {
const outcome = graduated.has(coin.mint) ? 'graduated' : 'dud';
- const wallets = await sql`
- SELECT wallet, buy_lamports, sell_lamports, is_creator,
- extract(epoch from first_seen_at)::bigint AS first_ts
- FROM pump_coin_wallets
- WHERE mint = ${coin.mint}
- ORDER BY buy_lamports DESC
- LIMIT ${TOP_WALLETS}
- `;
+ const wallets = walletsByCoin.get(coin.mint) || [];
for (const w of wallets) {
const d = attributeCoin({
outcome,
diff --git a/api/forge.js b/api/forge.js
index 8144d52b2..5ce423519 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -879,6 +879,11 @@ async function startJob(req, res) {
provider = createGcpProvider({ reconstructUrl: hunyuanUrl });
} else if (backendId === 'replicate_byok') {
provider = createRegenProvider({ apiToken: byokReplicateKey });
+ } else if (backendId === 'huggingface') {
+ // The free HF Spaces lane is driven by runHfImageLane() below — it
+ // creates its own provider. We deliberately do NOT build a Replicate
+ // client here: creating one would 503 on a deployment that has no
+ // REPLICATE_API_TOKEN, breaking an explicitly-chosen free engine.
} else {
provider = createRegenProvider();
}
@@ -913,6 +918,37 @@ async function startJob(req, res) {
views = [referenceImageUrl];
}
+ // Explicitly chosen free HuggingFace lane. Unlike the trellis free-first
+ // path below — which degrades to the paid Replicate lane when the free
+ // Spaces are down — an explicit pick of the FREE engine must never silently
+ // fall through to a paid lane: that would spend credits the user
+ // deliberately opted out of. So we run the free Spaces and, if every one is
+ // busy/down, return a designed error the UI can act on (retry / switch engine).
+ if (backendId === 'huggingface') {
+ if (
+ await runHfImageLane({
+ req,
+ res,
+ ip,
+ imageUrls: views,
+ prompt,
+ aspect,
+ tier,
+ path,
+ mode: isImageMode ? 'image_to_3d' : 'text_to_3d',
+ previewImageUrl: referenceImageUrl,
+ textToImageModel,
+ })
+ )
+ return;
+ return json(res, 502, {
+ error: 'provider_busy',
+ backend: 'huggingface',
+ message:
+ 'The free 3D Spaces are all busy or warming up right now. Try again in a moment, or pick another engine.',
+ });
+ }
+
// Free-first: exhaust the free reconstruct lane (HuggingFace Spaces) BEFORE
// the paid Replicate default, so a forge call never spends on — or dead-ends
// against — the paid account while a free lane can serve it. We already hold
diff --git a/api/marketplace/purchase-as-agent.js b/api/marketplace/purchase-as-agent.js
index c9a98268a..6c8ce2e0c 100644
--- a/api/marketplace/purchase-as-agent.js
+++ b/api/marketplace/purchase-as-agent.js
@@ -19,6 +19,7 @@
*/
import { Keypair, PublicKey, Transaction } from '@solana/web3.js';
import { solanaConnection } from '../_lib/solana/connection.js';
+import { confirmOrThrow } from '../_lib/solana/confirm.js';
import {
getAssociatedTokenAddressSync,
createTransferCheckedInstruction,
@@ -272,7 +273,7 @@ export default wrap(async (req, res) => {
skipPreflight: false,
preflightCommitment: 'confirmed',
});
- await connection.confirmTransaction({ signature: txSig, blockhash, lastValidBlockHeight }, 'confirmed');
+ await confirmOrThrow(connection, { signature: txSig, blockhash, lastValidBlockHeight }, 'confirmed');
log('purchase_as_agent.tx_confirmed', { purchase_id: pur.id, tx_signature: txSig });
} catch (e) {
await sql`
diff --git a/api/marketplace/purchase-bundle.js b/api/marketplace/purchase-bundle.js
index 08750a005..fdd8b9992 100644
--- a/api/marketplace/purchase-bundle.js
+++ b/api/marketplace/purchase-bundle.js
@@ -11,14 +11,13 @@
*/
import { Keypair } from '@solana/web3.js';
-import { PublicKey } from '@solana/web3.js';
import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
import { resolveMarketplaceFee } from '../_lib/marketplace-platform-fee.js';
-import { confirmSkillPurchase } from '../_lib/purchase-confirm.js';
+import { verifyBundlePayment } from '../_lib/purchase-confirm.js';
import { isUuid } from '../_lib/validate.js';
async function resolveAuth(req) {
@@ -96,10 +95,12 @@ async function handleCreate(req, res) {
const [purchase] = await sql`
INSERT INTO bundle_purchases
- (bundle_id, user_id, agent_id, price_amount, currency_mint, chain, platform_fee_amount)
+ (bundle_id, user_id, agent_id, price_amount, currency_mint, chain,
+ platform_fee_amount, reference, platform_fee_wallet)
VALUES
(${bundle.id}, ${auth.userId}, ${bundle.agent_id}, ${bundle.price_amount},
- ${bundle.currency_mint}, ${bundle.chain}, ${feeResult.feeAmount ?? 0})
+ ${bundle.currency_mint}, ${bundle.chain}, ${feeResult.feeAmount ?? 0},
+ ${reference}, ${feeResult.treasuryWallet ?? null})
RETURNING id, price_amount, currency_mint, chain
`;
@@ -129,27 +130,62 @@ async function handleConfirm(req, res, purchaseId) {
if (!(await requireCsrf(req, res, auth.userId))) return;
const body = await readJson(req).catch(() => null);
- const txSignature = body?.tx_signature;
- if (!txSignature) return error(res, 400, 'validation_error', 'tx_signature required');
+ // EVM settles by client-submitted tx hash; Solana is located on-chain via the
+ // reference minted at create (no client-supplied signature is trusted).
+ const evmTxHash = body?.tx_signature || null;
const [purchase] = await sql`
- SELECT bp.*, sb.price_amount AS bundle_price,
+ SELECT bp.*,
COALESCE(json_agg(bi.skill_name) FILTER (WHERE bi.skill_name IS NOT NULL), '[]') AS skills
FROM bundle_purchases bp
JOIN skill_bundles sb ON sb.id = bp.bundle_id
LEFT JOIN bundle_items bi ON bi.bundle_id = bp.bundle_id
WHERE bp.id = ${purchaseId} AND bp.user_id = ${auth.userId}
AND bp.status = 'pending'
- GROUP BY bp.id, sb.price_amount
+ GROUP BY bp.id
`;
if (!purchase) return error(res, 404, 'not_found', 'purchase not found or already processed');
- // Mark confirmed.
- await sql`
- UPDATE bundle_purchases
- SET status = 'confirmed', tx_signature = ${txSignature}, confirmed_at = now()
- WHERE id = ${purchaseId}
- `;
+ // Prove the payment on-chain BEFORE unlocking anything. A confirmed verdict
+ // returns the real transaction signature/hash; we never trust a client string.
+ const verdict = await verifyBundlePayment({
+ chain: purchase.chain,
+ agentId: purchase.agent_id,
+ reference: purchase.reference,
+ txHash: evmTxHash,
+ currencyMint: purchase.currency_mint,
+ priceAtomics: String(purchase.price_amount),
+ feeAtomics: String(purchase.platform_fee_amount ?? 0),
+ feeWallet: purchase.platform_fee_wallet,
+ decimals: purchase.mint_decimals ?? 6,
+ userId: auth.userId,
+ });
+
+ if (verdict.status === 'pending')
+ return json(res, 200, { data: { ok: false, status: 'pending', message: 'payment not yet found on-chain — retry shortly' } });
+ if (verdict.status !== 'confirmed')
+ return error(res, 402, 'payment_not_verified', verdict.message || 'payment could not be verified on-chain');
+
+ const txSignature = verdict.txSignature;
+
+ // Atomically claim the purchase. Only the winner unlocks skills and records
+ // revenue; the unique index on (tx_signature) is the hard backstop against a
+ // reused settlement tx.
+ let claimed;
+ try {
+ claimed = await sql`
+ UPDATE bundle_purchases
+ SET status = 'confirmed', tx_signature = ${txSignature}, confirmed_at = now()
+ WHERE id = ${purchaseId} AND status = 'pending'
+ RETURNING id
+ `;
+ } catch (e) {
+ if (e?.code === '23505')
+ return error(res, 409, 'tx_already_used', 'this transaction has already been used for another purchase');
+ throw e;
+ }
+ if (claimed.length === 0)
+ return error(res, 409, 'already_processed', 'purchase is no longer pending');
// Unlock every skill in the bundle — one row per skill.
const skills = purchase.skills;
@@ -163,6 +199,23 @@ async function handleConfirm(req, res, purchaseId) {
`;
}
+ // Record ONE bundle-level revenue event (the skills are unlocked above without
+ // their own per-skill credit, so the creator is paid exactly once for the
+ // bundle price). Gated by the unique intent_id backstop.
+ const gross = Number(purchase.price_amount);
+ const platformFee = Number(purchase.platform_fee_amount ?? 0);
+ const net = gross - platformFee;
+ await sql`
+ INSERT INTO agent_revenue_events
+ (agent_id, intent_id, skill, gross_amount, fee_amount, platform_fee_amount,
+ net_amount, currency_mint, chain, payer_address)
+ VALUES
+ (${purchase.agent_id}, ${'bundle_' + purchase.id}, ${'bundle'},
+ ${gross}, ${0}, ${platformFee}, ${net},
+ ${purchase.currency_mint}, ${purchase.chain}, ${null})
+ ON CONFLICT (intent_id) DO NOTHING
+ `;
+
return json(res, 200, {
data: {
ok: true,
diff --git a/api/nft/mint-scene-confirm.js b/api/nft/mint-scene-confirm.js
index 7944e1247..5d87fa582 100644
--- a/api/nft/mint-scene-confirm.js
+++ b/api/nft/mint-scene-confirm.js
@@ -2,6 +2,7 @@ import { env } from '../_lib/env.js';
import { wrap, cors, error, json, readJson, method, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { solanaConnection } from '../_lib/solana/connection.js';
+import { confirmOrThrow } from '../_lib/solana/confirm.js';
export default wrap(async (req, res) => {
if (cors(req, res)) return;
@@ -38,11 +39,17 @@ export default wrap(async (req, res) => {
try {
const latestBlockhash = await connection.getLatestBlockhash('confirmed');
- await connection.confirmTransaction(
+ await confirmOrThrow(
+ connection,
{ signature, ...latestBlockhash },
'confirmed',
);
} catch (e) {
+ // A confirmed-but-reverted tx is a hard failure, not an uncertain one — never
+ // hand back a soft 200 that reads as success.
+ if (e?.code === 'tx_reverted') {
+ return error(res, 422, 'tx_failed', `Mint transaction reverted on-chain: ${JSON.stringify(e.onChainErr)}`);
+ }
// Return the signature even if confirmation polling times out — the tx may still land.
return json(res, 200, { signature, warning: `Confirmation uncertain: ${e.message}` });
}
diff --git a/api/pump/[action].js b/api/pump/[action].js
index 5ff323061..562eb8e23 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -54,6 +54,7 @@
import { z } from 'zod';
import { Keypair, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';
import { sql } from '../_lib/db.js';
+import { confirmOrThrow } from '../_lib/solana/confirm.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error, rateLimited, respondError } from '../_lib/http.js';
import { putObject, publicUrl as r2PublicUrl } from '../_lib/r2.js';
@@ -1811,7 +1812,7 @@ async function handleLaunchAgent(req, res) {
let signature;
try {
signature = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction(signature, 'confirmed');
+ await confirmOrThrow(conn, signature, 'confirmed');
} catch (err) {
console.error('[pump/launch-agent] send failed', err);
await releaseSpend(reservation.reservationId);
@@ -4557,7 +4558,7 @@ async function signSendWithAgent({ network, agentKeypair, instructions, extraSig
const vtx = new VersionedTransaction(msg);
vtx.sign([agentKeypair, ...extraSigners]);
const signature = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');
+ await confirmOrThrow(conn, { signature, blockhash, lastValidBlockHeight }, 'confirmed');
return signature;
}
diff --git a/api/pump/helius-webhook.js b/api/pump/helius-webhook.js
index b4e74602c..877f42ed0 100644
--- a/api/pump/helius-webhook.js
+++ b/api/pump/helius-webhook.js
@@ -16,7 +16,7 @@
// });
import { timingSafeEqual } from 'node:crypto';
-import { sql } from '../_lib/db.js';
+import { sql, sqlValues } from '../_lib/db.js';
import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
import { parsePumpTrades } from '../_lib/helius.js';
import { WSOL_MINT } from '../_lib/pump-quote.js';
@@ -42,26 +42,26 @@ export default wrap(async (req, res) => {
const trades = txns.flatMap(parsePumpTrades);
if (trades.length === 0) return json(res, 200, { received: txns.length, trades: 0 });
- let inserted = 0;
- for (const t of trades) {
- // Helius parses native-SOL pump.fun swaps, so every monitored trade is
- // SOL-paired: the quote is wrapped SOL and quote_amount == sol_amount.
- const lamports = Math.round(t.sol * 1e9);
- const r = await sql`
- insert into pump_agent_trades (
- mint_id, user_id, wallet, direction, route,
- sol_amount, quote_mint, quote_symbol, quote_amount, tx_signature, network
- )
- select
- m.id, null, ${t.wallet}, ${t.side}, 'bonding_curve',
- ${lamports}, ${WSOL_MINT}, 'SOL', ${lamports}, ${t.signature}, 'mainnet'
- from pump_agent_mints m
- where m.mint = ${t.mint}
- on conflict (tx_signature, network) do nothing
- returning id
- `;
- if (r.length) inserted++;
- }
+ // Helius parses native-SOL pump.fun swaps, so every monitored trade is
+ // SOL-paired: the quote is wrapped SOL and quote_amount == sol_amount.
+ // One multi-row insert, joined to pump_agent_mints exactly as the per-trade
+ // query did — only trades whose mint is a tracked agent mint are persisted,
+ // and (tx_signature, network) collisions are skipped. Atomic in one statement.
+ const rows = trades.map((t) => [t.mint, t.wallet, t.side, Math.round(t.sol * 1e9), t.signature]);
+ const insertedRows = await sql`
+ insert into pump_agent_trades (
+ mint_id, user_id, wallet, direction, route,
+ sol_amount, quote_mint, quote_symbol, quote_amount, tx_signature, network
+ )
+ select
+ m.id, null, v.wallet, v.direction, 'bonding_curve',
+ v.lamports::bigint, ${WSOL_MINT}, 'SOL', v.lamports::bigint, v.signature, 'mainnet'
+ from ( values ${sqlValues(rows)} ) as v(mint, wallet, direction, lamports, signature)
+ join pump_agent_mints m on m.mint = v.mint
+ on conflict (tx_signature, network) do nothing
+ returning id
+ `;
+ const inserted = insertedRows.length;
return json(res, 200, { received: txns.length, trades: trades.length, inserted });
});
diff --git a/api/x402-pay.js b/api/x402-pay.js
index 80fb69b87..3da5db540 100644
--- a/api/x402-pay.js
+++ b/api/x402-pay.js
@@ -490,6 +490,21 @@ async function probeExternalRequirements({ url, method, body }) {
const networks = [...new Set(challenge.accepts.map((a) => a?.network).filter(Boolean))];
return { unsupported: true, networks, challenge };
}
+ // Pin the asset to the configured Solana USDC mint. Without this an external
+ // server could name ANY SPL token as `asset` (e.g. one the agent holds) and we
+ // would sign a transferChecked of THAT token — draining the wallet — while the
+ // USD spend cap (which divides amount by 1e6 assuming 6-decimal USDC) badly
+ // mis-counts a non-USDC charge. Refuse anything that isn't the known USDC mint.
+ if (!USDC_MAINNET_MINT || solAccept.asset !== USDC_MAINNET_MINT) {
+ throw Object.assign(
+ new Error('this service requested payment in a non-USDC asset; agent wallets only pay Solana USDC'),
+ {
+ status: 422,
+ code: 'unsupported_asset',
+ detail: { asset: solAccept.asset ?? null, expected: USDC_MAINNET_MINT ?? null },
+ },
+ );
+ }
const resource =
challenge.resource && typeof challenge.resource === 'object'
? challenge.resource
diff --git a/api/x402/pay-by-name.js b/api/x402/pay-by-name.js
index 2545dc0cc..042a6dd44 100644
--- a/api/x402/pay-by-name.js
+++ b/api/x402/pay-by-name.js
@@ -36,6 +36,7 @@ import {
} from '@solana/spl-token';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { confirmOrThrow } from '../_lib/solana/confirm.js';
import { sql } from '../_lib/db.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -297,7 +298,8 @@ async function handleSend(req, res, auth, body) {
let signature;
try {
signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction(
+ await confirmOrThrow(
+ conn,
{ signature, blockhash, lastValidBlockHeight },
'confirmed',
);
diff --git a/api/x402/vanity.js b/api/x402/vanity.js
index 228c7569b..c9f48ca17 100644
--- a/api/x402/vanity.js
+++ b/api/x402/vanity.js
@@ -602,13 +602,31 @@ export default wrap(async (req, res) => {
res.end(body);
if (paymentId) {
+ // Never persist spendable key material at rest. The live response above
+ // delivers the ground secret once over TLS (this endpoint's stated
+ // contract); the x402 replay/idempotency cache must NOT hold it, or a
+ // Redis read or compromise would recover spendable keys for the cache TTL.
+ // Strip the plaintext secret fields from the STORED copy so a replayed
+ // payment receives the public metadata plus an explicit marker, not the
+ // key. Sealed responses carry only ciphertext (sealedSecret), which is
+ // safe at rest, so they are cached unchanged.
+ let storedBody = body;
+ if (!result?.sealed) {
+ const { secretKeyBase58, secretKey, mnemonic, ...publicMeta } = result;
+ void secretKeyBase58; void secretKey; void mnemonic;
+ storedBody = JSON.stringify({
+ ...publicMeta,
+ secret_omitted_from_cache: true,
+ note: 'The ground secret is returned only once in the original response and is never stored. If you did not capture it, grind again.',
+ });
+ }
await storeResponse({
route: ROUTE,
paymentId,
payloadHash,
paymentHash,
status: 200,
- body,
+ body: storedBody,
contentType,
paymentResponseHeader,
});
diff --git a/data/changelog.json b/data/changelog.json
index 23afcbf17..197fe97f6 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$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-06-21",
+ "title": "Free photo → 3D is now a one-click engine in Forge",
+ "summary": "Turning a photo into a 3D model is free — and now you can pick it directly. Forge's engine selector has a new 'Hunyuan3D / TRELLIS' lane marked with a FREE badge that reconstructs your uploaded photo (or 2–4 angles) into a textured GLB at no cost and with no API key, running on community GPU Spaces with automatic failover across Hunyuan3D, TRELLIS, and TripoSR. Until now the free photo lane only kicked in behind the scenes; it's a first-class choice in the picker, shows live availability, and never silently falls back to a paid engine. The FREE badge also marks every other no-cost lane so you can always see which engines cost nothing.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/forge"
+ },
{
"date": "2026-06-21",
"title": "Authorize $THREE once, then pay with no wallet popups",
diff --git a/eslint.config.js b/eslint.config.js
index 4bdb72db4..9fcdb5108 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -28,8 +28,9 @@ export default [
'**/draco/**',
'**/basis/**',
'public/scene-studio/libs/**',
- 'src/scene-studio/vendor/**',
- '**/vendor/mediapipe/**',
+ // Any directory named `vendor` holds third-party code we don't own
+ // and must not lint (e.g. extensions/*/vendor/readability.js).
+ '**/vendor/**',
'**/*.bundle.js',
'public/dashboard/avaturn-sdk.js',
// Self-contained sub-projects with their own ESLint flat config
diff --git a/pages/forge.html b/pages/forge.html
index ba03fd18b..688b0ade8 100644
--- a/pages/forge.html
+++ b/pages/forge.html
@@ -201,6 +201,31 @@
.aspect button[aria-pressed='true'] .eng-key {
opacity: 0.95;
}
+ /* "FREE" pill on zero-cost engines (catalog free:true). A quiet green
+ accent so the free lanes read at a glance without shouting over the
+ selected-state styling. Sits after the label, before the health dot. */
+ .aspect button .eng-free {
+ margin-left: 0.45em;
+ padding: 0.05em 0.4em;
+ border-radius: 999px;
+ font-size: 0.62em;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ line-height: 1.5;
+ vertical-align: 0.08em;
+ /* Dark theme is the default — a bright mint reads on the dark button. */
+ color: #4ade80;
+ background: rgba(34, 197, 94, 0.14);
+ border: 1px solid rgba(74, 222, 128, 0.38);
+ }
+ html[data-theme='light'] .aspect button .eng-free {
+ color: #0a7d33;
+ background: rgba(34, 197, 94, 0.16);
+ border-color: rgba(34, 197, 94, 0.32);
+ }
+ .aspect button:disabled .eng-free {
+ opacity: 0.5;
+ }
.aspect button:focus-visible,
.chip:focus-visible,
.btn:focus-visible {
diff --git a/public/changelog.json b/public/changelog.json
index a68c87e7a..338664e59 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T04:34:43.784Z",
+ "generated_at": "2026-06-21T04:52:15.005Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -48,6 +48,17 @@
"feature"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "Free photo → 3D is now a one-click engine in Forge",
+ "summary": "Turning a photo into a 3D model is free — and now you can pick it directly. Forge's engine selector has a new 'Hunyuan3D / TRELLIS' lane marked with a FREE badge that reconstructs your uploaded photo (or 2–4 angles) into a textured GLB at no cost and with no API key, running on community GPU Spaces with automatic failover across Hunyuan3D, TRELLIS, and TripoSR. Until now the free photo lane only kicked in behind the scenes; it's a first-class choice in the picker, shows live availability, and never silently falls back to a paid engine. The FREE badge also marks every other no-cost lane so you can always see which engines cost nothing.",
+ "link": "/forge",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-21",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 4a60beb43..469f708f6 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -38,6 +38,14 @@
<category>sdk</category>
<description>A new forge_avatar MCP tool collapses the old two-step flow (generate a mesh, then rig it) into a single call: describe a character in text — or pass reference images — and it generates the textured model, auto-rigs it with a humanoid skeleton, and returns an animation-ready GLB that drops straight into the pose studio and plays the idle/walk library. A built-in humanoid check runs first, so a non-character prompt (furniture, a vehicle, an animal) is turned away with no charge instead of wasting a paid rig. It bundles generation and rigging at their combined price ($0.45) with no hidden markup, and you are never charged if no rigged avatar is produced.</description>
</item>
+ <item>
+ <title>Free photo → 3D is now a one-click engine in Forge</title>
+ <link>https://three.ws/forge</link>
+ <guid isPermaLink="false">2026-06-21:Free photo → 3D is now a one-click engine in Forge</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Turning a photo into a 3D model is free — and now you can pick it directly. Forge's engine selector has a new 'Hunyuan3D / TRELLIS' lane marked with a FREE badge that reconstructs your uploaded photo (or 2–4 angles) into a textured GLB at no cost and with no API key, running on community GPU Spaces with automatic failover across Hunyuan3D, TRELLIS, and TripoSR. Until now the free photo lane only kicked in behind the scenes; it's a first-class choice in the picker, shows live availability, and never silently falls back to a paid engine. The FREE badge also marks every other no-cost lane so you can always see which engines cost nothing.</description>
+ </item>
<item>
<title>Solana is now the default payment network</title>
<link>https://three.ws/dashboard</link>
diff --git a/public/features.json b/public/features.json
index 2c940a645..154febe09 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T04:34:43.761Z",
+ "generated_at": "2026-06-21T04:52:14.964Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/check-api-not-bundled.mjs b/scripts/check-api-not-bundled.mjs
new file mode 100644
index 000000000..867d01eaf
--- /dev/null
+++ b/scripts/check-api-not-bundled.mjs
@@ -0,0 +1,52 @@
+#!/usr/bin/env node
+/**
+ * Guards against the documented `npx vercel build` footgun: it overwrites the
+ * hand-written api/*.js source files in place with huge esbuild bundles. A
+ * bundle committed by accident is near-impossible to review and impossible to
+ * patch — so fail loudly the moment one lands.
+ *
+ * Detection: esbuild's CJS/ESM interop preamble emits these markers near the
+ * top of every bundle. Real source never contains them. We scan only the first
+ * slice of each file so a legitimate string mentioning one of these tokens deep
+ * in a file can't trip the check.
+ *
+ * Run by CI (.github/workflows/ci.yml) and safe to run by hand:
+ * node scripts/check-api-not-bundled.mjs
+ * Exits 0 when clean, 1 (listing offenders) when a bundle is detected.
+ */
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const API_DIR = fileURLToPath(new URL('../api', import.meta.url));
+const MARKERS = ['__defProp', 'createRequire(', '__toESM(', '__toCommonJS('];
+const HEAD_BYTES = 4096; // esbuild's preamble always sits at the very top
+
+/** @returns {string[]} every .js path under dir, recursively */
+function jsFiles(dir) {
+ const out = [];
+ for (const entry of readdirSync(dir)) {
+ const full = join(dir, entry);
+ if (statSync(full).isDirectory()) out.push(...jsFiles(full));
+ else if (entry.endsWith('.js')) out.push(full);
+ }
+ return out;
+}
+
+const offenders = [];
+for (const file of jsFiles(API_DIR)) {
+ const head = readFileSync(file, 'utf8').slice(0, HEAD_BYTES);
+ const hit = MARKERS.find((m) => head.includes(m));
+ if (hit) offenders.push({ file, hit });
+}
+
+if (offenders.length) {
+ console.error('\n✖ esbuild bundle(s) detected in api/ — these clobbered the source files:\n');
+ for (const { file, hit } of offenders) {
+ console.error(` ${file.replace(API_DIR, 'api')} (marker: ${hit})`);
+ }
+ console.error('\nRecover the source with: git restore -- api/ public/\n');
+ process.exit(1);
+}
+
+console.log(`✓ api/ is clean — no esbuild bundles among the source files`);
diff --git a/scripts/x402-modal/.gitignore b/scripts/x402-modal/.gitignore
new file mode 100644
index 000000000..11ff966ae
--- /dev/null
+++ b/scripts/x402-modal/.gitignore
@@ -0,0 +1,2 @@
+key.json
+browser-*.png
diff --git a/scripts/x402-modal/README.md b/scripts/x402-modal/README.md
new file mode 100644
index 000000000..31c5f5364
--- /dev/null
+++ b/scripts/x402-modal/README.md
@@ -0,0 +1,71 @@
+# x402 payment modal — end-to-end test harness
+
+Exercises the **published** `@three-ws/x402-payment-modal` package (the code in
+`../../x402-payment-modal`, not the repo's internal `api/_lib`) with a real,
+funded Solana keypair. Covers both Solana settlement tokens — **USDC** and
+**THREE** — through both the programmatic server helpers and the real browser
+modal UI.
+
+## What gets tested
+
+| Test | Token | Endpoint | Settlement |
+|------|-------|----------|------------|
+| Programmatic A | USDC | live `https://three.ws/api/mcp` ($0.001) | real PayAI facilitator (sponsors SOL fee) |
+| Programmatic B | THREE | local merchant+settler | submitted to RPC by us |
+| Browser | USDC + THREE | local merchant+settler | submitted to RPC by us |
+
+No live three.ws endpoint advertises THREE, so the local merchant
+(`merchant-server.mjs`) issues a spec-correct 402 with both tokens using the
+package's own `solanaAccept`, runs `handleCheckout` for prepare/encode, then
+verifies and broadcasts the signed transaction itself. To keep the throwaway
+wallet whole, `payTo = feePayer = buyer` → every local test is a **self-transfer**
+that costs only the SOL network fee (+ one-time ATA rent).
+
+## The keypair
+
+Provide the throwaway Solana key any of these ways (checked in order):
+
+- `X402_TEST_KEY` env — base58 secret **or** a JSON array string
+- `X402_TEST_KEY_PATH` env — path to a Solana CLI / web3.js JSON array file
+- default file `/home/codespace/.config/x402-test-wallets/solana.json`
+- `scripts/x402-modal/key.json`
+
+## Funding (throwaway amounts)
+
+| Asset | Amount | Why |
+|-------|--------|-----|
+| USDC | ~0.05 | live `/api/mcp` is $0.001/call; lots of headroom |
+| THREE | ~5 | local self-transfer test amount |
+| SOL | ~0.01 | local txs (buyer pays its own fee) + any ATA rent |
+
+The live USDC test is the only one that actually spends value (to three.ws). The
+THREE and local-USDC tests are self-transfers — value returns to the wallet,
+only SOL fees are consumed.
+
+## Run
+
+```bash
+# 0. confirm funding
+node scripts/x402-modal/preflight.mjs
+
+# 1. programmatic e2e (live USDC + local THREE)
+node scripts/x402-modal/merchant-server.mjs # terminal 1 (needed for the THREE test)
+node scripts/x402-modal/run-programmatic.mjs # terminal 2
+# --live only the live USDC test
+# --local only the local THREE test
+
+# 2. browser modal e2e (spawns the merchant itself)
+node scripts/x402-modal/run-browser.mjs
+HEADED=1 node scripts/x402-modal/run-browser.mjs # watch the modal
+```
+
+Browser screenshots land at `browser-USDC.png` / `browser-THREE.png` (gitignored).
+
+## Files
+
+- `_lib.mjs` — keypair loader, balance reader, mint constants
+- `preflight.mjs` — address + balances + readiness check (spends nothing)
+- `merchant-server.mjs` — local x402 merchant + settler built on the package
+- `run-programmatic.mjs` — package server helpers driven with the keypair
+- `page.html` — loads the real modal + injects a keypair-backed provider
+- `run-browser.mjs` — Playwright driver for the modal UI
diff --git a/scripts/x402-modal/_lib.mjs b/scripts/x402-modal/_lib.mjs
new file mode 100644
index 000000000..90aeafedb
--- /dev/null
+++ b/scripts/x402-modal/_lib.mjs
@@ -0,0 +1,83 @@
+// Shared helpers for the @three-ws/x402-payment-modal end-to-end test harness.
+//
+// Loads the throwaway Solana test keypair, exposes the mint constants the live
+// three.ws endpoints use, and reads SOL / USDC / THREE balances so the runner
+// can refuse to spend before the wallet is funded.
+
+import { readFileSync, existsSync } from 'node:fs';
+import bs58 from 'bs58';
+import { Connection, Keypair, PublicKey } from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync,
+ getAccount,
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+
+export const RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+export const SOLANA_MAINNET_CAIP2 = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
+
+// Mints the live three.ws facilitator settles, straight from the 402 challenge.
+export const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+// Candidate locations the keypair-generating agent may drop the throwaway key.
+const KEY_PATH_CANDIDATES = [
+ process.env.X402_TEST_KEY_PATH,
+ '/home/codespace/.config/x402-test-wallets/solana.json',
+ new URL('./key.json', import.meta.url).pathname,
+].filter(Boolean);
+
+/**
+ * Load the buyer keypair from (in order): X402_TEST_KEY (base58 or JSON array
+ * string), then any known key file path. Throws a clear message if none found.
+ * @returns {Keypair}
+ */
+export function loadBuyer() {
+ const inline = process.env.X402_TEST_KEY;
+ if (inline) return keypairFromSecret(inline.trim());
+ for (const p of KEY_PATH_CANDIDATES) {
+ if (p && existsSync(p)) return keypairFromSecret(readFileSync(p, 'utf8').trim());
+ }
+ throw new Error(
+ 'No test keypair found. Set X402_TEST_KEY (base58 or JSON array) or X402_TEST_KEY_PATH, ' +
+ `or drop the key at one of: ${KEY_PATH_CANDIDATES.join(', ')}`,
+ );
+}
+
+function keypairFromSecret(raw) {
+ // JSON array form: [12,34,...] (Solana CLI / web3.js export)
+ if (raw.startsWith('[')) return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(raw)));
+ // base58 secret key
+ return Keypair.fromSecretKey(bs58.decode(raw));
+}
+
+/** Read SOL (lamports → SOL) plus USDC and THREE token balances for an owner. */
+export async function readBalances(conn, owner) {
+ const lamports = await conn.getBalance(owner, 'confirmed');
+ const [usdc, three] = await Promise.all([
+ readToken(conn, owner, new PublicKey(USDC_MINT)),
+ readToken(conn, owner, new PublicKey(THREE_MINT)),
+ ]);
+ return { sol: lamports / 1e9, lamports, usdc, three };
+}
+
+async function readToken(conn, owner, mint) {
+ const ata = getAssociatedTokenAddressSync(
+ mint, owner, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ try {
+ const acct = await getAccount(conn, ata, 'confirmed');
+ return { exists: true, ata: ata.toBase58(), raw: acct.amount, ui: Number(acct.amount) / 1e6 };
+ } catch {
+ return { exists: false, ata: ata.toBase58(), raw: 0n, ui: 0 };
+ }
+}
+
+export function connection() {
+ return new Connection(RPC_URL, 'confirmed');
+}
+
+export function fmt(n, dp = 6) {
+ return Number(n).toLocaleString('en-US', { maximumFractionDigits: dp });
+}
diff --git a/scripts/x402-modal/merchant-server.mjs b/scripts/x402-modal/merchant-server.mjs
new file mode 100644
index 000000000..7305d6533
--- /dev/null
+++ b/scripts/x402-modal/merchant-server.mjs
@@ -0,0 +1,205 @@
+#!/usr/bin/env node
+// Local x402 merchant + settler for exercising @three-ws/x402-payment-modal
+// end to end against a real chain, including the $THREE path that no live
+// three.ws endpoint advertises.
+//
+// It wires the PUBLISHED package code, not the repo's internal api/_lib:
+// • /api/x402-checkout → the package's `handleCheckout` (prepare/encode)
+// • /paid → a real x402 resource: 402 challenge built with the
+// package's `solanaAccept`, then verify + settle.
+//
+// Settlement here submits the buyer-signed transaction to RPC itself (a local
+// stand-in for the PayAI facilitator). To keep the throwaway wallet whole, the
+// challenge sets payTo = feePayer = buyer, so each test is a self-transfer that
+// only costs the SOL network fee (+ one-time ATA rent). Static verification
+// (mint / amount / recipient / authority) runs before broadcast.
+//
+// BUYER=<base58 pubkey> node scripts/x402-modal/merchant-server.mjs
+// # PORT (default 8402), THREE_UI / USDC_UI amounts, SOLANA_RPC_URL all honored
+
+import http from 'node:http';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import {
+ Connection, PublicKey, VersionedTransaction,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+
+// The actual published package source.
+import {
+ solanaAccept, handleCheckout, NETWORK_SOLANA_MAINNET,
+} from '../../x402-payment-modal/server/checkout.js';
+
+import { loadBuyer } from './_lib.mjs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const PORT = Number(process.env.PORT || 8402);
+const RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+const USDC_UI = process.env.USDC_UI || '0.001';
+const THREE_UI = process.env.THREE_UI || '1';
+
+// payTo / feePayer = the buyer itself → self-transfer, value never leaves wallet.
+const buyer = process.env.BUYER || loadBuyer().publicKey.toBase58();
+const conn = new Connection(RPC_URL, 'confirmed');
+
+const TRANSFER_CHECKED = 12; // SPL Token instruction discriminator
+
+function send(res, status, body, headers = {}) {
+ const json = Buffer.from(JSON.stringify(body));
+ res.writeHead(status, {
+ 'content-type': 'application/json',
+ 'access-control-allow-origin': '*',
+ 'access-control-allow-headers': 'content-type, x-payment',
+ 'access-control-expose-headers': 'x-payment-response',
+ 'content-length': json.length,
+ ...headers,
+ });
+ res.end(json);
+}
+
+function readJson(req) {
+ return new Promise((resolve) => {
+ let raw = '';
+ req.on('data', (c) => (raw += c));
+ req.on('end', () => {
+ try { resolve(raw ? JSON.parse(raw) : {}); } catch { resolve({}); }
+ });
+ });
+}
+
+function challenge(resourceUrl) {
+ const common = { payTo: buyer, feePayer: buyer, maxTimeoutSeconds: 60 };
+ return {
+ x402Version: 2,
+ error: 'Payment required',
+ resource: {
+ url: resourceUrl,
+ description: 'Local x402 self-transfer test — pay in USDC or THREE.',
+ mimeType: 'application/json',
+ },
+ accepts: [
+ solanaAccept({ token: 'usdc', uiAmount: USDC_UI, ...common }),
+ solanaAccept({ token: 'three', uiAmount: THREE_UI, ...common }),
+ ],
+ };
+}
+
+// Decode the X-PAYMENT envelope, statically verify the SPL transfer matches one
+// of the advertised accepts, broadcast it, and confirm. Returns the settlement
+// record or throws with a human-readable reason.
+async function verifyAndSettle(xPaymentB64, resourceUrl) {
+ const env = JSON.parse(Buffer.from(xPaymentB64, 'base64').toString('utf8'));
+ const accept = env.accepted;
+ if (!accept || !accept.asset) throw new Error('envelope missing accepted terms');
+
+ const txBuf = Buffer.from(env.payload.transaction, 'base64');
+ const vtx = VersionedTransaction.deserialize(txBuf);
+ const msg = vtx.message;
+ const keys = msg.staticAccountKeys.map((k) => k.toBase58());
+
+ const mint = new PublicKey(accept.asset);
+ const payTo = new PublicKey(accept.payTo);
+ // Resolve the owning token program so we derive the matching ATA — THREE is Token-2022.
+ const mintInfo = await conn.getAccountInfo(mint, 'confirmed');
+ const tokenProgramId = mintInfo?.owner?.equals(TOKEN_2022_PROGRAM_ID) ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;
+ const receiverAta = getAssociatedTokenAddressSync(
+ mint, payTo, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID,
+ ).toBase58();
+
+ let matched = null;
+ for (const ix of msg.compiledInstructions) {
+ if (keys[ix.programIdIndex] !== tokenProgramId.toBase58()) continue;
+ const data = Buffer.from(ix.data);
+ if (data.length < 10 || data[0] !== TRANSFER_CHECKED) continue;
+ const amount = data.readBigUInt64LE(1);
+ const acc = ix.accountKeyIndexes.map((i) => keys[i]);
+ const [source, ixMint, dest, owner] = acc; // TransferChecked account order
+ if (ixMint !== mint.toBase58()) continue;
+ if (dest !== receiverAta) throw new Error(`recipient mismatch: ${dest} != ${receiverAta}`);
+ if (amount.toString() !== accept.amount) throw new Error(`amount ${amount} != required ${accept.amount}`);
+ matched = { source, dest, owner, amount: amount.toString() };
+ break;
+ }
+ if (!matched) throw new Error('no matching TransferChecked instruction for the advertised accept');
+
+ const signature = await conn.sendRawTransaction(txBuf, { skipPreflight: false, maxRetries: 3 });
+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');
+ await conn.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');
+
+ return {
+ success: true,
+ network: accept.network || NETWORK_SOLANA_MAINNET,
+ transaction: signature,
+ payer: matched.owner,
+ asset: accept.asset,
+ amount: accept.amount,
+ };
+}
+
+const server = http.createServer(async (req, res) => {
+ const u = new URL(req.url, `http://localhost:${PORT}`);
+
+ if (req.method === 'OPTIONS') {
+ res.writeHead(204, {
+ 'access-control-allow-origin': '*',
+ 'access-control-allow-methods': 'GET,POST,OPTIONS',
+ 'access-control-allow-headers': 'content-type, x-payment',
+ });
+ return res.end();
+ }
+
+ // Package checkout core: prepare / encode.
+ if (u.pathname === '/api/x402-checkout') {
+ const body = await readJson(req);
+ const out = await handleCheckout({
+ action: u.searchParams.get('action'),
+ body,
+ options: { rpcUrl: RPC_URL },
+ });
+ return send(res, out.status, out.body);
+ }
+
+ // The paid resource.
+ if (u.pathname === '/paid') {
+ const resourceUrl = `http://localhost:${PORT}/paid`;
+ const xPayment = req.headers['x-payment'];
+ if (!xPayment) return send(res, 402, challenge(resourceUrl));
+ try {
+ const settlement = await verifyAndSettle(xPayment, resourceUrl);
+ const receipt = Buffer.from(JSON.stringify(settlement)).toString('base64');
+ return send(res, 200, {
+ message: 'Paid on Solana — thanks!',
+ settled: settlement,
+ }, { 'x-payment-response': receipt });
+ } catch (err) {
+ return send(res, 402, { error: 'settlement_failed', error_description: String(err.message || err) });
+ }
+ }
+
+ // Static test page for the browser modal harness.
+ if (u.pathname === '/' || u.pathname === '/index.html') {
+ const html = readFileSync(join(__dirname, 'page.html'), 'utf8');
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
+ return res.end(html);
+ }
+
+ // Serve the published modal source so the page imports the real thing.
+ if (u.pathname === '/x402.js') {
+ const js = readFileSync(join(__dirname, '../../x402-payment-modal/src/index.js'), 'utf8');
+ res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' });
+ return res.end(js);
+ }
+
+ send(res, 404, { error: 'not_found' });
+});
+
+server.listen(PORT, () => {
+ console.log(`x402 modal merchant+settler on http://localhost:${PORT}`);
+ console.log(` buyer / payTo / feePayer : ${buyer}`);
+ console.log(` checkout core : /api/x402-checkout?action=prepare|encode`);
+ console.log(` paid resource : /paid (USDC ${USDC_UI} | THREE ${THREE_UI})`);
+ console.log(` RPC : ${RPC_URL}`);
+});
diff --git a/scripts/x402-modal/page.html b/scripts/x402-modal/page.html
new file mode 100644
index 000000000..671474005
--- /dev/null
+++ b/scripts/x402-modal/page.html
@@ -0,0 +1,100 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>x402 modal — browser e2e</title>
+ <style>
+ body { font: 15px/1.5 system-ui, sans-serif; max-width: 640px; margin: 48px auto; padding: 0 20px; color: #111; }
+ h1 { font-size: 20px; }
+ button { font: inherit; padding: 12px 18px; border-radius: 10px; border: 1px solid #111; background: #111; color: #fff; cursor: pointer; }
+ button:hover { background: #333; }
+ pre { background: #f4f4f5; padding: 12px; border-radius: 8px; overflow: auto; font-size: 13px; }
+ .row { display: flex; gap: 12px; align-items: center; margin: 18px 0; }
+ .tag { font-size: 12px; color: #666; }
+ </style>
+</head>
+<body>
+ <h1>@three-ws/x402-payment-modal — browser e2e</h1>
+ <p class="tag">Real modal source, keypair-backed provider, local self-transfer settlement.</p>
+
+ <div class="row">
+ <!-- The modal binds this declaratively via init(); we also drive it via X402.pay() from the runner. -->
+ <button id="payBtn" data-x402-endpoint="/paid" data-x402-merchant="x402 local test" data-x402-action="Local paid call">
+ Pay & call /paid
+ </button>
+ </div>
+
+ <pre id="log">waiting…</pre>
+
+ <script type="module">
+ import nacl from 'https://esm.sh/[email protected]';
+
+ const logEl = document.getElementById('log');
+ const lines = [];
+ function log(...a) { lines.push(a.join(' ')); logEl.textContent = lines.join('\n'); }
+ window.__x402log = log;
+
+ // ── Inject a Phantom-shaped provider backed by the throwaway keypair. ──
+ // SECRET_KEY (64-byte array) and PUBKEY (base58) are filled in by the runner.
+ const SECRET_KEY = Uint8Array.from(window.__X402_SECRET || []);
+ const PUBKEY = window.__X402_PUBKEY;
+
+ function signerIndex(tx) {
+ const keys = tx.message.staticAccountKeys.map((k) => k.toBase58());
+ return keys.indexOf(PUBKEY);
+ }
+
+ const provider = {
+ isPhantom: true,
+ publicKey: { toString: () => PUBKEY },
+ async connect() { return { publicKey: { toString: () => PUBKEY } }; },
+ async disconnect() {},
+ // Sign the modal's VersionedTransaction in-place with tweetnacl.
+ async signTransaction(tx) {
+ const msg = tx.message.serialize();
+ const sig = nacl.sign.detached(msg, SECRET_KEY);
+ const idx = signerIndex(tx);
+ if (idx < 0) throw new Error('buyer is not a required signer of this tx');
+ tx.signatures[idx] = sig;
+ return tx;
+ },
+ async signAllTransactions(txs) { return Promise.all(txs.map((t) => this.signTransaction(t))); },
+ async signMessage(message) {
+ return { signature: nacl.sign.detached(message, SECRET_KEY), publicKey: provider.publicKey };
+ },
+ };
+ window.solana = provider;
+ window.phantom = { solana: provider };
+
+ // ── Load the real published modal and point it at this local server. ──
+ const X402 = await import('/x402.js');
+ X402.configure({ checkoutOrigin: location.origin, checkoutPath: '/api/x402-checkout' });
+ log('modal version:', X402.version);
+
+ // Surface results to the runner via globals + DOM events.
+ window.__x402done = null;
+ window.addEventListener('x402:result', (e) => {
+ window.__x402done = { ok: true, detail: e.detail };
+ log('RESULT', JSON.stringify(e.detail).slice(0, 400));
+ });
+ window.addEventListener('x402:error', (e) => {
+ window.__x402done = { ok: false, detail: e.detail };
+ log('ERROR', JSON.stringify(e.detail).slice(0, 400));
+ });
+
+ // Kick off pay() WITHOUT awaiting so the runner can click the token pill
+ // and the Phantom button while the modal is open. Resolution lands on
+ // window.__x402done.
+ window.__startPay = (label) => {
+ window.__x402done = null;
+ log('pay() opening for', label);
+ X402.pay({ endpoint: '/paid', merchant: 'x402 local test', action: `Local ${label} call` })
+ .then((res) => { window.__x402done = { ok: true, detail: res }; log('pay() resolved:', JSON.stringify(res).slice(0, 400)); })
+ .catch((err) => { window.__x402done = { ok: false, detail: { message: String(err.message || err) } }; log('pay() threw:', String(err.message || err)); });
+ };
+
+ log('ready');
+ </script>
+</body>
+</html>
diff --git a/scripts/x402-modal/preflight.mjs b/scripts/x402-modal/preflight.mjs
new file mode 100644
index 000000000..a87938441
--- /dev/null
+++ b/scripts/x402-modal/preflight.mjs
@@ -0,0 +1,34 @@
+#!/usr/bin/env node
+// Preflight: load the throwaway keypair, print its address + on-chain balances,
+// and report whether it holds enough to run the e2e tests. Spends nothing.
+//
+// node scripts/x402-modal/preflight.mjs
+
+import { loadBuyer, connection, readBalances, fmt, RPC_URL } from './_lib.mjs';
+
+// Conservative minimums for a full run (USDC live call + a few local THREE/USDC
+// self-transfers where the buyer also pays SOL fees + any one-time ATA rent).
+const MIN_SOL = 0.01; // local self-transfers pay their own fee + possible ATA rent
+const MIN_USDC = 0.05; // live /api/mcp is $0.001/call; plenty of headroom
+const MIN_THREE = 5; // local THREE self-transfer test amount, with headroom
+
+const buyer = loadBuyer();
+const conn = connection();
+
+console.log('x402 modal test — preflight');
+console.log(' RPC :', RPC_URL);
+console.log(' buyer :', buyer.publicKey.toBase58());
+
+const b = await readBalances(conn, buyer.publicKey);
+console.log('');
+console.log(' SOL :', fmt(b.sol, 9), b.sol >= MIN_SOL ? 'OK' : `LOW (need ~${MIN_SOL})`);
+console.log(' USDC :', fmt(b.usdc.ui), b.usdc.exists === false ? '(no ATA)' : '', b.usdc.ui >= MIN_USDC ? 'OK' : `LOW (need ~${MIN_USDC})`);
+console.log(' THREE :', fmt(b.three.ui), b.three.exists === false ? '(no ATA)' : '', b.three.ui >= MIN_THREE ? 'OK' : `LOW (need ~${MIN_THREE})`);
+console.log('');
+console.log(' USDC ATA :', b.usdc.ata);
+console.log(' THREE ATA:', b.three.ata);
+
+const ready = b.sol >= MIN_SOL && b.usdc.ui >= MIN_USDC && b.three.ui >= MIN_THREE;
+console.log('');
+console.log(ready ? '✓ Funded and ready for full e2e.' : '… Fund the address above, then re-run preflight.');
+process.exit(ready ? 0 : 1);
diff --git a/scripts/x402-modal/run-browser.mjs b/scripts/x402-modal/run-browser.mjs
new file mode 100644
index 000000000..86001d8dd
--- /dev/null
+++ b/scripts/x402-modal/run-browser.mjs
@@ -0,0 +1,103 @@
+#!/usr/bin/env node
+// Browser end-to-end test of @three-ws/x402-payment-modal: loads the real modal
+// source in Chromium, injects a keypair-backed Phantom-shaped provider (no
+// extension), and drives the actual modal UI — token picker → connect → sign →
+// settle — for BOTH Solana tokens against the local merchant+settler.
+//
+// node scripts/x402-modal/run-browser.mjs
+// HEADED=1 node scripts/x402-modal/run-browser.mjs # watch it
+//
+// Spawns merchant-server.mjs itself; settles on-chain (self-transfer).
+
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import bs58 from 'bs58';
+import { chromium } from 'playwright';
+import { loadBuyer, USDC_MINT, THREE_MINT } from './_lib.mjs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const PORT = Number(process.env.PORT || 8402);
+const BASE = `http://localhost:${PORT}`;
+const HEADED = !!process.env.HEADED;
+
+const buyer = loadBuyer();
+const pub = buyer.publicKey.toBase58();
+
+function startMerchant() {
+ const child = spawn('node', [join(__dirname, 'merchant-server.mjs')], {
+ env: { ...process.env, PORT: String(PORT), BUYER: pub, X402_TEST_KEY: bs58.encode(buyer.secretKey) },
+ stdio: ['ignore', 'pipe', 'inherit'],
+ });
+ return new Promise((resolve, reject) => {
+ const to = setTimeout(() => reject(new Error('merchant server did not start in time')), 10000);
+ child.stdout.on('data', (d) => {
+ process.stdout.write(`[merchant] ${d}`);
+ if (String(d).includes('merchant+settler on')) { clearTimeout(to); resolve(child); }
+ });
+ });
+}
+
+async function payToken(page, label, mint) {
+ console.log(`\n--- modal pay: ${label} ---`);
+ await page.evaluate((l) => window.__startPay(l), label);
+ await page.waitForSelector('.x402-modal', { timeout: 15000 });
+ // Pick the token (pills only render when >1 Solana accept).
+ const pill = page.locator(`[data-token-asset="${mint}"]`);
+ if (await pill.count()) {
+ await pill.first().click();
+ console.log(' selected token pill');
+ }
+ await page.locator('[data-wallet="phantom"]').first().click();
+ console.log(' clicked Phantom → signing + settling…');
+
+ // Terminal state = pay() settled OR the modal rendered an in-modal error
+ // (the failure path doesn't reject pay(); it shows a "Try again" box).
+ const done = await page.waitForFunction(() => {
+ if (window.__x402done) return window.__x402done;
+ const box = document.querySelector('.x402-error-box');
+ if (box) return { ok: false, detail: { message: box.textContent.trim() } };
+ return null;
+ }, null, { timeout: 90000 }).then((h) => h.jsonValue());
+ const shot = join(__dirname, `browser-${label}.png`);
+ await page.screenshot({ path: shot, fullPage: true }).catch(() => {});
+ if (!done.ok) throw new Error(`${label} modal failed: ${JSON.stringify(done.detail)}`);
+
+ const sig = done.detail?.payment?.transaction || done.detail?.response?.headers?.['x-payment-response'];
+ console.log(` ✓ ${label} paid via modal. tx: ${sig || '(see result)'}`);
+ console.log(` screenshot: ${shot}`);
+ // Reset for next token.
+ const close = page.locator('[data-close]');
+ if (await close.count()) await close.first().click().catch(() => {});
+ return done.detail;
+}
+
+let merchant;
+let browser;
+let failed = false;
+try {
+ merchant = await startMerchant();
+ browser = await chromium.launch({ headless: !HEADED });
+ const page = await browser.newPage();
+ page.on('console', (m) => { if (m.type() === 'error') console.log(' [page error]', m.text()); });
+
+ await page.addInitScript(({ secret, pubkey }) => {
+ window.__X402_SECRET = secret;
+ window.__X402_PUBKEY = pubkey;
+ }, { secret: Array.from(buyer.secretKey), pubkey: pub });
+
+ await page.goto(BASE, { waitUntil: 'networkidle' });
+ await page.waitForFunction(() => window.solana?.isPhantom && window.__startPay, null, { timeout: 15000 });
+ console.log('page ready; modal + injected provider loaded.');
+
+ await payToken(page, 'USDC', USDC_MINT);
+ await payToken(page, 'THREE', THREE_MINT);
+ console.log('\n✓ Browser e2e passed for both tokens.');
+} catch (e) {
+ failed = true;
+ console.error('\n✗ Browser e2e failed:', e.message);
+} finally {
+ if (browser) await browser.close().catch(() => {});
+ if (merchant) merchant.kill();
+}
+process.exit(failed ? 1 : 0);
diff --git a/scripts/x402-modal/run-programmatic.mjs b/scripts/x402-modal/run-programmatic.mjs
new file mode 100644
index 000000000..3914016b6
--- /dev/null
+++ b/scripts/x402-modal/run-programmatic.mjs
@@ -0,0 +1,140 @@
+#!/usr/bin/env node
+// Programmatic end-to-end test of @three-ws/x402-payment-modal, driving the
+// package's own server helpers with the throwaway keypair as the signer.
+//
+// Test A (live) — USDC on Solana against https://three.ws/api/mcp ($0.001).
+// Real PayAI facilitator settles; buyer needs only USDC.
+// Test B (local) — THREE on Solana against the local merchant+settler. No live
+// endpoint advertises THREE, so we settle it ourselves. Self-
+// transfer (payTo = buyer) → costs only the SOL network fee.
+//
+// node scripts/x402-modal/merchant-server.mjs # in another terminal (for B)
+// node scripts/x402-modal/run-programmatic.mjs # both tests
+// node scripts/x402-modal/run-programmatic.mjs --live # only A
+// node scripts/x402-modal/run-programmatic.mjs --local # only B
+
+import { VersionedTransaction } from '@solana/web3.js';
+import {
+ prepareSolanaCheckout, encodeX402Payment,
+} from '../../x402-payment-modal/server/checkout.js';
+import { loadBuyer, connection, readBalances, fmt, RPC_URL } from './_lib.mjs';
+
+const args = new Set(process.argv.slice(2));
+const runLive = !args.has('--local');
+const runLocal = !args.has('--live');
+const LOCAL = process.env.LOCAL_MERCHANT || 'http://localhost:8402';
+const MCP = 'https://three.ws/api/mcp';
+
+const buyer = loadBuyer();
+const conn = connection();
+const pub = buyer.publicKey.toBase58();
+
+function signTx(txBase64) {
+ const vtx = VersionedTransaction.deserialize(Buffer.from(txBase64, 'base64'));
+ vtx.sign([buyer]);
+ return Buffer.from(vtx.serialize()).toString('base64');
+}
+
+async function explorer(sig) {
+ return `https://solscan.io/tx/${sig}`;
+}
+
+// ── Test A: live USDC via three.ws + PayAI facilitator ──────────────────────
+async function testLiveUsdc() {
+ console.log('\n=== Test A — live USDC on Solana via three.ws/api/mcp ===');
+ const callBody = {
+ jsonrpc: '2.0', id: 1, method: 'tools/call',
+ params: { name: 'agent_reputation', arguments: { address: pub } },
+ };
+
+ const r1 = await fetch(MCP, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify(callBody),
+ });
+ if (r1.status !== 402) throw new Error(`expected 402, got ${r1.status}`);
+ const ch = await r1.json();
+ const accept = ch.accepts.find((a) => String(a.network).startsWith('solana:'));
+ if (!accept) throw new Error('no Solana accept in challenge');
+ console.log(` 402 → pay ${accept.amount} ${accept.extra?.name} to ${accept.payTo}`);
+ console.log(` feePayer (sponsor): ${accept.extra.feePayer}`);
+
+ // PACKAGE: build the unsigned tx the buyer should sign.
+ const prepared = await prepareSolanaCheckout({ accept, buyer: pub, rpcUrl: RPC_URL });
+ const signed = signTx(prepared.tx_base64); // buyer signs as transfer authority only
+ // PACKAGE: wrap into the X-PAYMENT envelope.
+ const { x_payment } = encodeX402Payment({ accept, signedTxBase64: signed, resourceUrl: MCP });
+
+ const r2 = await fetch(MCP, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', accept: 'application/json', 'x-payment': x_payment },
+ body: JSON.stringify(callBody),
+ });
+ console.log(` retry with X-PAYMENT → ${r2.status}`);
+ const settleHeader = r2.headers.get('x-payment-response');
+ const out = await r2.json();
+ if (r2.status !== 200) throw new Error(`paid call failed: ${JSON.stringify(out).slice(0, 300)}`);
+ if (settleHeader) {
+ const rec = JSON.parse(Buffer.from(settleHeader, 'base64').toString('utf8'));
+ const sig = rec.transaction || rec.txHash || rec.signature;
+ console.log(` settled on-chain: ${sig}`);
+ console.log(` ${await explorer(sig)}`);
+ }
+ console.log(' ✓ live USDC payment succeeded; tool result received.');
+}
+
+// ── Test B: local THREE self-transfer, settled by the local merchant ─────────
+async function testLocalThree() {
+ console.log('\n=== Test B — THREE on Solana via local merchant+settler ===');
+ const paid = `${LOCAL}/paid`;
+
+ const r1 = await fetch(paid, { headers: { accept: 'application/json' } });
+ if (r1.status !== 402) throw new Error(`expected 402 from local /paid, got ${r1.status} — is merchant-server running?`);
+ const ch = await r1.json();
+ const accept = ch.accepts.find((a) => a.extra?.name === 'THREE');
+ if (!accept) throw new Error('no THREE accept advertised by local merchant');
+ console.log(` 402 → pay ${accept.amount} THREE to ${accept.payTo} (self)`);
+
+ // PACKAGE server core: prepare via the merchant's /api/x402-checkout.
+ const pr = await fetch(`${LOCAL}/api/x402-checkout?action=prepare`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ accept, buyer: pub }),
+ });
+ const prepared = await pr.json();
+ if (!prepared.tx_base64) throw new Error(`prepare failed: ${JSON.stringify(prepared)}`);
+ const signed = signTx(prepared.tx_base64); // buyer == feePayer → fully signed
+
+ const en = await fetch(`${LOCAL}/api/x402-checkout?action=encode`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ accept, signed_tx_base64: signed, resource_url: paid }),
+ });
+ const { x_payment } = await en.json();
+ if (!x_payment) throw new Error('encode returned no x_payment');
+
+ const r2 = await fetch(paid, { headers: { accept: 'application/json', 'x-payment': x_payment } });
+ const out = await r2.json();
+ console.log(` retry with X-PAYMENT → ${r2.status}`);
+ if (r2.status !== 200) throw new Error(`THREE settlement failed: ${JSON.stringify(out)}`);
+ const sig = out.settled?.transaction;
+ console.log(` settled on-chain: ${sig}`);
+ console.log(` ${await explorer(sig)}`);
+ console.log(' ✓ THREE payment built by the package settled on-chain.');
+}
+
+console.log('x402 modal — programmatic e2e');
+console.log(' buyer:', pub);
+const before = await readBalances(conn, buyer.publicKey);
+console.log(` balances: ${fmt(before.sol, 6)} SOL | ${fmt(before.usdc.ui)} USDC | ${fmt(before.three.ui)} THREE`);
+
+let failed = false;
+if (runLive) {
+ try { await testLiveUsdc(); } catch (e) { failed = true; console.error(' ✗ Test A failed:', e.message); }
+}
+if (runLocal) {
+ try { await testLocalThree(); } catch (e) { failed = true; console.error(' ✗ Test B failed:', e.message); }
+}
+
+const after = await readBalances(conn, buyer.publicKey);
+console.log(`\n balances after: ${fmt(after.sol, 6)} SOL | ${fmt(after.usdc.ui)} USDC | ${fmt(after.three.ui)} THREE`);
+console.log(` spent: ${fmt(before.sol - after.sol, 9)} SOL | ${fmt(before.usdc.ui - after.usdc.ui)} USDC`);
+process.exit(failed ? 1 : 0);
diff --git a/sdk/src/solana-attestations.js b/sdk/src/solana-attestations.js
index f33d6ee65..ef71d3eed 100644
--- a/sdk/src/solana-attestations.js
+++ b/sdk/src/solana-attestations.js
@@ -55,7 +55,12 @@ async function signAndSend({ network, preferred, ix, feePayer }) {
const tx = new Transaction({ feePayer, recentBlockhash: blockhash }).add(ix);
const { signature } = await provider.signAndSendTransaction(tx);
- await conn.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');
+ const conf = await conn.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');
+ // A confirmed-but-reverted tx carries its error in value.err rather than
+ // throwing — surface it so a failed attestation never looks like a success.
+ if (conf?.value?.err) {
+ throw new Error(`attestation tx ${signature} reverted on-chain: ${JSON.stringify(conf.value.err)}`);
+ }
return signature;
}
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 5e45a0b76..70b77aa21 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -10,6 +10,7 @@
import { openTalkMode } from './voice/talk-mode.js';
import { downloadAvatar } from './avatar-export.js';
import { fbxFromUrl } from './remesh-convert.js';
+import { safeUrl } from './safe-url.js';
import { log } from './shared/log.js';
import { emptyStateHTML, errorStateHTML } from './shared/state-kit.js';
import { mountViewSwitcher } from './view-switcher.js';
@@ -217,7 +218,7 @@ function renderShell(glbUrl) {
const author = avatar.author || avatar.attribution;
const byLine = author?.handle
? author.profileUrl || author.url
- ? `<p class="av-by">by <a href="${esc(author.profileUrl || author.url)}" target="_blank" rel="noopener">${esc(author.displayName || author.handle)}</a></p>`
+ ? `<p class="av-by">by <a href="${esc(safeUrl(author.profileUrl || author.url))}" target="_blank" rel="noopener">${esc(author.displayName || author.handle)}</a></p>`
: `<p class="av-by">by ${esc(author.displayName || author.handle)}</p>`
: avatar.owner_username
? `<p class="av-by">by <a href="/u/${esc(avatar.owner_username)}">@${esc(avatar.owner_username)}</a></p>`
diff --git a/src/bounties.js b/src/bounties.js
index 47aded23f..b500b4e66 100644
--- a/src/bounties.js
+++ b/src/bounties.js
@@ -7,6 +7,8 @@
// bounty, not just the first page. Sort + query are reflected in the URL so a
// view is shareable and survives refresh. Read-only.
+import { safeUrl } from './safe-url.js';
+
const API = '/api/pump-bounties';
const PAGE = 30;
const MAX_SCAN_PAGES = 24; // safety ceiling on the full-board search scan
@@ -266,7 +268,7 @@ function card(b) {
(a) => a.kind === 'image' || /^image\//.test(a.contentType || ''),
);
const thumb = img
- ? `<div class="card-thumb" style="background-image:url('${esc(img.url)}')">${statusBadge(b.status, true)}</div>`
+ ? `<div class="card-thumb" style="background-image:url('${esc(safeUrl(img.url, ''))}')">${statusBadge(b.status, true)}</div>`
: `<div class="card-thumb empty">🎯${statusBadge(b.status, true)}</div>`;
const usd = b.reward.totalUsd != null ? `$${fmtNum(b.reward.totalUsd)}` : '—';
const token = b.reward.sol != null ? `◎ ${fmtNum(b.reward.sol)} SOL` : tokenLabel(b);
diff --git a/src/communities.js b/src/communities.js
index 9442c69db..7aa000da6 100644
--- a/src/communities.js
+++ b/src/communities.js
@@ -8,6 +8,7 @@
// a source is empty or unreachable, the UI says so and offers a way forward.
import { log } from './shared/log.js';
+import { safeUrl } from './safe-url.js';
const NAME_STORAGE_KEY = 'walk:player-name';
const AVATAR_CHOICE_KEY = 'communities:avatar-choice';
const DEFAULT_AVATAR_URL = '/avatars/default.glb';
@@ -448,7 +449,7 @@ function renderCoinProfile(coin) {
if (coin.telegram) socials.push(['Telegram', coin.telegram]);
if (coin.website) socials.push(['Website', coin.website]);
$('cp-socials').innerHTML = socials
- .map(([label, href]) => `<a class="cp-social" href="${escAttr(href)}" target="_blank" rel="noopener">${esc(label)} ↗</a>`)
+ .map(([label, href]) => `<a class="cp-social" href="${escAttr(safeUrl(href))}" target="_blank" rel="noopener">${esc(label)} ↗</a>`)
.join('');
$('coin-profile-skeleton').hidden = true;
diff --git a/src/forge.js b/src/forge.js
index 1d32490fb..f6bb57871 100644
--- a/src/forge.js
+++ b/src/forge.js
@@ -170,9 +170,16 @@ function setCinema(on) {
const ENGINE_KEY_SVG =
'<svg class="eng-key" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="7.5" cy="15.5" r="4.5"/><path d="M10.7 12.3 21 2"/><path d="m15 7 3 3"/><path d="m18 4 3 3"/></svg>';
-// Short engine labels for the picker buttons, keyed by backend id.
+// Inline "FREE" pill appended to zero-cost engine buttons (catalog `free:true`).
+// The free lanes are named by engine like every other button; this pill — not
+// the label — is what marks them free, so two free lanes never both read "Free".
+const ENGINE_FREE_PILL = '<span class="eng-free" aria-hidden="true">FREE</span>';
+
+// Short engine labels for the picker buttons, keyed by backend id. Free lanes
+// carry the FREE pill above, so they are labelled by engine name like the rest.
const ENGINE_LABELS = {
- nvidia: 'Free',
+ nvidia: 'NVIDIA',
+ huggingface: 'Hunyuan3D',
trellis: 'Fast',
meshy: 'Meshy',
tripo: 'Tripo',
@@ -457,11 +464,12 @@ function buildEngineButtons() {
// BYOK engines carry a small key glyph so the picker shows at a glance
// which lanes run on the user's own API key vs the free/included ones.
const short = ENGINE_LABELS[b.id] || b.label;
- btn.innerHTML = `<span class="eng-label">${short}</span>${b.byok ? ENGINE_KEY_SVG : ''}`;
+ btn.innerHTML = `<span class="eng-label">${short}</span>${b.free ? ENGINE_FREE_PILL : ''}${b.byok ? ENGINE_KEY_SVG : ''}`;
const keyNote = b.byok ? ` · uses your own ${KEY_HINTS[b.byok]?.label || b.byok} key` : '';
- btn.title = `${b.label} — ${b.blurb}${keyNote}`;
+ const freeNote = b.free ? ' · free, no API key' : '';
+ btn.title = `${b.label} — ${b.blurb}${freeNote}${keyNote}`;
// aria-label survives the dynamic title rewrites in updateEngineAvailability.
- btn.setAttribute('aria-label', `${b.label}${keyNote}`);
+ btn.setAttribute('aria-label', `${b.label}${freeNote}${keyNote}`);
btn.setAttribute('aria-pressed', String(b.id === selectedEngine.backend));
els.engine.appendChild(btn);
}
diff --git a/src/galaxy.js b/src/galaxy.js
index d0670e326..d34911e44 100644
--- a/src/galaxy.js
+++ b/src/galaxy.js
@@ -245,7 +245,7 @@ function buildLegend(clusters) {
btn.type = 'button';
btn.dataset.cluster = String(c.id);
btn.innerHTML =
- `<span class="gx-legend-swatch" style="color:${c.color};background:${c.color}"></span>` +
+ `<span class="gx-legend-swatch" style="color:${escapeHtml(c.color)};background:${escapeHtml(c.color)}"></span>` +
`<span class="gx-legend-name">${escapeHtml(c.label)}</span>` +
`<span class="gx-legend-count">${c.size}</span>`;
btn.title = c.theme || c.label;
@@ -406,7 +406,7 @@ function selectAgent(index, fly = false) {
}
els.gxCardName.textContent = a.name;
els.gxCardConstellation.innerHTML = cluster
- ? `<span class="gx-tip-dot" style="background:${cluster.color}"></span>${escapeHtml(cluster.label)}`
+ ? `<span class="gx-tip-dot" style="background:${escapeHtml(cluster.color)}"></span>${escapeHtml(cluster.label)}`
: '';
els.gxCardDesc.textContent = a.description || 'No description.';
@@ -597,7 +597,7 @@ function updateHover() {
const c = state.clusterById.get(a.cluster);
els.gxTip.innerHTML =
`<div class="gx-tip-name">${escapeHtml(a.name)}</div>` +
- (c ? `<div class="gx-tip-cluster"><span class="gx-tip-dot" style="background:${c.color}"></span>${escapeHtml(c.label)}</div>` : '');
+ (c ? `<div class="gx-tip-cluster"><span class="gx-tip-dot" style="background:${escapeHtml(c.color)}"></span>${escapeHtml(c.label)}</div>` : '');
els.gxTip.hidden = false;
els.gxCanvas.classList.add('gx-pointing');
positionTip();
diff --git a/src/go.js b/src/go.js
index 2fce27afc..427e8a7b8 100644
--- a/src/go.js
+++ b/src/go.js
@@ -1,5 +1,7 @@
// Bounty board — three.ws/go
+import { safeUrl } from './safe-url.js';
+
const API = '/api/bounties';
let currentTab = 'feed';
let currentUser = null;
@@ -177,7 +179,7 @@ function renderSubmissionCard(s) {
s.media_url && isImageUrl(s.media_url)
? `<img class="sub-media" src="${esc(s.media_url)}" alt="submission media" loading="lazy" />`
: s.media_url
- ? `<a href="${esc(s.media_url)}" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-sm" style="display:inline-flex;gap:6px;margin-bottom:8px;">🔗 View proof</a>`
+ ? `<a href="${esc(safeUrl(s.media_url))}" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-sm" style="display:inline-flex;gap:6px;margin-bottom:8px;">🔗 View proof</a>`
: '';
return `
diff --git a/src/ibm-proof.js b/src/ibm-proof.js
index 6f2796228..8c51f73b0 100644
--- a/src/ibm-proof.js
+++ b/src/ibm-proof.js
@@ -291,10 +291,10 @@ function renderProof(data) {
['TimeSeries', m.timeseries],
['Narrator', m.narrator],
['Guardian', m.guardian],
- ].filter(([, v]) => v).map(([k, v]) => `<span class="m"><b>${k}</b> ${v}</span>`).join('');
+ ].filter(([, v]) => v).map(([k, v]) => `<span class="m"><b>${k}</b> ${escapeHtml(v)}</span>`).join('');
const at = data.attester?.address;
$('p-attester').innerHTML = at
- ? `<a href="${data.attester.explorer}" target="_blank" rel="noopener" style="color:var(--brand-blue-light);text-decoration:none">${at}</a>`
+ ? `<a href="${escapeHtml(explorerHref(data.attester.explorer))}" target="_blank" rel="noopener" style="color:var(--brand-blue-light);text-decoration:none">${escapeHtml(at)}</a>`
: '<span style="color:var(--faint)">not configured — set AVATAR_WALLET_SECRET to enable notarization</span>';
}
@@ -354,7 +354,7 @@ async function notarize(data) {
const out = await r.json();
const oc = out.onchain || {};
if (oc.submitted && oc.signature) {
- showNotice('ok', `Notarized on-chain. <a href="${oc.explorer}" target="_blank" rel="noopener">View on Solscan ↗</a>`);
+ showNotice('ok', `Notarized on-chain. <a href="${escapeHtml(explorerHref(oc.explorer))}" target="_blank" rel="noopener">View on Solscan ↗</a>`);
avatar.speak('Done. The forecast is now permanently on-chain — anyone can verify it.');
avatar.animate('celebrate');
addToFeed(out);
@@ -395,11 +395,11 @@ function renderFeed() {
const cls = it.dir === 'up' ? 'up' : it.dir === 'down' ? 'down' : '';
const arrow = it.dir === 'up' ? '▲' : it.dir === 'down' ? '▼' : '—';
const right = it.explorer
- ? `<div style="display:flex;flex-direction:column;align-items:flex-end;gap:3px"><a class="tx" href="${it.explorer}" target="_blank" rel="noopener">Solscan ↗</a><button class="copy verify-item" data-sig="${it.signature}">verify on-chain ↻</button></div>`
+ ? `<div style="display:flex;flex-direction:column;align-items:flex-end;gap:3px"><a class="tx" href="${escapeHtml(explorerHref(it.explorer))}" target="_blank" rel="noopener">Solscan ↗</a><button class="copy verify-item" data-sig="${escapeHtml(it.signature)}">verify on-chain ↻</button></div>`
: '<span class="l2">pending</span>';
return `<div class="attestation">
<div class="badge2 ${cls}">${arrow}</div>
- <div class="meta"><div class="l1">${it.symbol} · ${fmtPct(it.changePct)}</div><div class="l2">${it.digest.slice(0, 40)}…</div></div>
+ <div class="meta"><div class="l1">${escapeHtml(it.symbol)} · ${fmtPct(it.changePct)}</div><div class="l2">${escapeHtml(String(it.digest).slice(0, 40))}…</div></div>
${right}
</div>`;
}).join('');
@@ -467,8 +467,8 @@ function renderPicker() {
const chg = p.change24h != null
? `<span style="color:${p.change24h >= 0 ? 'var(--up)' : 'var(--down)'};margin-left:7px">${p.change24h >= 0 ? '+' : ''}${Number(p.change24h).toFixed(1)}%</span>`
: '';
- return `<button class="chip" role="tab" data-pool="${p.pool}" aria-selected="${i === 0 ? 'true' : 'false'}">
- <span class="sym">${sym}</span><span class="nm">${nm}</span><span class="px">${px}${chg}</span>
+ return `<button class="chip" role="tab" data-pool="${escapeHtml(p.pool)}" aria-selected="${i === 0 ? 'true' : 'false'}">
+ <span class="sym">${escapeHtml(sym)}</span><span class="nm">${escapeHtml(nm)}</span><span class="px">${px}${chg}</span>
</button>`;
}).join('');
el.querySelectorAll('.chip').forEach((c) => c.addEventListener('click', () => {
diff --git a/src/marketplace.js b/src/marketplace.js
index 42d7c8ecb..8fee9436d 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -18,6 +18,7 @@ import {
bindDetailExtras,
} from './marketplace-detail.js';
import { onchainBadgeHTML } from './shared/onchain-badge.js';
+import { safeUrl } from './safe-url.js';
import { walletChipHTML, walletChipEl, wireWalletChips } from './shared/agent-wallet-chip.js';
import { seeInWorldHref, hasCustomAvatar } from './shared/agent-3d.js';
import { coinChipHTML } from './shared/agent-coin.js';
@@ -1456,7 +1457,7 @@ function openAvatarModal(avatar) {
$('avatar-modal-desc')?.insertAdjacentElement('afterend', authorEl);
}
authorEl.innerHTML = avatar.author.profileUrl
- ? `by <a href="${escapeHtml(avatar.author.profileUrl)}" rel="author">${escapeHtml(avatar.author.displayName || avatar.author.handle)}</a>`
+ ? `by <a href="${escapeHtml(safeUrl(avatar.author.profileUrl))}" rel="author">${escapeHtml(avatar.author.displayName || avatar.author.handle)}</a>`
: `by ${escapeHtml(avatar.author.displayName || avatar.author.handle)}`;
} else if (authorEl) { authorEl.textContent = ''; }
@@ -4036,7 +4037,7 @@ function renderOnchainDetail(a) {
const fact = (label, value, link) => {
if (!value) return '';
const v = link
- ? `<a href="${escapeHtml(link)}" target="_blank" rel="noopener">${escapeHtml(value)}</a>`
+ ? `<a href="${escapeHtml(safeUrl(link))}" target="_blank" rel="noopener">${escapeHtml(value)}</a>`
: escapeHtml(value);
return `<div class="onchain-fact"><span class="onchain-fact-label">${escapeHtml(label)}</span><span class="onchain-fact-value">${v}</span></div>`;
};
@@ -4392,7 +4393,7 @@ function renderAvatarCard(a, spotlight = false) {
const when = a.createdAt ? liveTime(a.createdAt) : '';
const author = a.author;
const authorLine = author?.profileUrl
- ? `<a class="card-author" href="${escapeHtml(author.profileUrl)}" rel="author">${escapeHtml(author.displayName || author.handle)}</a>`
+ ? `<a class="card-author" href="${escapeHtml(safeUrl(author.profileUrl))}" rel="author">${escapeHtml(author.displayName || author.handle)}</a>`
: author?.handle
? `<span class="card-author">${escapeHtml(author.displayName || author.handle)}</span>`
: `<span class="card-author muted">Anonymous</span>`;
@@ -4788,7 +4789,7 @@ async function loadAvatarDetail(id) {
const authorEl = $('avatar-detail-author');
if (avatar.author?.handle) {
authorEl.innerHTML = avatar.author.profileUrl
- ? `by <a href="${escapeHtml(avatar.author.profileUrl)}" rel="author">${escapeHtml(avatar.author.displayName || avatar.author.handle)}</a>`
+ ? `by <a href="${escapeHtml(safeUrl(avatar.author.profileUrl))}" rel="author">${escapeHtml(avatar.author.displayName || avatar.author.handle)}</a>`
: `by ${escapeHtml(avatar.author.displayName || avatar.author.handle)}`;
}
diff --git a/src/safe-url.js b/src/safe-url.js
new file mode 100644
index 000000000..c9059da8c
--- /dev/null
+++ b/src/safe-url.js
@@ -0,0 +1,21 @@
+/**
+ * Returns `url` only if it is a same-origin relative path or an http(s) URL.
+ * Anything else — `javascript:`, `data:`, `vbscript:`, blank, or non-string —
+ * collapses to a safe placeholder, neutralising script-scheme injection in
+ * `href`, `src`, and CSS `url(...)` sinks.
+ *
+ * Allowed: strings starting with `/`, `./`, `../`, `#`, or matching `^https?:`
+ * (case-insensitive, after trimming surrounding whitespace).
+ *
+ * @param {unknown} url - candidate URL, typically user- or remote-controlled.
+ * @param {string} [fallback='#'] - returned when `url` is rejected.
+ * @returns {string} the original url if safe, otherwise `fallback`.
+ */
+export function safeUrl(url, fallback = '#') {
+ if (typeof url !== 'string') return fallback;
+ const trimmed = url.trim();
+ if (!trimmed) return fallback;
+ if (/^(?:\/|\.\/|\.\.\/|#)/.test(trimmed)) return url;
+ if (/^https?:/i.test(trimmed)) return url;
+ return fallback;
+}
diff --git a/src/three-access.js b/src/three-access.js
index 2c531d8ec..7228d003f 100644
--- a/src/three-access.js
+++ b/src/three-access.js
@@ -28,6 +28,7 @@
// the UI never throws and the server stays the only authority on eligibility.
import { getConnectedWallet, getConnectedWalletAddress } from './wallet.js';
+import { safeUrl } from './safe-url.js';
const ACCESS_TTL_MS = 30_000;
// The matrix cache is keyed by identity (the connected wallet, or null for the
@@ -380,7 +381,7 @@ export function showThreeGate(gate, opts = {}) {
<p class="tg-desc" id="tg-desc">${sub}</p>
${gate.why ? `<p class="tg-why">${escapeHtml(gate.why)}</p>` : ''}
<div class="tg-actions">
- <a class="tg-btn tg-btn--primary" id="tg-get" href="${escapeHtml(getUrl)}">Get $THREE</a>
+ <a class="tg-btn tg-btn--primary" id="tg-get" href="${escapeHtml(safeUrl(getUrl))}">Get $THREE</a>
${payBtn}
<a class="tg-btn tg-btn--ghost" href="${ECONOMY_URL}">$THREE price &amp; chart</a>
</div>
diff --git a/src/three-lock.js b/src/three-lock.js
index 9d2cacc88..729772391 100644
--- a/src/three-lock.js
+++ b/src/three-lock.js
@@ -17,6 +17,8 @@
// Fully keyboard-navigable (real <a>/<button>), ARIA-labelled, reduced-motion
// aware, and responsive. Never throws — a missing target is a no-op.
+import { safeUrl } from './safe-url.js';
+
const ECONOMY_URL = '/three-token';
const SIGN_IN_URL = '/login';
const LINK_WALLET_URL = '/dashboard/account#wallets';
@@ -159,7 +161,7 @@ function renderLocked(state) {
const held = state.held || { label: 'Member', level: 0 };
const reason = state.reason || 'insufficient_tier';
const tone = tierTone(required.id);
- const getUrl = escapeHtml(state.getThreeUrl || ECONOMY_URL);
+ const getUrl = escapeHtml(safeUrl(state.getThreeUrl || ECONOMY_URL));
const sub =
reason === 'sign_in'
diff --git a/tests/api/forge-free-first.test.js b/tests/api/forge-free-first.test.js
index f7a059cf1..5b95a8fc3 100644
--- a/tests/api/forge-free-first.test.js
+++ b/tests/api/forge-free-first.test.js
@@ -133,6 +133,9 @@ function makeRes() {
setHeader(name, value) {
this.headers[String(name).toLowerCase()] = value;
},
+ getHeader(name) {
+ return this.headers[String(name).toLowerCase()];
+ },
end(body) {
this.body = body ? JSON.parse(body) : null;
},
@@ -206,6 +209,54 @@ describe('forge free-first reconstruct ordering', () => {
expect(res.headers['retry-after']).toBe('30');
});
+ it('routes an EXPLICIT huggingface pick to the free lane and never the paid one', async () => {
+ // The user deliberately chose the free engine for a photo upload.
+ process.env.HF_TOKEN = 'test-hf-token';
+ replicateSubmit.mockClear();
+ hfSubmit.mockClear();
+ try {
+ const req = makeReq({
+ image_urls: ['https://cdn.example/photo.png'],
+ backend: 'huggingface',
+ tier: 'standard',
+ path: 'image',
+ skip_validation: true,
+ });
+ const res = makeRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body.backend).toBe('huggingface');
+ expect(res.body.mode).toBe('image_to_3d');
+ expect(hfSubmit).toHaveBeenCalled();
+ expect(replicateSubmit).not.toHaveBeenCalled();
+ } finally {
+ delete process.env.HF_TOKEN;
+ }
+ });
+
+ it('surfaces a designed busy error (never a paid fallback) when an explicit free pick has no lane', async () => {
+ // HF_TOKEN unset → the free Spaces provider is unavailable. An explicit free
+ // pick must NOT silently spend on the paid Replicate account; it returns a
+ // designed, retryable error instead.
+ delete process.env.HF_TOKEN;
+ replicateSubmit.mockClear();
+ const req = makeReq({
+ image_urls: ['https://cdn.example/photo.png'],
+ backend: 'huggingface',
+ tier: 'standard',
+ path: 'image',
+ skip_validation: true,
+ });
+ const res = makeRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(502);
+ expect(res.body.error).toBe('provider_busy');
+ expect(res.body.backend).toBe('huggingface');
+ expect(replicateSubmit).not.toHaveBeenCalled();
+ });
+
it('restores the paid-default ORDER when FORGE_PREFER_FREE=false (Replicate tried first)', async () => {
// The flag flips ORDER, not availability. With free-first OFF the paid
// Replicate default is attempted FIRST; HF still serves as the post-failure
diff --git a/tests/api/forge-health.test.js b/tests/api/forge-health.test.js
index 025a70442..9f42955af 100644
--- a/tests/api/forge-health.test.js
+++ b/tests/api/forge-health.test.js
@@ -11,6 +11,7 @@ import { BACKENDS } from '../../api/_lib/forge-tiers.js';
const ENV_VARS = [
'NVIDIA_API_KEY',
+ 'HF_TOKEN',
'REPLICATE_API_TOKEN',
'GCP_HUNYUAN3D_URL',
'GCP_TRIPOSG_URL',
@@ -82,6 +83,7 @@ describe('forge-health — per-backend verdicts', () => {
mockUpstreams([]);
const health = await probeForgeHealth();
expect(health.backends.nvidia.status).toBe('unconfigured');
+ expect(health.backends.huggingface.status).toBe('unconfigured');
expect(health.backends.trellis.status).toBe('unconfigured');
expect(health.backends.hunyuan3d.status).toBe('unconfigured');
});
@@ -134,6 +136,29 @@ describe('forge-health — per-backend verdicts', () => {
expect(health.backends.nvidia.status).toBe('down');
});
+ it('passes HuggingFace when whoami authenticates the token (200)', async () => {
+ process.env.HF_TOKEN = 'hf_test';
+ mockUpstreams([['huggingface.co', 200]]);
+ const health = await probeForgeHealth();
+ expect(health.backends.huggingface.status).toBe('ok');
+ });
+
+ it('fails HuggingFace on a rejected token (401) and degrades on rate-limit (429)', async () => {
+ process.env.HF_TOKEN = 'hf_bad';
+ mockUpstreams([['huggingface.co', 401]]);
+ expect((await probeForgeHealth()).backends.huggingface.status).toBe('down');
+ resetForgeHealthCache();
+ mockUpstreams([['huggingface.co', 429]]);
+ expect((await probeForgeHealth()).backends.huggingface.status).toBe('degraded');
+ });
+
+ it('never probes HuggingFace when HF_TOKEN is unset', async () => {
+ mockUpstreams([]);
+ const health = await probeForgeHealth();
+ expect(health.backends.huggingface.status).toBe('unconfigured');
+ expect(backendProbes()).toEqual([]);
+ });
+
it('probes a deployed Hunyuan3D worker and reports 5xx as down', async () => {
process.env.GCP_HUNYUAN3D_URL = 'https://hunyuan3d.example.run.app';
process.env.GCP_RECONSTRUCTION_KEY = 'secret';
diff --git a/tests/api/forge-tiers.test.js b/tests/api/forge-tiers.test.js
index 04e50200d..f5eef1512 100644
--- a/tests/api/forge-tiers.test.js
+++ b/tests/api/forge-tiers.test.js
@@ -119,6 +119,66 @@ describe('forge-tiers — NVIDIA NIM backend registration', () => {
});
});
+// The free HuggingFace Spaces lane is the free option for PHOTO input — the
+// counterpart to the text-only NVIDIA lane. It must surface in the catalog as a
+// free, image-capable, platform-keyed engine gated on HF_TOKEN, and be an
+// explicit opt-in (never the silent auto-default).
+describe('forge-tiers — HuggingFace free image lane', () => {
+ const prev = process.env.HF_TOKEN;
+ afterEach(() => {
+ if (prev === undefined) delete process.env.HF_TOKEN;
+ else process.env.HF_TOKEN = prev;
+ });
+
+ it('registers a free, platform-keyed image backend that accepts user photos', () => {
+ const hf = BACKENDS.huggingface;
+ expect(hf).toBeTruthy();
+ expect(hf.provider).toBe('huggingface');
+ expect(hf.byok).toBe(false);
+ expect(hf.paths).toEqual(['image']);
+ expect(hf.requiresEnv).toEqual(['HF_TOKEN']);
+ expect(hf.free).toBe(true);
+ expect(hf.userImages).toBe(true);
+ expect(hf.credits).toBeNull();
+ expect(hf.baseEta).toBeGreaterThan(0);
+ });
+
+ it('is configured only when HF_TOKEN is present', () => {
+ delete process.env.HF_TOKEN;
+ expect(backendIsConfigured('huggingface')).toBe(false);
+ process.env.HF_TOKEN = 'hf_test';
+ expect(backendIsConfigured('huggingface')).toBe(true);
+ });
+
+ it('surfaces in the catalog as a free, photo-capable, selectable engine', () => {
+ process.env.HF_TOKEN = 'hf_test';
+ const hf = buildCatalog().backends.find((b) => b.id === 'huggingface');
+ expect(hf).toBeTruthy();
+ expect(hf.free).toBe(true);
+ expect(hf.user_images).toBe(true);
+ expect(hf.byok).toBeNull();
+ expect(hf.configured).toBe(true);
+ const est = hf.estimates.image.find((e) => e.tier === 'standard');
+ expect(est.eta_seconds).toBeGreaterThan(0);
+ expect(est.credits).toBeNull();
+ });
+
+ it('stays selectable when explicitly named on the image path with photos', () => {
+ expect(
+ resolveBackendId({ path: 'image', tier: 'standard', backend: 'huggingface', userImages: true }),
+ ).toBe('huggingface');
+ });
+
+ // An explicit opt-in lane, not a silent default — the standing image default
+ // stays trellis (which free-firsts to HF internally), so resolution without an
+ // explicit pick never surprises a caller onto the HF Spaces lane.
+ it('is never the auto-resolved default for the image path', () => {
+ delete process.env.HF_TOKEN;
+ expect(resolveBackendId({ path: 'image', tier: 'standard' })).not.toBe('huggingface');
+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: true })).not.toBe('huggingface');
+ });
+});
+
// The Hunyuan3D lane runs on its own Cloud Run worker. It must never report
// configured off the avatar pipeline's GCP_RECONSTRUCTION_URL — that service's
// face pipeline rejects every non-face image, so the lane looked live in the
diff --git a/tests/api/x402-forge.test.js b/tests/api/x402-forge.test.js
index ca2774fbf..ed03b3e1e 100644
--- a/tests/api/x402-forge.test.js
+++ b/tests/api/x402-forge.test.js
@@ -98,6 +98,9 @@ function makeRes() {
setHeader(name, value) {
this.headers[String(name).toLowerCase()] = value;
},
+ getHeader(name) {
+ return this.headers[String(name).toLowerCase()];
+ },
end(body) {
this.body = body ?? null;
},
diff --git a/tests/http-cache-control.test.js b/tests/http-cache-control.test.js
new file mode 100644
index 000000000..45eb01ba7
--- /dev/null
+++ b/tests/http-cache-control.test.js
@@ -0,0 +1,84 @@
+/**
+ * http.js Cache-Control boundary — unit tests.
+ *
+ * json()/text() are secure-by-default: they emit `no-store` UNLESS the handler
+ * already set a Cache-Control header (the documented way a public read opts into
+ * CDN caching) or passes one via the headers argument. Error responses must
+ * NEVER inherit a permissive cache header, so error()/serverError()/
+ * validationError() force `no-store`.
+ *
+ * Regression guard: previously json() unconditionally forced `no-store`, so a
+ * handler that did `res.setHeader('cache-control', 'public, s-maxage=60')` right
+ * before `json()` (e.g. /u/:username) was silently never cached.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { json, text, error, validationError } from '../api/_lib/http.js';
+
+// Minimal ServerResponse stand-in: case-insensitive header store + end capture.
+function fakeRes() {
+ const headers = {};
+ return {
+ statusCode: 0,
+ body: undefined,
+ ended: false,
+ setHeader(k, v) { headers[String(k).toLowerCase()] = v; },
+ getHeader(k) { return headers[String(k).toLowerCase()]; },
+ end(b) { this.body = b; this.ended = true; },
+ _headers: headers,
+ };
+}
+
+describe('json() cache-control', () => {
+ it('defaults to no-store when nothing is set', () => {
+ const res = fakeRes();
+ json(res, 200, { ok: true });
+ expect(res.getHeader('cache-control')).toBe('no-store');
+ });
+
+ it('respects a Cache-Control the handler set before calling json()', () => {
+ const res = fakeRes();
+ res.setHeader('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=300');
+ json(res, 200, { ok: true });
+ expect(res.getHeader('cache-control')).toBe('public, s-maxage=60, stale-while-revalidate=300');
+ });
+
+ it('respects a cache-control passed via the headers argument', () => {
+ const res = fakeRes();
+ json(res, 200, { ok: true }, { 'cache-control': 'public, s-maxage=120' });
+ expect(res.getHeader('cache-control')).toBe('public, s-maxage=120');
+ });
+
+ it('still applies the security headers', () => {
+ const res = fakeRes();
+ json(res, 200, { ok: true });
+ expect(res.getHeader('x-content-type-options')).toBe('nosniff');
+ expect(res.getHeader('content-type')).toMatch(/application\/json/);
+ });
+});
+
+describe('text() cache-control', () => {
+ it('respects a pre-set Cache-Control', () => {
+ const res = fakeRes();
+ res.setHeader('cache-control', 'public, max-age=300');
+ text(res, 200, 'hello');
+ expect(res.getHeader('cache-control')).toBe('public, max-age=300');
+ });
+});
+
+describe('error responses never cache', () => {
+ it('error() forces no-store even when the success path set a permissive header', () => {
+ const res = fakeRes();
+ res.setHeader('cache-control', 'public, s-maxage=600');
+ error(res, 404, 'not_found', 'nope');
+ expect(res.getHeader('cache-control')).toBe('no-store');
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('validationError() forces no-store', () => {
+ const res = fakeRes();
+ res.setHeader('cache-control', 'public, s-maxage=600');
+ validationError(res, { status: 400, code: 'validation_error', message: 'bad', issues: [] });
+ expect(res.getHeader('cache-control')).toBe('no-store');
+ });
+});
diff --git a/tests/solana-confirm.test.js b/tests/solana-confirm.test.js
new file mode 100644
index 000000000..041e08de8
--- /dev/null
+++ b/tests/solana-confirm.test.js
@@ -0,0 +1,62 @@
+/**
+ * confirmOrThrow — unit tests.
+ *
+ * Solana's `Connection.confirmTransaction` resolves normally for a transaction
+ * that landed in a block but reverted during execution; the on-chain error is
+ * carried in `result.value.err`, NOT thrown. Every server-signed money path
+ * routes its confirmation through confirmOrThrow so a revert becomes a thrown
+ * error the caller handles, instead of being silently recorded as confirmed.
+ *
+ * These tests exercise the helper against a fake Connection so no RPC is hit.
+ */
+
+import { describe, it, expect, vi } from 'vitest';
+import { confirmOrThrow } from '../api/_lib/solana/confirm.js';
+
+function fakeConn(value) {
+ return {
+ confirmTransaction: vi.fn().mockResolvedValue({ context: { slot: 1 }, value }),
+ };
+}
+
+describe('confirmOrThrow', () => {
+ it('returns the confirmation result for a successful tx (value.err === null)', async () => {
+ const conn = fakeConn({ err: null });
+ const out = await confirmOrThrow(conn, 'sig123', 'confirmed');
+ expect(out.value.err).toBeNull();
+ expect(conn.confirmTransaction).toHaveBeenCalledWith('sig123', 'confirmed');
+ });
+
+ it('throws when the tx landed but reverted (value.err set)', async () => {
+ const conn = fakeConn({ err: { InstructionError: [0, { Custom: 6001 }] } });
+ await expect(confirmOrThrow(conn, 'sigABC', 'confirmed')).rejects.toThrow(/reverted on-chain/);
+ });
+
+ it('tags the thrown error with code, signature, and the on-chain err', async () => {
+ const onChainErr = { InstructionError: [1, 'ProgramFailedToComplete'] };
+ const conn = fakeConn({ err: onChainErr });
+ await expect(confirmOrThrow(conn, 'deadbeef', 'confirmed')).rejects.toMatchObject({
+ code: 'tx_reverted',
+ signature: 'deadbeef',
+ onChainErr,
+ });
+ });
+
+ it('extracts the signature from the object strategy form', async () => {
+ const conn = fakeConn({ err: { foo: 'bar' } });
+ await expect(
+ confirmOrThrow(conn, { signature: 'objSig', blockhash: 'bh', lastValidBlockHeight: 9 }, 'confirmed'),
+ ).rejects.toMatchObject({ signature: 'objSig', code: 'tx_reverted' });
+ });
+
+ it('defaults the commitment to "confirmed"', async () => {
+ const conn = fakeConn({ err: null });
+ await confirmOrThrow(conn, 'sig');
+ expect(conn.confirmTransaction).toHaveBeenCalledWith('sig', 'confirmed');
+ });
+
+ it('does not swallow a genuinely thrown RPC/timeout error', async () => {
+ const conn = { confirmTransaction: vi.fn().mockRejectedValue(new Error('block height exceeded')) };
+ await expect(confirmOrThrow(conn, 'sig')).rejects.toThrow(/block height exceeded/);
+ });
+});
diff --git a/workers/oracle/agent-loop.js b/workers/oracle/agent-loop.js
index 63f72faa1..f2d9a9e96 100644
--- a/workers/oracle/agent-loop.js
+++ b/workers/oracle/agent-loop.js
@@ -8,7 +8,7 @@
import { sql } from '../../api/_lib/db.js';
import { log } from './log.js';
import { evaluateWatch } from '../../api/_lib/oracle/agent-eval.js';
-import { executeAction, agentBudget } from './executor.js';
+import { executeAction } from './executor.js';
import { alertAgentEntry, alertPersonalEntry, alertPersonalSignal, alertPersonalConvictionDrop, alertFollowers } from '../../api/_lib/oracle/alerts.js';
// Module cursor — only consider verdicts scored since the last pass.
@@ -74,12 +74,44 @@ async function droppedConvictionPositions(network, mints) {
`.catch((e) => { log.warn('droppedConvictionPositions query failed:', e.message); return []; });
}
-async function alreadyActed(agentId, mint, network) {
- const r = await sql`
- select 1 from oracle_watch_actions
- where agent_id = ${agentId} and mint = ${mint} and network = ${network} limit 1
+/**
+ * Open positions + today's committed SOL for every agent in one pass — the
+ * batched form of executor.agentBudget, keyed by agent_id. Preserves the exact
+ * budget semantics (open = outcome 'open' & status filled/taken; spent = sum of
+ * size_sol over the last 24h for filled/taken). Agents with no rows are absent
+ * from the Map and default to a zero budget at the call site.
+ */
+async function agentBudgets(agentIds, network) {
+ const map = new Map();
+ if (!agentIds.length) return map;
+ const rows = await sql`
+ select agent_id,
+ count(*) filter (where outcome = 'open' and status in ('filled','taken'))::int as open_count,
+ coalesce(sum(size_sol) filter (where acted_at > now() - interval '24 hours' and status in ('filled','taken')), 0)::numeric as spent_today
+ from oracle_watch_actions
+ where agent_id = any(${agentIds}) and network = ${network}
+ group by agent_id
`.catch(() => []);
- return r.length > 0;
+ for (const r of rows) {
+ map.set(r.agent_id, { openCount: Number(r.open_count) || 0, spentTodaySol: Number(r.spent_today) || 0 });
+ }
+ return map;
+}
+
+/**
+ * Set of "agentId:mint" pairs that already have an action for the given agents
+ * and mints — the batched form of alreadyActed. Scoping to the watch agents and
+ * the fresh-coin mints keeps the result bounded.
+ */
+async function actedPairs(agentIds, mints, network) {
+ const set = new Set();
+ if (!agentIds.length || !mints.length) return set;
+ const rows = await sql`
+ select agent_id, mint from oracle_watch_actions
+ where agent_id = any(${agentIds}) and mint = any(${mints}) and network = ${network}
+ `.catch(() => []);
+ for (const r of rows) set.add(`${r.agent_id}:${r.mint}`);
+ return set;
}
/**
@@ -110,10 +142,17 @@ export async function actOnFreshCoins(cfg, coins) {
}).catch(() => {});
}
- let acted = 0;
+ // Pre-aggregate budgets (one GROUP BY) and already-acted pairs (one query)
+ // for every armed agent against the fresh mints, replacing per-watch and
+ // per-(watch,coin) round trips inside the loops below.
+ const watchAgentIds = [...new Set(watches.map((w) => w.agent_id))];
+ const budgets = await agentBudgets(watchAgentIds, cfg.network);
+ const acted = await actedPairs(watchAgentIds, freshMints, cfg.network);
+
+ let actedCount = 0;
const liveEntries = [];
for (const watch of watches) {
- const { openCount, spentTodaySol } = await agentBudget(watch.agent_id, cfg.network);
+ const { openCount, spentTodaySol } = budgets.get(watch.agent_id) || { openCount: 0, spentTodaySol: 0 };
let open = openCount, spent = spentTodaySol;
// Personal signal alerts: fire once per watch for coins that clear its threshold
@@ -129,10 +168,15 @@ export async function actOnFreshCoins(cfg, coins) {
for (const coin of coins) {
const decision = evaluateWatch({ watch, coin, openCount: open, spentTodaySol: spent });
if (!decision.act) continue;
- if (await alreadyActed(watch.agent_id, coin.mint, cfg.network)) continue;
+ const actedKey = `${watch.agent_id}:${coin.mint}`;
+ if (acted.has(actedKey)) continue;
const res = await executeAction({ cfg, watch, coin, size: decision.size, reason: decision.reason });
+ // executeAction always logs an action row (filled/skipped/failed), so the
+ // original per-iteration alreadyActed check would dedup this pair on any
+ // later coin in this pass — mirror that by recording it now.
+ acted.add(actedKey);
if (res.status === 'filled') {
- acted += 1; open += 1; spent += decision.size;
+ actedCount += 1; open += 1; spent += decision.size;
// Platform channel: live-mode entries only (too much noise for sim).
if (watch.mode === 'live' && cfg.mode === 'live') {
liveEntries.push({
@@ -172,9 +216,9 @@ export async function actOnFreshCoins(cfg, coins) {
}
}
}
- if (acted) log.info(`agent loop: ${acted} action(s) across ${watches.length} armed agent(s)`);
+ if (actedCount) log.info(`agent loop: ${actedCount} action(s) across ${watches.length} armed agent(s)`);
if (liveEntries.length) alertAgentEntry(liveEntries).catch(() => {});
- return acted;
+ return actedCount;
}
export async function runAgentPass(cfg) {
diff --git a/workers/oracle/executor.js b/workers/oracle/executor.js
index d53723c7a..0ce16f0bc 100644
--- a/workers/oracle/executor.js
+++ b/workers/oracle/executor.js
@@ -131,7 +131,13 @@ async function buyOnPump({ network, mint, solAmount, payer, useJito = false, jit
const tx = new VersionedTransaction(msg);
tx.sign([payer]);
const sig = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });
- await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
+ const conf = await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
+ // confirmTransaction resolves for a tx that landed-but-reverted; the on-chain
+ // error is in value.err, not a thrown exception. Surface it so the executor
+ // never records a reverted oracle execution as a confirmed one.
+ if (conf?.value?.err) {
+ throw new Error(`oracle tx ${sig} reverted on-chain: ${JSON.stringify(conf.value.err)}`);
+ }
return sig;
}
diff --git a/x402-payment-modal/server/checkout.js b/x402-payment-modal/server/checkout.js
index a7739b84e..19b2db0bf 100644
--- a/x402-payment-modal/server/checkout.js
+++ b/x402-payment-modal/server/checkout.js
@@ -25,6 +25,7 @@ import {
} from '@solana/web3.js';
import {
TOKEN_PROGRAM_ID,
+ TOKEN_2022_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID,
getAssociatedTokenAddressSync,
createAssociatedTokenAccountIdempotentInstruction,
@@ -148,6 +149,7 @@ const MINT_DECIMALS_TTL_MS = 5 * 60 * 1000;
const BLOCKHASH_TTL_MS = 8 * 1000;
const mintDecimalsCache = new Map(); // `${rpc}:${mint}` -> { decimals, at }
const blockhashCache = new Map(); // rpc -> { blockhash, at }
+const tokenProgramCache = new Map(); // `${rpc}:${mint}` -> { programId, at }
/** Thrown for any client-correctable problem; carries an HTTP `status` + `code`. */
export class CheckoutError extends Error {
@@ -207,11 +209,31 @@ function validateAccept(accept) {
return accept;
}
-async function getMintDecimals(conn, rpc, mint) {
+// Resolve which token program owns a mint — legacy SPL Token or Token-2022.
+// Pump.fun mints (including THREE) and many newer assets are Token-2022, whose
+// program id differs; deriving ATAs or building transferChecked with the wrong
+// program yields the wrong accounts and an unprocessable transaction. The owner
+// is immutable, so cache it like decimals.
+async function getTokenProgramId(conn, rpc, mint) {
+ const key = `${rpc}:${mint.toBase58()}`;
+ const hit = tokenProgramCache.get(key);
+ if (hit && Date.now() - hit.at < MINT_DECIMALS_TTL_MS) return hit.programId;
+ const info = await conn.getAccountInfo(mint, 'confirmed');
+ if (!info) throw new CheckoutError(400, 'invalid_request', `mint ${mint.toBase58()} not found on this network`);
+ const owner = info.owner;
+ let programId;
+ if (owner.equals(TOKEN_2022_PROGRAM_ID)) programId = TOKEN_2022_PROGRAM_ID;
+ else if (owner.equals(TOKEN_PROGRAM_ID)) programId = TOKEN_PROGRAM_ID;
+ else throw new CheckoutError(400, 'invalid_request', `mint ${mint.toBase58()} is not an SPL token (owner ${owner.toBase58()})`);
+ tokenProgramCache.set(key, { programId, at: Date.now() });
+ return programId;
+}
+
+async function getMintDecimals(conn, rpc, mint, programId) {
const key = `${rpc}:${mint.toBase58()}`;
const hit = mintDecimalsCache.get(key);
if (hit && Date.now() - hit.at < MINT_DECIMALS_TTL_MS) return hit.decimals;
- const info = await getMint(conn, mint);
+ const info = await getMint(conn, mint, 'confirmed', programId);
mintDecimalsCache.set(key, { decimals: info.decimals, at: Date.now() });
return info.decimals;
}
@@ -249,13 +271,18 @@ export async function prepareSolanaCheckout({ accept, buyer, rpcUrl, devnetRpcUr
const buyerPubkey = new PublicKey(buyer);
const amount = BigInt(accept.amount);
+ // Pick the owning token program (legacy SPL Token vs Token-2022) so ATAs,
+ // the idempotent create, and transferChecked all target the right program —
+ // THREE and other pump.fun mints are Token-2022.
+ const tokenProgramId = await getTokenProgramId(conn, rpc, mint);
+
const senderAta = getAssociatedTokenAddressSync(
- mint, buyerPubkey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ mint, buyerPubkey, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID,
);
const receiverAta = getAssociatedTokenAddressSync(
- mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ mint, payTo, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID,
);
- const mintDecimals = await getMintDecimals(conn, rpc, mint);
+ const mintDecimals = await getMintDecimals(conn, rpc, mint, tokenProgramId);
const ixs = [
ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),
@@ -267,13 +294,13 @@ export async function prepareSolanaCheckout({ accept, buyer, rpcUrl, devnetRpcUr
if (!receiverInfo) {
ixs.push(
createAssociatedTokenAccountIdempotentInstruction(
- feePayer, receiverAta, payTo, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ feePayer, receiverAta, payTo, mint, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID,
),
);
}
ixs.push(
createTransferCheckedInstruction(
- senderAta, mint, receiverAta, buyerPubkey, amount, mintDecimals, [], TOKEN_PROGRAM_ID,
+ senderAta, mint, receiverAta, buyerPubkey, amount, mintDecimals, [], tokenProgramId,
),
);
diff --git a/x402-payment-modal/test/token2022.integration.test.js b/x402-payment-modal/test/token2022.integration.test.js
new file mode 100644
index 000000000..877874487
--- /dev/null
+++ b/x402-payment-modal/test/token2022.integration.test.js
@@ -0,0 +1,34 @@
+// Opt-in integration test: confirms prepareSolanaCheckout builds a valid
+// transaction for BOTH a legacy SPL Token mint (USDC) and a Token-2022 mint
+// (THREE). It needs a live Solana mainnet RPC, so it is skipped unless
+// X402_INTEGRATION is set — the default `npm test` stays fully offline.
+//
+// X402_INTEGRATION=1 npm test
+// X402_INTEGRATION=1 SOLANA_RPC_URL=https://your-rpc npm test
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { prepareSolanaCheckout, solanaAccept } from '../server/checkout.js';
+
+const RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+const run = process.env.X402_INTEGRATION ? test : test.skip;
+
+// Any valid base58 owner works as buyer/payTo/feePayer — prepare only reads the
+// mint account and a blockhash; it never inspects the buyer's balance.
+const ADDR = 'So11111111111111111111111111111111111111112';
+
+run('prepareSolanaCheckout builds a tx for legacy USDC', async () => {
+ const accept = solanaAccept({ token: 'usdc', uiAmount: '0.001', payTo: ADDR, feePayer: ADDR });
+ const prepared = await prepareSolanaCheckout({ accept, buyer: ADDR, rpcUrl: RPC });
+ assert.equal(prepared.network, accept.network);
+ assert.ok(Buffer.from(prepared.tx_base64, 'base64').length > 100);
+});
+
+run('prepareSolanaCheckout builds a tx for Token-2022 THREE', async () => {
+ // THREE (FeMbDoX…pump) is owned by the Token-2022 program. Before the
+ // program-detection fix this threw TokenInvalidAccountOwnerError.
+ const accept = solanaAccept({ token: 'three', uiAmount: '1', payTo: ADDR, feePayer: ADDR });
+ const prepared = await prepareSolanaCheckout({ accept, buyer: ADDR, rpcUrl: RPC });
+ assert.equal(prepared.network, accept.network);
+ assert.ok(Buffer.from(prepared.tx_base64, 'base64').length > 100);
+});