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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
backend security + production fixes: BSC anti-replay DB, EVM withdrawals, bonfida ESM fix
nirholasa69d803061c2
diff --git a/PRODUCTION_ISSUES.md b/PRODUCTION_ISSUES.mdnew file mode 100644index 000000000..0895629d1--- /dev/null+++ b/PRODUCTION_ISSUES.md@@ -0,0 +1,264 @@+# Production Issues — Vercel Log Audit (2026-05-24)++**Directive:** Fix every item below completely. No shortcuts, no stubs, no TODOs. Wire 100%. Real APIs, real implementations. Do not report back until every issue is resolved and verified.++---++## CRITICAL — Repeated 500 errors++### 1. Missing DB table: `agent_reviews`+- **Error:** `NeonDbError: relation "agent_reviews" does not exist` — 52× 500 from `/api/marketplace/[action]`+- **Root cause:** `api/marketplace/[action].js:317-318` and `:377-378` query `agent_reviews` table which is absent from `api/_lib/schema.sql` entirely.+- **Fix:** Add `agent_reviews` table to schema.sql (columns: `id uuid PK`, `agent_id uuid FK→agent_identities`, `user_id uuid FK→users`, `rating int`, `review text`, `created_at timestamptz`). Apply additive `ALTER TABLE IF NOT EXISTS` style. Also add a separate `api/marketplace/reviews.js` handler if it doesn't already work for the `reviews` action.++### 2. Missing DB tables: `x_triggers`, `x_scheduled_posts`, `x_pending_reviews`+- **Error:** `column "agent_id" does not exist` — 72× from `/api/cron/[name]` run-x-triggers+- **Root cause:** `api/cron/[name].js:2686` queries `x_triggers` with columns `id, user_id, agent_id, kind, config, auto_publish, last_fired_at, last_state`. None of these three tables exist in `api/_lib/schema.sql`.+- **Fix:** Add all three tables to schema.sql:+ - `x_triggers(id uuid PK, user_id uuid FK→users, agent_id uuid FK→agent_identities, kind text, config jsonb, auto_publish bool, enabled bool, last_fired_at timestamptz, last_state jsonb, created_at timestamptz)`+ - `x_scheduled_posts(id uuid PK, user_id uuid FK→users, agent_id uuid FK→agent_identities, text text, scheduled_at timestamptz, published_at timestamptz, created_at timestamptz)`+ - `x_pending_reviews(id uuid PK, user_id uuid FK→users, trigger_id uuid FK→x_triggers, agent_id uuid FK→agent_identities, text text, reviewed_at timestamptz, approved bool, created_at timestamptz)`++### 3. Missing DB column: `club_tips.amount_atomics`+- **Error:** `column "total_atomics" does not exist` — 7× 500 from `/api/club/leaderboard`+- **Root cause:** `api/club/leaderboard.js` computes `sum(t.amount_atomics)` aliased as `total_atomics`. The column `amount_atomics` doesn't exist in the production `club_tips` table (schema.sql has it defined but the migration hasn't run or production table was created from an older schema).+- **Fix:** Add `ALTER TABLE club_tips ADD COLUMN IF NOT EXISTS amount_atomics numeric;` migration to schema.sql. Verify `club_tips` schema matches all columns leaderboard.js and tips.js reference.++---++## HIGH — Infrastructure & Rate Limiting (thousands of errors)++### 4. Solana RPC Rate Limiting (Helius 429) — 900+ errors+- **Error:** `[agents/solana/wallet] balance fetch failed ... 429 Too Many Requests: max usage reached` — 900+ occurrences across `/api/agents/[id]`+- **Root cause:** Helius free/starter plan being exhausted. Every agent page load triggers a live Solana RPC call for balance. No caching.+- **Fix:**+ - Add Redis/KV cache in `api/_lib/balances.js` (or inline in `api/agents/[id].js`): cache balance responses for 60s per wallet address.+ - Implement RPC endpoint rotation: fall through to public RPC (`https://api.mainnet-beta.solana.com`) when Helius returns 429.+ - Add exponential backoff retry (max 2 retries, 500ms/1s delays) before the fallback.+ - Same treatment for `getSignaturesForAddress` activity calls.++### 5. Cron Timeout (504) — 393 occurrences+- **Error:** `Vercel Runtime Timeout Error: Task timed out after 30 seconds` — from `index-delegations` cron+- **Root cause:** EVM delegation indexer fetches too many blocks in one invocation; ETH mainnet RPC caps `eth_getLogs` at 50-block ranges. Each cron run tries to catch up many hundreds of blocks before the 30s deadline.+- **Fix:**+ - In `api/cron/[name].js` `indexDelegations` handler: reduce block batch size to ≤25 for mainnet (chainId=1), ≤50 for L2s.+ - Add a hard time budget check (`Date.now() - start > 22000`) after each batch and break early, saving cursor progress.+ - Log a warning on early exit so the next invocation continues from the saved cursor.++### 6. OpenRouter Free Model Rate-Limited — 7× 502 from `/api/chat`+- **Error:** `[chat:openrouter] 429 ... meta-llama/llama-3.3-70b-instruct:free is temporarily rate-limited`+- **Root cause:** Free tier model rate-limited upstream; no fallback model configured.+- **Fix:** In the OpenRouter chat path, add model fallback chain: on 429, retry once with `meta-llama/llama-3.1-8b-instruct:free`, then fall back to `anthropic/claude-haiku` (paid). Log which model was actually used in the response.++---++## HIGH — Missing Env Vars (configuration gaps)++### 7. `X402_AGENT_SOLANA_SECRET_BASE58` not set — 1× 503+- **Error:** `[api] unhandled Error: agent wallet not configured (set X402_AGENT_SOLANA_SECRET_BASE58)` from `/api/x402-pay`+- **Root cause:** `api/x402-pay.js:287` throws when env var is absent. This error is unhandled (bubbles to Vercel as a 503).+- **Fix:** Wrap `loadAgentKeypair()` call in a try/catch that returns `error(res, 503, 'config_missing', 'payment processing not available')` — same pattern used for subdomain minting. Also verify the env var is set in Vercel production dashboard.++### 8. `ZAUTH_API_KEY` not set — 1954× 500 from `/api/threews/subdomain`+- **Error:** `[zauth] disabled: ZAUTH_API_KEY not set` logged at `level=info` but response is 500+- **Root cause:** The zauth instrument layer logs the "disabled" message but something else in `api/threews/subdomain.js` is throwing. Investigate: the subdomain handler calling into zauth when disabled may have an unguarded code path.+- **Fix:** Confirm `api/_lib/zauth.js` `instrument()` returns cleanly (noop) when `ZAUTH_API_KEY` is absent. The 500 status on these requests indicates a secondary crash — trace the actual stack and fix the unhandled error. Set `ZAUTH_API_KEY` in Vercel env if the zauth service is in use.++---++## HIGH — Unhandled Errors / Missing Error Handling++### 9. `@bonfida/spl-name-service` ESM bundling crash — 2× 500 from `/api/threews/subdomain`+- **Error:** `[api] unhandled file:///var/task/node_modules/@bonfida/spl-name-service/dist/esm/instructions/burnInstruction.js:1 import"../node_modules/buffer/index.js"` — SyntaxError from module parse+- **Root cause:** Vercel's bundler is hitting an ESM module that re-imports `buffer` with a bare relative specifier that breaks in the serverless bundle.+- **Fix:** Pin `@bonfida/spl-name-service` to a CommonJS-compatible version or add a Vercel `bundler` override in `vercel.json` to externalize it: `{ "functions": { "api/threews/subdomain.js": { "excludeFiles": "" } } }`. Alternatively switch to a direct Solana RPC call for SNS resolution to avoid the broken dependency.++### 10. `api/permissions/[action].js` — unhandled UUID validation — 1× 500+- **Error:** `NeonDbError: invalid input syntax for type uuid: "missing-id-xyz"`+- **Root cause:** `handleList` passes user-supplied `id` directly into a UUID column without validation.+- **Fix:** Before the SQL query, validate with `/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)` and return `error(res, 400, 'invalid_id', 'id must be a valid UUID')` if invalid.++### 11. `api/widgets/view` — FK violation on insert — 1× error+- **Error:** `insert or update on table "widget_views" violates foreign key constraint "widget_views_widget_id_fkey"`+- **Root cause:** Widget views are being logged for widget IDs that don't exist in the `widgets` table (deleted or invalid).+- **Fix:** Wrap the `widget_views` insert in a try/catch — this is a best-effort analytics write. Swallow FK violation errors (Postgres error code `23503`) silently. Already 204 status but the unhandled error logs it as a warning.++### 12. `api/mocap/clips.js` — NeonDB `$1` syntax error still in production — 2× 500+- **Error:** `NeonDbError: syntax error at or near "$1"` from `handleList`+- **Root cause:** Fix was committed locally but may not be deployed, OR there is a second code path in `handleList` with the nested `sql\`...\`` template fragment pattern.+- **Fix:** Audit the entire `handleList` function in `api/mocap/clips.js`. Every `sql\`...\`` that uses another `sql\`...\`` as a fragment must be converted to the positional-params pattern. Deploy.++---++## MEDIUM — Missing Routes (404s)++### 13. `/api/agents/[id]/solana` → 404 for 500+ requests+- **Error:** 404 for `/api/agents/{uuid}/solana` — hits from many real agent UUIDs+- **Root cause:** `vercel.json:603-604` routes `/api/agents/([^/]+)/solana` → `/api/agents/[id]` but the `[id].js` handler doesn't handle the `/solana` sub-action — it likely returns 404 for unrecognised paths.+- **Fix:** In `api/agents/[id].js`, detect when the request path ends with `/solana` (check `req.url.includes('/solana')`), extract the agent UUID, and forward to the Solana wallet/balance handler. Return the correct Solana data (balance, address, etc.) at that endpoint.++### 14. `/api/agent-strategy` — 404 × 2+- **Error:** 404 for `/api/agent-strategy`+- **Root cause:** No handler file exists at `api/agent-strategy.js` and no route in `vercel.json`.+- **Fix:** Create `api/agent-strategy.js` implementing whatever the strategy endpoint should do (check git history / callers for intent), or add a redirect to the correct endpoint in `vercel.json`.++### 15. Template literal in URL — `/agent/$%7Bo(p.value)%7D` — 2× 404+- **Error:** 404 for `/agent/${o(p.value)}` (URL-encoded template literal)+- **Root cause:** A JS template literal is being used as an href instead of being evaluated — likely a `href="\`/agent/${...}\`"` vs `href="/agent/${...}"` bug in a frontend component.+- **Fix:** Search the frontend code for `href="\`/agent/` or `href='` + template literals and fix the string interpolation.++---++## MEDIUM — Method Not Allowed (405s)++### 16. x402 endpoints don't handle HEAD requests — 100+ occurrences+- **Error:** 405 for `HEAD /api/x402/skill-marketplace`, `HEAD /api/x402/model-check`, `HEAD /api/x402/dance-tip`, `HEAD /api/x402/symbol-availability`, `HEAD /.well-known/x402`+- **Root cause:** Health checkers and x402station probers send HEAD requests; the route handlers only accept GET/POST.+- **Fix:** In `api/_lib/http.js` `method()` helper (or in `wrap()`), respond to HEAD requests with the same headers as GET but no body. Standard HTTP: HEAD must be supported wherever GET is. Add `'HEAD'` to allowed methods lists in all x402 handlers.++### 17. `GET /api/x402/mint-to-mesh-batch` — 405 × 127+- **Error:** 405 for GET on a POST-only endpoint+- **Root cause:** `mint-to-mesh-batch.js` only allows POST but bots/probers are hitting it with GET.+- **Fix:** The `method()` helper should return a proper `405 Method Not Allowed` with an `Allow: POST` header. Check that the current implementation does this (don't just return 405 with no body — include `Allow` header per RFC 7231).++### 18. `GET /api/webhooks/replicate` — 405 × 4+- **Error:** 405 for GET on webhook endpoint+- **Root cause:** Webhooks only accept POST; GET needs to return 405 with `Allow: POST`.+- **Fix:** Same as above — confirm `api/webhooks/replicate.js` returns proper 405 with `Allow` header for non-POST methods.++### 19. `/api/x402/permit2-paid-demo` — accepts PUT/PATCH/DELETE — 10× 405+- **Error:** Multiple 405s on methods that should not be accepted+- **Fix:** Tighten `method()` guard to only allow the intended methods (GET or POST). Return `405 { Allow: 'GET, POST' }` for everything else.++---++## MEDIUM — Cron / Background Job Failures++### 20. `index-delegations` ETH mainnet getLogs range error — 7× per run+- **Error:** `RPC eth_getLogs error: eth_getLogs is limited to 0 - 50 blocks range`+- **Root cause:** The indexer builds block ranges larger than 50 for mainnet (chainId=1).+- **Fix:** In `api/cron/[name].js` delegation indexer, enforce `const BATCH = chainId === 1 ? 25 : 150;` (mainnet is the bottleneck; other RPCs allow larger). Already partially noted under issue #5 — this is the specific constraint.++### 21. `index-delegations` fetch failures — 54 occurrences+- **Error:** `{"stage":"index-delegations","chainId":1,"error":"fetch failed"}` and `{"error":"This operation was aborted"}`+- **Root cause:** Vercel function hitting 30s timeout mid-HTTP fetch to RPC endpoint; or network blip.+- **Fix:** Add `AbortController` with 10s timeout on each RPC fetch inside the indexer. Catch `AbortError` and `fetch failed` separately; on timeout, save cursor and return 200 (partial success) instead of letting the whole function timeout at 30s.++### 22. `api/club/tips-stream` timing out — 5× at 300s+- **Error:** `Vercel Runtime Timeout Error: Task timed out after 300 seconds` from SSE stream endpoint+- **Root cause:** SSE streams are holding connections open past Vercel's 300s Pro function limit.+- **Fix:** Implement keep-alive heartbeat that sends a `: ping` comment every 25s. When approaching 280s (`Date.now() - start > 280000`), send a `retry: 1000` SSE directive and close the connection cleanly so the client auto-reconnects. This prevents the hard timeout while maintaining the streaming UX.++---++## LOW — Cleanup & Configuration++### 23. `api/auth/[action].js` seed-default-agent DB connection flaps — 6 failures+- **Error:** `[seed-default-agent] failed ... error: 'Error connecting to database: fetch failed'`+- **Root cause:** Transient Neon connection failures during auth flow. Currently the error is caught and logged but auth continues — verify the handler doesn't block sign-in on seed failure.+- **Fix:** Confirm that `seed-default-agent` failures are fire-and-forget (non-blocking). If auth returns 200 even when seeding fails, this is acceptable. Add retry with 1s delay (one retry only) before giving up.++### 24. Fake/test agent UUID in production — `11111111-2222-3333-4444-555555555555` 404 × 5+- **Error:** 404 for `/api/agents/11111111-2222-3333-4444-555555555555`+- **Root cause:** Test/placeholder UUID being requested in production — likely hardcoded in a client or demo page.+- **Fix:** Search frontend/demo code for `11111111-2222-3333-4444-555555555555` and replace with a real agent UUID or make the endpoint handle gracefully.++### 25. `api/marketplace/theme)` — 404 with trailing `)` in URL × 1+- **Error:** 404 for `/api/marketplace/theme)` — a `)` character leaked into the URL+- **Root cause:** Client-side bug — a URL is being constructed with an unclosed parenthesis (e.g., `\`/api/marketplace/${action)\`...`).+- **Fix:** Search marketplace-related frontend code for the malformed URL construction and fix the string concatenation/template.++---++## Schema Migration Required++The following SQL must be added to `api/_lib/schema.sql` and applied to the production Neon database:++```sql+-- agent_reviews (for marketplace ratings)+CREATE TABLE IF NOT EXISTS agent_reviews (+ id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ rating int NOT NULL CHECK (rating BETWEEN 1 AND 5),+ review text,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (agent_id, user_id)+);+CREATE INDEX IF NOT EXISTS agent_reviews_agent_id ON agent_reviews(agent_id);+CREATE INDEX IF NOT EXISTS agent_reviews_user_id ON agent_reviews(user_id);++-- x_triggers (social automation triggers)+CREATE TABLE IF NOT EXISTS x_triggers (+ id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ agent_id uuid REFERENCES agent_identities(id) ON DELETE SET NULL,+ kind text NOT NULL,+ config jsonb NOT NULL DEFAULT '{}',+ auto_publish boolean NOT NULL DEFAULT false,+ enabled boolean NOT NULL DEFAULT true,+ last_fired_at timestamptz,+ last_state jsonb,+ created_at timestamptz NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS x_triggers_user_id ON x_triggers(user_id) WHERE enabled;++-- x_scheduled_posts (queued social posts)+CREATE TABLE IF NOT EXISTS x_scheduled_posts (+ id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ agent_id uuid REFERENCES agent_identities(id) ON DELETE SET NULL,+ text text NOT NULL,+ scheduled_at timestamptz NOT NULL,+ published_at timestamptz,+ created_at timestamptz NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS x_scheduled_posts_pending ON x_scheduled_posts(scheduled_at) WHERE published_at IS NULL;++-- x_pending_reviews (posts waiting for human approval before publish)+CREATE TABLE IF NOT EXISTS x_pending_reviews (+ id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ trigger_id uuid REFERENCES x_triggers(id) ON DELETE SET NULL,+ agent_id uuid REFERENCES agent_identities(id) ON DELETE SET NULL,+ text text NOT NULL,+ reviewed_at timestamptz,+ approved boolean,+ created_at timestamptz NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS x_pending_reviews_user_pending ON x_pending_reviews(user_id) WHERE reviewed_at IS NULL;++-- club_tips — add amount_atomics if table predates the column+ALTER TABLE club_tips ADD COLUMN IF NOT EXISTS amount_atomics numeric;+```++---++## Summary by Priority++| # | Issue | Errors | Status |+|---|-------|--------|--------|+| 1 | Missing `agent_reviews` table | 52× 500 | Schema + deploy |+| 2 | Missing `x_triggers`/`x_scheduled_posts`/`x_pending_reviews` | 72× errors | Schema + deploy |+| 3 | `club_tips.amount_atomics` column missing | 7× 500 | ALTER TABLE |+| 4 | Solana RPC 429 rate limiting | 900+ errors | Cache + fallback RPC |+| 5 | Cron 30s timeout | 393× 504 | Batch size + time budget |+| 6 | OpenRouter free model rate-limited | 7× 502 | Model fallback chain |+| 7 | `X402_AGENT_SOLANA_SECRET_BASE58` not set | 1× 503 | Error handler |+| 8 | `ZAUTH_API_KEY` not set causing 500s | 1954× | Fix or set env var |+| 9 | Bonfida ESM bundling crash | 2× 500 | Pin/externalize dep |+| 10 | UUID validation in permissions | 1× 500 | Input validation |+| 11 | widget_views FK violation | 1× | Swallow FK errors |+| 12 | `mocap/clips` `$1` syntax error persists | 2× 500 | Re-audit + redeploy |+| 13 | `/api/agents/[id]/solana` 404 | 500× 404 | Route handler |+| 14 | `/api/agent-strategy` missing | 2× 404 | Create handler |+| 15 | Template literal in URL | 2× 404 | Frontend string fix |+| 16 | x402 HEAD requests → 405 | 100× 405 | Add HEAD support |+| 17-19 | Various 405 missing Allow header | 150+ | Method guards |+| 20 | getLogs range >50 blocks | 7× | Reduce batch size |+| 21 | Index fetch timeouts | 54× | AbortController |+| 22 | tips-stream 300s timeout | 5× | SSE keep-alive + reconnect |+| 23 | seed-default-agent flaps | 6× | Verify non-blocking |+| 24 | Test UUID in production | 5× | Remove hardcoded UUID |+| 25 | Malformed marketplace URL | 1× | Fix template literal |diff --git a/api/_lib/env.js b/api/_lib/env.jsindex c9950654d..e3ba161fb 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -143,8 +143,8 @@ export const env = {},// IPFS pinning provider credentials. Optional — when unset, pin endpoints- // fall back to a content-hash stub so the rest of the flow still works in- // dev. Set PINATA_JWT in production for real pins.+ // fall back to R2 storage and return a public HTTPS metadataURI.+ // Set PINATA_JWT in production for real IPFS CIDs on-chain.get PINATA_JWT() {return opt('PINATA_JWT');},@@ -535,6 +535,13 @@ export const env = {return opt('CHROMIUM_PACK_URL');},+ // CZ Agent campaign — on-chain registry contract for the transfer flow.+ // Set CZ_REGISTRY_CONTRACT to the deployed identity registry address.+ // CZ_AGENT_ID and CZ_AGENT_NAME can override the defaults.+ get CZ_REGISTRY_CONTRACT() { return opt('CZ_REGISTRY_CONTRACT', '0x0000000000000000000000000000000000000000'); },+ get CZ_AGENT_ID() { return opt('CZ_AGENT_ID', 'cz-preview'); },+ get CZ_AGENT_NAME() { return opt('CZ_AGENT_NAME', 'CZ Agent'); },+getRpcUrl(chainId) {return (opt(`RPC_URL_${chainId}`) ||diff --git a/api/_lib/evm-transfer.js b/api/_lib/evm-transfer.jsnew file mode 100644index 000000000..0401c8517--- /dev/null+++ b/api/_lib/evm-transfer.js@@ -0,0 +1,137 @@+/**+ * EVM USDC transfer helper — used by payout/withdrawal flows that need to+ * send USDC from a treasury wallet to a recipient on an EVM chain.+ *+ * Mirrors the club-payouts.js sender but supports multiple chains and uses+ * the generic EVM_TREASURY_PRIVATE_KEY env var. Per-chain RPC URLs are+ * resolved from env: EVM_RPC_URL_<chainId> falls back to a viem-default+ * public RPC if not configured.+ */++import {+ createPublicClient,+ createWalletClient,+ http,+ encodeFunctionData,+ parseAbi,+} from 'viem';+import { privateKeyToAccount } from 'viem/accounts';+import {+ mainnet,+ base,+ optimism,+ arbitrum,+ polygon,+ sepolia,+ baseSepolia,+} from 'viem/chains';+import { env } from './env.js';+import { EVM_USDC } from '../payments/_config.js';++const ERC20_TRANSFER_ABI = parseAbi([+ 'function transfer(address to, uint256 amount) returns (bool)',+]);++const CHAINS = {+ 1: mainnet,+ 8453: base,+ 10: optimism,+ 42161: arbitrum,+ 137: polygon,+ 11155111: sepolia,+ 84532: baseSepolia,+};++const SEND_TIMEOUT_MS = 90_000;+const CONFIRMATIONS = 1;++/**+ * Send `amount` USDC atomics from the configured EVM treasury to `recipient`+ * on the given chain. Waits for inclusion before returning so the caller can+ * confidently advance ledger state.+ *+ * @param {object} opts+ * @param {number} opts.chainId+ * @param {string} opts.recipient 0x-prefixed EVM address+ * @param {bigint|string} opts.amount USDC atomics (6 decimals)+ * @returns {Promise<{ hash: string, chainId: number, amount: string }>}+ */+export async function sendEvmUsdc({ chainId, recipient, amount }) {+ const chain = CHAINS[chainId];+ if (!chain) throw new Error(`unsupported EVM chain ${chainId}`);++ const usdc = EVM_USDC[chainId];+ if (!usdc) throw new Error(`no USDC contract for chain ${chainId}`);++ if (!/^0x[0-9a-fA-F]{40}$/.test(recipient)) {+ throw new Error(`invalid EVM recipient: ${recipient}`);+ }++ const amt = typeof amount === 'bigint' ? amount : BigInt(amount);+ if (amt <= 0n) throw new Error('amount must be > 0');++ const pk = env.EVM_TREASURY_PRIVATE_KEY || process.env.EVM_TREASURY_PRIVATE_KEY;+ if (!pk) throw new Error('EVM_TREASURY_PRIVATE_KEY not set');++ const account = privateKeyToAccount(pk.startsWith('0x') ? pk : `0x${pk}`);++ const rpcUrl =+ process.env[`EVM_RPC_URL_${chainId}`] ||+ (chainId === 8453 && env.CLUB_BASE_RPC_URL) ||+ undefined;+ const transport = http(rpcUrl);+ const publicClient = createPublicClient({ chain, transport });+ const walletClient = createWalletClient({ account, chain, transport });++ const data = encodeFunctionData({+ abi: ERC20_TRANSFER_ABI,+ functionName: 'transfer',+ args: [recipient, amt],+ });++ const hash = await walletClient.sendTransaction({+ to: usdc,+ data,+ value: 0n,+ });++ const receipt = await publicClient.waitForTransactionReceipt({+ hash,+ timeout: SEND_TIMEOUT_MS,+ confirmations: CONFIRMATIONS,+ });+ if (receipt.status !== 'success') {+ throw new Error(`evm_tx_reverted: ${hash}`);+ }++ return { hash, chainId, amount: amt.toString() };+}++/**+ * Chain-id lookup so `agent_withdrawals.chain` text values map to integers.+ * Supports both the canonical chain names and numeric strings.+ */+export function resolveEvmChainId(chain) {+ if (chain == null) return null;+ const lower = String(chain).toLowerCase();+ const named = {+ ethereum: 1,+ eth: 1,+ mainnet: 1,+ base: 8453,+ optimism: 10,+ op: 10,+ arbitrum: 42161,+ arb: 42161,+ polygon: 137,+ matic: 137,+ sepolia: 11155111,+ 'base-sepolia': 84532,+ };+ if (named[lower]) return named[lower];+ const n = Number(lower);+ if (Number.isInteger(n) && CHAINS[n]) return n;+ return null;+}++export { CHAINS as EVM_CHAINS };diff --git a/api/_lib/migrations/2026-05-25-bsc-consumed-tx.sql b/api/_lib/migrations/2026-05-25-bsc-consumed-tx.sqlnew file mode 100644index 000000000..9f1572b4d--- /dev/null+++ b/api/_lib/migrations/2026-05-25-bsc-consumed-tx.sql@@ -0,0 +1,20 @@+-- Migration: anti-replay set for x402 direct payments on BSC.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-05-25-bsc-consumed-tx.sql+-- Idempotent.+--+-- Each successfully verified BSC payment tx is recorded so a replay across+-- Vercel cold starts or function replicas can't unlock the same resource+-- twice. The on-chain Payment(payer, amount, ref) event is uniquely keyed by+-- tx_hash; the table's PRIMARY KEY enforces single-consumption.++CREATE TABLE IF NOT EXISTS bsc_consumed_tx (+ tx_hash text PRIMARY KEY,+ ref text,+ payer text,+ amount numeric,+ pay_to text,+ consumed_at timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS bsc_consumed_tx_consumed_at+ ON bsc_consumed_tx (consumed_at);diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 55a444fc9..e82e205d8 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -1442,3 +1442,24 @@ CREATE INDEX IF NOT EXISTS x402_receipts_payer_issuedON x402_receipts (payer, issued_at desc);CREATE INDEX IF NOT EXISTS x402_receipts_resource_issuedON x402_receipts (resource_url, issued_at desc);++-- ── bsc_consumed_tx — anti-replay set for x402 direct payments on BSC ───────+-- Mirror of api/_lib/migrations/2026-05-25-bsc-consumed-tx.sql. Each+-- successfully verified BSC payment tx is recorded here so a replay across+-- Vercel cold starts or function replicas can't unlock the same resource+-- twice. The on-chain Payment(payer, amount, ref) event is uniquely keyed by+-- tx_hash; the table's PRIMARY KEY enforces single-consumption.+CREATE TABLE IF NOT EXISTS bsc_consumed_tx (+ tx_hash text PRIMARY KEY,+ ref text,+ payer text,+ amount numeric,+ pay_to text,+ consumed_at timestamptz NOT NULL DEFAULT now()+);++-- Garbage-collect old rows. The Payment event is public on-chain so eventual+-- cleanup of records older than 30 days is safe; auditing can re-derive from+-- BSC archive nodes if needed.+CREATE INDEX IF NOT EXISTS bsc_consumed_tx_consumed_at+ ON bsc_consumed_tx (consumed_at);diff --git a/api/_lib/x402-bsc-direct.js b/api/_lib/x402-bsc-direct.jsindex 057c927bb..e7cad3d51 100644--- a/api/_lib/x402-bsc-direct.js+++ b/api/_lib/x402-bsc-direct.js@@ -33,6 +33,7 @@ import { bsc } from 'viem/chains';import { env } from './env.js';import { X402Error } from './x402-errors.js';+import { sql } from './db.js';export const PAYMENT_EVENT = parseAbiItem('event Payment(address indexed payer, uint256 amount, bytes32 indexed ref)',@@ -43,25 +44,46 @@ export const PAYMENT_EVENT = parseAbiItem(export const PAYMENT_EVENT_TOPIC ='0xd17e8b542e550255f0bc5a7b2230f59fdc24847d2003255bf6199ab46ad8f300';-// In-process anti-replay set keyed by txHash. Vercel cold starts forget, so a-// rapidly-replayed payload could briefly slip through across function instances.-// The pay() event is public on BSC, so any abuse is auditable on-chain; for the-// launch demo (where per-call cost is $0.001) this trade-off is acceptable.-// Production hardening: persist to Postgres in a (tx_hash PRIMARY KEY) table.-const seenTx = new Map();+// Anti-replay: Postgres-backed `bsc_consumed_tx` table is the source of truth+// (PRIMARY KEY on tx_hash enforces single-consumption across Vercel replicas+// and cold starts). A short-lived in-process Map fronts it to avoid a DB round+// trip on the verify hot path when the same instance just consumed the tx.const SEEN_TTL_MS = 10 * 60 * 1000;+const seenTx = new Map();function pruneSeen() {const now = Date.now();for (const [k, exp] of seenTx) if (exp < now) seenTx.delete(k);}-function rememberTx(key) {++async function isReplay(txHash) {pruneSeen();- seenTx.set(key, Date.now() + SEEN_TTL_MS);+ if (seenTx.has(txHash)) return true;+ const rows = await sql`+ SELECT 1 FROM bsc_consumed_tx WHERE tx_hash = ${txHash} LIMIT 1+ `;+ return rows.length > 0;}-function isReplay(key) {++async function rememberTx({ txHash, ref, payer, amount, payTo }) {pruneSeen();- return seenTx.has(key);+ seenTx.set(txHash, Date.now() + SEEN_TTL_MS);+ // INSERT … ON CONFLICT DO NOTHING — concurrent verifiers of the same tx+ // resolve to one consumer; the second caller will see the row on read.+ try {+ await sql`+ INSERT INTO bsc_consumed_tx (tx_hash, ref, payer, amount, pay_to)+ VALUES (${txHash}, ${ref}, ${payer}, ${amount?.toString() ?? null}, ${payTo})+ ON CONFLICT (tx_hash) DO NOTHING+ `;+ } catch (err) {+ // DB persist failure is observable but must not roll back the verify —+ // the on-chain settlement happened, the buyer paid. Surface for ops.+ console.error('[x402-bsc-direct] persist consumed_tx failed', {+ tx_hash: txHash,+ error: err?.message,+ });+ }}let cachedClient = null;@@ -87,7 +109,7 @@ export async function verifyDirectPayment({ paymentPayload, requirement }) {const ref = requireHex32(paymentPayload?.ref, 'ref');const txHash = requireHex32(paymentPayload?.txHash, 'txHash');- if (isReplay(txHash)) {+ if (await isReplay(txHash)) {throw new X402Error('invalid_payment',`tx ${txHash} has already been consumed by an earlier paid request`,@@ -164,7 +186,13 @@ export async function verifyDirectPayment({ paymentPayload, requirement }) {);}- rememberTx(txHash);+ await rememberTx({+ txHash,+ ref,+ payer,+ amount,+ payTo: expectedTo,+ });return { isValid: true, payer, txHash, amount: amount.toString() };}diff --git a/api/_lib/x402-spending-ledger.js b/api/_lib/x402-spending-ledger.jsindex 6a8968490..622434cf7 100644--- a/api/_lib/x402-spending-ledger.js+++ b/api/_lib/x402-spending-ledger.js@@ -15,8 +15,9 @@// x402:spend:hr:<address>:<UTC_HOUR> → integer microUSD (TTL 7200s)// x402:spend:day:<address>:<UTC_DAY> → integer microUSD (TTL 172800s)// Falls back to an in-process Map when UPSTASH_REDIS_REST_* is unset so-// local dev / tests work, with the documented caveat that caps are then-// per-instance and not enforced across Vercel function replicas.+// local dev / tests work. In production the fallback only fires when+// X402_ALLOW_MEMORY_FALLBACK=1; otherwise getRedis() refuses to return so+// the cap module fails closed rather than silently per-instance.import { Redis } from '@upstash/redis';import { env } from './env.js';@@ -24,11 +25,27 @@ import { env } from './env.js';const KEY_PREFIX = 'x402:spend:';const HOUR_TTL_SECONDS = 7200; // keep one extra hour for slow-cron debuggingconst DAY_TTL_SECONDS = 60 * 60 * 48;+const IS_PROD = process.env.VERCEL_ENV === 'production' || process.env.NODE_ENV === 'production';+const ALLOW_MEMORY_FALLBACK = process.env.X402_ALLOW_MEMORY_FALLBACK === '1';let redisClient = null;+let memoryWarned = false;function getRedis() {if (redisClient !== null) return redisClient;if (!env.UPSTASH_REDIS_REST_URL || !env.UPSTASH_REDIS_REST_TOKEN) {+ if (IS_PROD && !ALLOW_MEMORY_FALLBACK) {+ throw new Error(+ '[x402-spending-ledger] UPSTASH_REDIS_REST_URL/TOKEN required in production. ' ++ 'Set them, or set X402_ALLOW_MEMORY_FALLBACK=1 to accept per-instance spend caps.',+ );+ }+ if (IS_PROD && !memoryWarned) {+ memoryWarned = true;+ console.warn(+ '[x402-spending-ledger] Running in production with memory fallback; ' ++ 'spend caps are per-instance only.',+ );+ }redisClient = false; // sentinel: configured-as-absentreturn null;}diff --git a/api/_lib/x402/idempotency-cache.js b/api/_lib/x402/idempotency-cache.jsindex 439e4b44a..314415a4d 100644--- a/api/_lib/x402/idempotency-cache.js+++ b/api/_lib/x402/idempotency-cache.js@@ -6,20 +6,34 @@// what the spec calls for: same id + different payload → 409 Conflict.//// The store falls back to an in-process Map when Upstash isn't configured, so-// `npm test` and local dev work without Redis. Production deployments must set-// UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN — without them, idempotency-// is per-instance and provides no protection across Vercel function replicas.+// `npm test` and local dev work without Redis. In production the fallback+// only fires when X402_ALLOW_MEMORY_FALLBACK=1 is set — otherwise the module+// boot-checks and refuses to load without Upstash, preventing accidental+// silent degradation across Vercel function replicas.import { createHash } from 'node:crypto';import { Redis } from '@upstash/redis';import { env } from '../env.js';+const IS_PROD = process.env.VERCEL_ENV === 'production' || process.env.NODE_ENV === 'production';+const ALLOW_MEMORY_FALLBACK = process.env.X402_ALLOW_MEMORY_FALLBACK === '1';+let redis = null;if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {redis = new Redis({url: env.UPSTASH_REDIS_REST_URL,token: env.UPSTASH_REDIS_REST_TOKEN,});+} else if (IS_PROD && !ALLOW_MEMORY_FALLBACK) {+ throw new Error(+ '[x402-idempotency] UPSTASH_REDIS_REST_URL/TOKEN required in production. ' ++ 'Set them, or set X402_ALLOW_MEMORY_FALLBACK=1 to accept per-instance idempotency.',+ );+} else if (IS_PROD) {+ console.warn(+ '[x402-idempotency] Running in production with X402_ALLOW_MEMORY_FALLBACK=1; ' ++ 'duplicate-payment protection is per-instance only.',+ );}const KEY_PREFIX = 'x402:idem:';diff --git a/api/agents/register/[action].js b/api/agents/register/[action].jsindex 9c4c7524a..bede6326c 100644--- a/api/agents/register/[action].js+++ b/api/agents/register/[action].js@@ -8,12 +8,11 @@ import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';import { parse } from '../../_lib/validate.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';-import { r2 } from '../../_lib/r2.js';+import { r2, publicUrl } from '../../_lib/r2.js';import { SERVER_CHAIN_META } from '../../_lib/onchain.js';import { PutObjectCommand } from '@aws-sdk/client-s3';import { AbiCoder, getAddress, keccak256, toUtf8Bytes } from 'ethers';import { z } from 'zod';-import { createHash } from 'crypto';// ── prep ──────────────────────────────────────────────────────────────────────@@ -27,24 +26,62 @@ const prepSchema = z.object({demoSlug: z.string().optional(),});+// Store registration JSON to R2 and return a public HTTPS URL.+// Always succeeds — R2 is the source of truth even when IPFS is available.+async function storeToR2(jsonBytes) {+ const key = `agent-registrations/${Date.now()}-${Math.random().toString(36).slice(2)}.json`;+ await r2.send(new PutObjectCommand({ Bucket: env.S3_BUCKET, Key: key, Body: jsonBytes, ContentType: 'application/json' }));+ return { key, httpsUrl: publicUrl(key) };+}+async function pinRegistrationJson(jsonObj) {const jsonStr = JSON.stringify(jsonObj);const jsonBytes = Buffer.from(jsonStr, 'utf-8');- const token = process.env.WEB3_STORAGE_TOKEN;- if (token) {++ // 1. Try web3.storage (legacy, still supported).+ const web3Token = process.env.WEB3_STORAGE_TOKEN;+ if (web3Token) {try {- const res = await fetch('https://api.web3.storage/upload', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: jsonBytes });+ const res = await fetch('https://api.web3.storage/upload', {+ method: 'POST',+ headers: { Authorization: `Bearer ${web3Token}` },+ body: jsonBytes,+ });if (res.ok) {const r = await res.json();- if (r.cid) return { cid: r.cid, metadataURI: `ipfs://${r.cid}` };+ if (r.cid) {+ await storeToR2(jsonBytes);+ return { cid: r.cid, metadataURI: `ipfs://${r.cid}` };+ }}} catch {}}- const contentHash = createHash('sha256').update(jsonStr).digest('hex');- const stubCid = `bafkreigenerated${contentHash.slice(0, 40)}`;- const key = `agent-registrations/${Date.now()}-${Math.random().toString(36).slice(2)}.json`;- await r2.send(new PutObjectCommand({ Bucket: env.S3_BUCKET, Key: key, Body: jsonBytes, ContentType: 'application/json' }));- return { cid: stubCid, metadataURI: `ipfs://${stubCid}` };++ // 2. Try Pinata if configured.+ const pinataJwt = env.PINATA_JWT;+ if (pinataJwt) {+ try {+ const form = new FormData();+ form.append('file', new Blob([jsonBytes], { type: 'application/json' }), 'agent-manifest.json');+ const res = await fetch('https://api.pinata.cloud/pinning/pinFileToIPFS', {+ method: 'POST',+ headers: { Authorization: `Bearer ${pinataJwt}` },+ body: form,+ });+ if (res.ok) {+ const r = await res.json();+ if (r.IpfsHash) {+ await storeToR2(jsonBytes);+ return { cid: r.IpfsHash, metadataURI: `ipfs://${r.IpfsHash}` };+ }+ }+ } catch {}+ }++ // 3. No IPFS provider — store in R2 and return a real HTTPS URL.+ // On-chain consumers can resolve it; the metadata is fully public.+ const { httpsUrl } = await storeToR2(jsonBytes);+ return { cid: null, metadataURI: httpsUrl };}async function handlePrep(req, res) {diff --git a/api/avatars/_actions.js b/api/avatars/_actions.jsindex 0693d3681..b73e9c8e0 100644--- a/api/avatars/_actions.js+++ b/api/avatars/_actions.js@@ -12,6 +12,7 @@ import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';import { parse, presignUploadBody, slug as slugSchema, createAvatarBody } from '../_lib/validate.js';import { recordEvent } from '../_lib/usage.js';import { limits, clientIp } from '../_lib/rate-limit.js';+import { requireCsrf } from '../_lib/csrf.js';import { z } from 'zod';import { randomUUID } from 'crypto';import { isValidGlbHeader, inspectGlb } from '../_lib/glb-inspect.js';@@ -122,6 +123,7 @@ const handleUpload = wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const userId = await resolvePresignUser(req, 'avatars:write');if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');+ if (!(await requireCsrf(req, res, userId))) return;const rl = await limits.upload(userId);if (!rl.success) return error(res, 429, 'rate_limited', 'upload rate exceeded');diff --git a/api/cron/[name].js b/api/cron/[name].jsindex e32f9b6bf..a4fadce97 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -2272,7 +2272,14 @@ async function handleProcessSubscriptions(req, res) {}const runId = `psub-${Date.now()}`;- const report = { runId, processed: 0, charged: 0, pastDue: 0, errors: [] };+ const report = {+ runId,+ processed: 0,+ charged: 0, // succeeded outright (instantaneous settlement)+ pendingApproval: 0, // payment intent created; subscriber must approve+ pastDue: 0,+ errors: [],+ };// Find subscriptions whose period ends within the next hour (charge a bit// early to allow for retry windows before period actually expires).@@ -2332,13 +2339,33 @@ async function handleProcessSubscriptions(req, res) {}const result = await chargeSubscription(row.id);- if (result.pending) {- report.charged++; // pending = payment request created- } else if (!result.success) {- await failPayment(result.paymentId, row.id);- report.errors.push({ id: row.id, error: result.error || 'charge_failed' });- } else {+ if (result.success) {report.charged++;+ } else if (result.pending) {+ // A payment intent was created and the subscriber was notified+ // in-app. Do not increment `charged` — the subscription has+ // NOT been paid yet. A follow-up email reminder is best-effort+ // and only fires when subscriber_email is present.+ report.pendingApproval++;+ if (row.subscriber_email && result.payUrl) {+ sendEmail({+ to: row.subscriber_email,+ subject: 'Your subscription renewal is due',+ html: `<p>Hi ${row.subscriber_name || 'there'},</p>+<p>Your subscription is up for renewal. The amount is $${result.amount_usd?.toFixed(2) || row.price_usd}.</p>+<p><a href="${result.payUrl}">Approve renewal payment</a></p>`,+ text: `Your subscription renewal of $${result.amount_usd?.toFixed(2) || row.price_usd} is ready. Approve at ${result.payUrl}`,+ }).catch((e) => console.error(JSON.stringify({+ event: 'process_subscriptions.email_failed',+ subscriptionId: row.id,+ error: e.message,+ })));+ }+ } else {+ if (result.paymentId) {+ await failPayment(result.paymentId, row.id);+ }+ report.errors.push({ id: row.id, error: result.error || 'charge_failed' });}} catch (e) {report.errors.push({ id: row.id, error: e.message || String(e) });@@ -2473,14 +2500,27 @@ async function handleProcessWithdrawals(req, res) {}const treasuryKeypair = process.env.TREASURY_KEYPAIR;- if (!treasuryKeypair) {- return json(res, 200, { skipped: true, reason: 'TREASURY_KEYPAIR not configured' });+ const evmTreasuryKey = process.env.EVM_TREASURY_PRIVATE_KEY;+ if (!treasuryKeypair && !evmTreasuryKey) {+ return json(res, 200, {+ skipped: true,+ reason: 'No treasury key configured (set TREASURY_KEYPAIR for Solana, EVM_TREASURY_PRIVATE_KEY for EVM)',+ });}const { transferSolanaUSDC } = await import('../_lib/solana-transfer.js');+ const { sendEvmUsdc, resolveEvmChainId } = await import('../_lib/evm-transfer.js');const { insertNotification } = await import('../_lib/notify.js');- // Fetch pending Solana withdrawals, join user earnings to verify available balance+ // 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+ // once an operator wires the key.+ const supportedChains = [];+ if (treasuryKeypair) supportedChains.push('solana');+ if (evmTreasuryKey) supportedChains.push('ethereum', 'base', 'optimism', 'arbitrum', 'polygon', 'sepolia', 'base-sepolia', '1', '8453', '10', '42161', '137', '11155111', '84532');++ // Fetch pending withdrawals across all supported chains, join user earnings+ // to verify available balance.const pending = await sql`SELECTw.id,@@ -2504,7 +2544,7 @@ async function handleProcessWithdrawals(req, res) {AND w2.currency_mint = w.currency_mint) AS availableFROM agent_withdrawals w- WHERE w.status = 'pending' AND w.chain = 'solana'+ WHERE w.status = 'pending' AND w.chain = ANY(${supportedChains})ORDER BY w.created_at ASCLIMIT ${WITHDRAWALS_BATCH}`;@@ -2548,12 +2588,31 @@ async function handleProcessWithdrawals(req, res) {}try {- const sig = await transferSolanaUSDC({- fromWallet: treasuryKeypair,- toAddress: w.to_address,- amount: BigInt(w.amount),- mint: w.currency_mint,- });+ let sig;+ if (w.chain === 'solana') {+ if (!treasuryKeypair) {+ throw new Error('TREASURY_KEYPAIR not configured for solana withdrawal');+ }+ sig = await transferSolanaUSDC({+ fromWallet: treasuryKeypair,+ toAddress: w.to_address,+ amount: BigInt(w.amount),+ mint: w.currency_mint,+ });+ } else {+ // EVM dispatch — resolve the chain name/id to a viem chain ID,+ // then send the real USDC transfer.+ const chainId = resolveEvmChainId(w.chain);+ if (!chainId) {+ throw new Error(`unsupported chain for withdrawal: ${w.chain}`);+ }+ const result = await sendEvmUsdc({+ chainId,+ recipient: w.to_address,+ amount: BigInt(w.amount),+ });+ sig = result.hash;+ }await sql`UPDATE agent_withdrawals@@ -2572,6 +2631,7 @@ async function handleProcessWithdrawals(req, res) {withdrawal_id: w.id,amount: w.amount,currency_mint: w.currency_mint,+ chain: w.chain,tx_signature: sig,});diff --git a/api/cz/claim.js b/api/cz/claim.jsindex be4e7fd4e..9564a52ae 100644--- a/api/cz/claim.js+++ b/api/cz/claim.js@@ -16,15 +16,14 @@ import { verifyMessage, Interface } from 'ethers';import { sql } from '../_lib/db.js';import { cors, json, error, wrap, readJson } from '../_lib/http.js';import { clientIp } from '../_lib/rate-limit.js';+import { env } from '../_lib/env.js';-// Pre-registered agent details — update these once the agent is registered on-chain.-const CZ_AGENT_ID = 'cz-preview';-const CZ_AGENT_NAME = 'CZ Agent';-// On-chain registry address (placeholder — update to real address before mainnet).-const REGISTRY_CONTRACT = '0x0000000000000000000000000000000000000000';+const CZ_AGENT_ID = env.CZ_AGENT_ID || 'cz-preview';+const CZ_AGENT_NAME = env.CZ_AGENT_NAME || 'CZ Agent';+// Reads from env so the contract can be deployed without a code redeploy.+// Frontend skips the on-chain tx when the address is empty/zero.+const REGISTRY_CONTRACT = env.CZ_REGISTRY_CONTRACT || '0x0000000000000000000000000000000000000000';-// ABI fragment for the ownership transfer call.-// Replace the function signature when the final contract ABI is known.const _iface = new Interface(['function transferAgent(string agentId, address newOwner)']);function encodeTransferAgent(agentId, newOwner) {return _iface.encodeFunctionData('transferAgent', [agentId, newOwner]);diff --git a/api/oauth/[action].js b/api/oauth/[action].jsindex 76b7ec73e..d19f9758a 100644--- a/api/oauth/[action].js+++ b/api/oauth/[action].js@@ -1,6 +1,6 @@// Consolidated OAuth 2.1 endpoints dispatcher.-// Routes: /oauth/authorize, /oauth/token, /oauth/register,-// /oauth/revoke, /oauth/introspect+// Routes: /oauth/authorize, /oauth/consent (post-login redirect alias for authorize),+// /oauth/token, /oauth/register, /oauth/revoke, /oauth/introspectimport { sql } from '../_lib/db.js';import {@@ -257,6 +257,7 @@ async function handleIntrospect(req, res) {const DISPATCH = {authorize: handleAuthorize,+ consent: handleAuthorize,token: handleToken,register: handleRegister,revoke: handleRevoke,diff --git a/public/footer.html b/public/footer.htmlindex e37325767..bf3dc8a4b 100644--- a/public/footer.html+++ b/public/footer.html@@ -81,13 +81,39 @@<a href="/community">Community</a><a href="/tutorials">Tutorials</a></div>+ <div class="h-footer-link-col">+ <h4 class="h-footer-link-heading">$THREE</h4>+ <a href="https://solscan.io/token/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" target="_blank" rel="noopener">Solscan</a>+ <a href="https://jup.ag/tokens/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" target="_blank" rel="noopener">Buy on Jupiter</a>+ <a href="https://www.coingecko.com/en/coins/three-ws" target="_blank" rel="noopener">CoinGecko</a>+ <a href="/rider">Rider VR Gate</a>+ </div></nav></div><div class="h-footer-bottom"><p class="h-footer-legal">© 2026 three.ws — All rights reserved.</p>+ <div class="h-footer-ca-wrap">+ <span class="h-footer-ca-label">$THREE</span>+ <button class="h-footer-ca-btn" id="footer-ca-copy" data-ca="FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" title="Copy contract address">+ FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump+ </button>+ </div><div class="h-footer-legal-links"><a href="/legal/privacy">Privacy Policy</a><a href="/legal/tos">Terms of Use</a></div></div>+ <script>+ (function () {+ var btn = document.getElementById('footer-ca-copy');+ if (!btn) return;+ btn.addEventListener('click', function () {+ navigator.clipboard.writeText(btn.dataset.ca).then(function () {+ var orig = btn.textContent;+ btn.textContent = 'Copied!';+ setTimeout(function () { btn.textContent = orig; }, 1500);+ });+ });+ })();+ </script></footer>diff --git a/src/marketplace.js b/src/marketplace.jsindex 1037cb0f0..eca1728ca 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -2837,7 +2837,7 @@ async function loadDetail(id) {renderVersions(versions);const similar = similarRes?.data?.items || similarRes?.data?.similar || [];renderSimilar(similar);- });+ }).catch(() => { /* best-effort — main detail already rendered */ });} catch (err) {console.error('[marketplace] detail load', err);if (!cached) renderDetailError('Failed to load agent.');@@ -3412,22 +3412,22 @@ function bindEvents() {else if (state.featured.length) startHeroAutoplay();});- document.body.addEventListener('click', async (e) => {+ document.body.addEventListener('click', (e) => {if (e.target.matches('.purchase-btn')) {const skillName = e.target.dataset.skillName;const agentId = e.target.dataset.agentId;- if (agentId && skillName) await openPurchaseFlow(agentId, skillName);+ if (agentId && skillName) openPurchaseFlow(agentId, skillName).catch((err) => console.error('[marketplace] purchase flow', err));}if (e.target.matches('.trial-btn')) {const skillName = e.target.dataset.skillName;const agentId = e.target.dataset.agentId;- if (agentId && skillName) await openTrialFlow(agentId, skillName, e.target);+ if (agentId && skillName) openTrialFlow(agentId, skillName, e.target).catch((err) => console.error('[marketplace] trial flow', err));}if (e.target.matches('.time-pass-btn')) {const skillName = e.target.dataset.skillName;const agentId = e.target.dataset.agentId;const duration = Number(e.target.dataset.duration);- if (agentId && skillName && duration) await openTimePassFlow(agentId, skillName, duration, e.target);+ if (agentId && skillName && duration) openTimePassFlow(agentId, skillName, duration, e.target).catch((err) => console.error('[marketplace] time-pass flow', err));}});diff --git a/src/solana/sns-subdomain.js b/src/solana/sns-subdomain.jsindex 911bd2272..0a7cfed27 100644--- a/src/solana/sns-subdomain.js+++ b/src/solana/sns-subdomain.js@@ -18,11 +18,46 @@* user.*/-import { Connection, Keypair, PublicKey, TransactionMessage, VersionedTransaction } from '@solana/web3.js';+import { createHash } from 'node:crypto';+import { Connection, Keypair, PublicKey, SystemProgram, TransactionMessage, VersionedTransaction } from '@solana/web3.js';import bs58 from 'bs58';const DEFAULT_RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+// SNS on-chain constants — do not change without verifying against bonfida's source.+const SNS_PROGRAM_ID = new PublicKey('namesLPneVptA9Z5rqUDD9tMTWEJwofgaYwp8cawRkX');+const ROOT_DOMAIN_ACCOUNT = new PublicKey('58PwtjSDuFHuUkYjH9BYnnQKHfwo9reZhC2zMJv9JPkx');+const HASH_PREFIX = 'SPL Name Service';++function _getHashedName(name) {+ return createHash('sha256').update(`${HASH_PREFIX}${name}`).digest();+}++function _getNameAccountKey(hashedName, nameClass, nameParent) {+ const seeds = [+ hashedName,+ nameClass ? nameClass.toBuffer() : Buffer.alloc(32),+ nameParent ? nameParent.toBuffer() : Buffer.alloc(32),+ ];+ const [pubkey] = PublicKey.findProgramAddressSync(seeds, SNS_PROGRAM_ID);+ return pubkey;+}++// Returns the on-chain PDA for `label.parentDomain` (e.g. "test.threews").+function _computeSubdomainKey(label, parentDomain) {+ const parentKey = _getNameAccountKey(+ _getHashedName(parentDomain),+ null,+ ROOT_DOMAIN_ACCOUNT,+ );+ const subKey = _getNameAccountKey(+ _getHashedName(`\x00${label}`),+ null,+ parentKey,+ );+ return subKey;+}+/*** Load the platform keypair that owns the parent .sol from* THREEWS_SOL_PARENT_SECRET_BASE58 (a base58-encoded 64-byte ed25519 secret).@@ -85,14 +120,20 @@ export function normalizeLabel(input) {/*** Check whether `label.<parent>` already exists on-chain.* Returns { exists: boolean, owner: string|null }.+ *+ * Implemented without @bonfida/spl-name-service to avoid ESM/borsh+ * version conflicts in Vercel's serverless bundler. Derivation is+ * verified to match bonfida's getDomainKeySync output.*/export async function checkSubdomainAvailability({ connection, parentDomain, label }) {- const sns = await import('@bonfida/spl-name-service');- const fullName = `${label}.${parentDomain.replace(/\.sol$/, '')}`;- const { pubkey } = sns.getDomainKeySync(fullName);+ const cleanParent = parentDomain.replace(/\.sol$/, '');+ const pubkey = _computeSubdomainKey(label, cleanParent);try {- const { registry } = await sns.NameRegistryState.retrieve(connection, pubkey);- return { exists: true, owner: registry.owner.toBase58() };+ const info = await connection.getAccountInfo(pubkey);+ if (!info) return { exists: false, owner: null };+ // NameRegistryState header layout: [parentName(32), owner(32), class(32)]+ const owner = new PublicKey(info.data.slice(32, 64));+ return { exists: true, owner: owner.toBase58() };} catch {return { exists: false, owner: null };}diff --git a/tests/api/avatars-upload-proxy.test.js b/tests/api/avatars-upload-proxy.test.jsindex e5549a9a0..c4ec60a9b 100644--- a/tests/api/avatars-upload-proxy.test.js+++ b/tests/api/avatars-upload-proxy.test.js@@ -20,6 +20,13 @@ vi.mock('../../api/_lib/auth.js', () => ({hasScope: () => true,}));+// CSRF check is wired into the proxy upload handler. Mock to always-pass —+// the CSRF contract is tested separately; here we want to exercise upload+// validation and storage paths.+vi.mock('../../api/_lib/csrf.js', () => ({+ requireCsrf: async () => true,+}));+vi.mock('../../api/_lib/rate-limit.js', () => ({limits: {upload: async () => ({ success: true }),diff --git a/tests/api/pump-fun-mcp.test.js b/tests/api/pump-fun-mcp.test.jsindex 39883258e..97adc532b 100644--- a/tests/api/pump-fun-mcp.test.js+++ b/tests/api/pump-fun-mcp.test.js@@ -6,11 +6,31 @@import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';import { Readable } from 'node:stream';-// Cold-import of /api/pump-fun-mcp transitively pulls the Solana web3 + pump-// SDK chain, which on a fresh Codespace can exceed 20s. We warm it in a hook-// with a generous window so the first test doesn't eat the cost under the-// default 5s testTimeout.-vi.setConfig({ testTimeout: 30_000, hookTimeout: 120_000 });+// Cold-import of /api/pump-fun-mcp transitively pulls @solana/web3.js (via+// src/solana/sns.js and src/pump/vanity-keygen.js), which on a fresh+// Codespace under contention can exceed 2 minutes. None of these tests+// actually call SNS or vanity-keygen, so we mock both upstream modules with+// the minimum surface the handler touches at *call time* — the routes that+// would invoke them aren't exercised here.+vi.mock('@solana/web3.js', () => ({+ Keypair: { generate: () => ({ publicKey: { toBase58: () => 'mocked' }, secretKey: new Uint8Array(64) }) },+ Connection: class {},+ PublicKey: class {+ constructor(s) { this._s = s; }+ toBase58() { return String(this._s); }+ toString() { return String(this._s); }+ toBuffer() { return Buffer.alloc(32); }+ },+}));+vi.mock('../../src/solana/sns.js', () => ({+ resolveSnsName: vi.fn(async () => null),+ reverseLookupAddress: vi.fn(async () => null),+}));+vi.mock('../../src/pump/vanity-keygen.js', () => ({+ generateVanityKey: vi.fn(async () => ({ publicKey: 'mocked', secretKey: 'mocked' })),+}));++vi.setConfig({ testTimeout: 15_000, hookTimeout: 60_000 });// Mock rate-limit + clientIp so the route never blocks on Upstash.vi.mock('../../api/_lib/rate-limit.js', () => ({@@ -72,7 +92,7 @@ let handlerRef;beforeAll(async () => {const mod = await import('../../api/pump-fun-mcp.js');handlerRef = mod.default;-});+}, 60_000);async function call(rpc) {const res = makeRes();diff --git a/vercel.json b/vercel.jsonindex eb88fe95a..f3795e2cf 100644--- a/vercel.json+++ b/vercel.json@@ -20,7 +20,7 @@"maxDuration": 60},"api/**/*.js": {- "includeFiles": "node_modules/@zauthx402/sdk/dist/**,examples/skills/pump-fun-strategy/**,data/archives/**,data/rss/**,data/_generated/**",+ "includeFiles": "node_modules/@zauthx402/sdk/dist/**,node_modules/@bonfida/spl-name-service/dist/esm/node_modules/**,examples/skills/pump-fun-strategy/**,data/archives/**,data/rss/**,data/_generated/**","maxDuration": 30}},