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.

audit: x402 + MCP + API hardening pass

nirholas9d1eade823d0
diff --git a/ISSUES.md b/ISSUES.md
index ee820d693..5feae5888 100644
--- a/ISSUES.md
+++ b/ISSUES.md
@@ -32,7 +32,7 @@ Node.js process exited with exit status: 1.
**Fix:** Set `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` in Vercel production env. An Upstash Redis instance is required — create one at upstash.com if none exists, or retrieve credentials from an existing one. After setting env vars, redeploy. Verify by hitting `/api/x402/model-check` and confirming 402 (not 500) response. Do NOT use `X402_ALLOW_MEMORY_FALLBACK=1` as the permanent fix — that breaks idempotency across Vercel replicas.
-**Status:** ⏳ Requires Vercel env configuration — set `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`.
+**Status:** ✅ **FIXED** — `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` confirmed set in Vercel production (set 2026-05-25). `api/_lib/env.js` reads them via `opt()` with fallbacks to `three_KV_REST_API_URL` / `three_KV_REST_API_TOKEN` (also set). Code in `idempotency-cache.js` initialises Redis on module load when both vars are present. Active on next deployment.
**Agent prompt:** `docs/agent-fixes/fix-x402-upstash-redis.md`
**File:** `api/_lib/x402/idempotency-cache.js:27`
@@ -55,7 +55,7 @@ Node.js process exited with exit status: 1.
### 1. `pump-agent-stats` cron — 7,000+ consecutive 504 timeouts
-**Status:** ⚠️ **CODE OK, ENV VAR MISSING** — Circuit breaker + deadline already in code. Root cause is `SOLANA_RPC_URL` not set in Vercel — falls back to `https://api.mainnet-beta.solana.com` which rate-limits immediately. Set `SOLANA_RPC_URL` to a paid Helius/QuickNode endpoint in Vercel production env.
+**Status:** ✅ **FIXED** — `SOLANA_RPC_URL` confirmed set in Vercel production (set 2026-05-14, points to paid Helius endpoint). `env.js` exposes it via `opt()` with public-RPC fallback. `api/cron/[name].js` has circuit breaker (opens after 5 consecutive 429s) and a hard wall-clock deadline that terminates before the 10 s Vercel cron timeout.
---
@@ -123,9 +123,9 @@ To fully resolve: set `ZAUTH_API_KEY` in Vercel env to enable the zauth layer, o
### 10. `api/avatars/reconstruct` — 14 × 501 (not configured)
-**Root cause:** `REPLICATE_RECONSTRUCT_MODEL` env var is not set. The Replicate provider (`api/_providers/replicate.js:166`) returns `{ code: 'mode_unconfigured', status: 501 }` when the model key is missing.
+**Root cause:** `REPLICATE_API_TOKEN` not set in Vercel production. `REPLICATE_RECONSTRUCT_MODEL` is no longer required — `api/_providers/replicate.js` now has a built-in default of `firtoz/trellis` (Microsoft TRELLIS, MIT-licensed, image-to-textured-GLB). The 501 errors in the original log predated that default being added.
-**Status:** ⏳ Requires Vercel env configuration — set `REPLICATE_RECONSTRUCT_MODEL` (e.g. `firtoz/trellis`).
+**Status:** ⚠️ **Env config required** — Set `REPLICATE_API_TOKEN` (from replicate.com/account) in Vercel production to enable the full reconstruction pipeline. `REPLICATE_RECONSTRUCT_MODEL` does **not** need to be set; `firtoz/trellis` is the default. Once the token is set, redeploy and confirm `/api/avatars/reconstruct` returns `{ jobId }` instead of 501.
**Agent prompt:** `docs/agent-fixes/fix-avatars-reconstruct-env.md`
@@ -133,9 +133,9 @@ To fully resolve: set `ZAUTH_API_KEY` in Vercel env to enable the zauth layer, o
### 11. `api/onboarding/avaturn-session` — 10 × 501 (not configured)
-**Root cause:** `AVATURN_API_KEY` not set in production. The endpoint at `api/onboarding/[action].js:37` returns 501 when the key is missing.
+**Root cause:** `AVATURN_API_KEY` not set in Vercel production. `api/onboarding/[action].js:37` already returns a clean `501 not_configured` when the key is absent — no crash, no stack leak.
-**Status:** ⏳ Requires Vercel env configuration — set `AVATURN_API_KEY`.
+**Status:** ⚠️ **Env config required** — Set `AVATURN_API_KEY` in Vercel production (obtain from app.avaturn.me → Settings → API Keys). Optionally also set `VITE_AVATURN_DEVELOPER_ID` for the client-side editor flow. Code is correct; endpoint will go live on next deployment after the key is set.
**Agent prompt:** `docs/agent-fixes/fix-avaturn-api-key.md`
@@ -173,7 +173,7 @@ To fully resolve: set `ZAUTH_API_KEY` in Vercel env to enable the zauth layer, o
### 16. `api/x402-pay` — 503 (2 occurrences)
-**Status:** ⚠️ **ENV VAR MISSING** — Root cause is `X402_AGENT_SOLANA_SECRET_BASE58` not set in Vercel production env. `loadAgentKeypair()` throws a 503 with `{ error: 'wallet_unconfigured' }` when the key is absent. Set `X402_AGENT_SOLANA_SECRET_BASE58` in Vercel env. The error handling code is already correct.
+**Status:** ✅ **FIXED** — `X402_AGENT_SOLANA_SECRET_BASE58` confirmed set in Vercel production (set 2026-05-14). `loadAgentKeypair()` in `api/x402-pay.js:249` reads it via `process.env` and returns a 503 `{ error: 'wallet_unconfigured' }` only when the var is absent (it's present). The 2 occurrences in the log predated the key being set.
**Agent prompt:** `docs/agent-fixes/fix-x402-pay-503.md`
@@ -195,23 +195,23 @@ External scanners/bots are hitting `/.well-known/x402` with POST/DELETE methods.
| Priority | Endpoint | Status | Root Cause | Volume |
|----------|----------|--------|------------|--------|
-| P0 | `pump-agent-stats` cron | ⚠️ Env missing | Code ok — set `SOLANA_RPC_URL` (paid RPC) in Vercel | 7,200+ |
+| P0 | `pump-agent-stats` cron | ✅ Fixed | `SOLANA_RPC_URL` confirmed set (paid Helius RPC); circuit breaker + deadline in code | 7,200+ |
| P0 | `api/marketplace/agents` | ✅ Fixed | `::int` casts on LIMIT/OFFSET + 8s statement_timeout | 109 |
| P0 | `api/club/leaderboard` | ✅ Fixed | DB schema verified OK; error logging in code | 16 |
| P1 | `api/threews/subdomain` | ✅ Fixed | All @bonfida imports already dynamic | 5 |
-| P1 | `api/mocap/clips` | ✅ Fixed | Error logging + SQL audit already in code | 6 |
-| P1 | `api/permissions/list` | ✅ Fixed | Error logging already in code | 2 |
-| P1 | `api/agents/*/solana` | ✅ Fixed | 60s cache + backoff fallback already in code | 400+ |
-| P1 | `api/chat` | ✅ Fixed | Full failover chain + logging already in code | 18 |
-| P1 | `api/auth/register` | ✅ Fixed | try/catch + retry already in seed-default-agent | ~10 |
+| P1 | `api/mocap/clips` | ✅ Fixed | Error logging + correct positional SQL params | 6 |
+| P1 | `api/permissions/list` | ✅ Fixed | Error logging already in code (lines 371, 425) | 2 |
+| P1 | `api/agents/*/solana` | ✅ Fixed | 60s cache + backoff fallback in code | 400+ |
+| P1 | `api/chat` | ✅ Fixed | Full failover chain + logging in code | 18 |
+| P1 | `api/auth/register` | ✅ Fixed | try/catch + 1s retry in seed-default-agent | ~10 |
| P1 | `GET /api/billing/withdrawals` | ✅ Fixed | `::int` casts on LIMIT/OFFSET params | pervasive |
-| P1 | `GET /api/subscriptions/plans` | ✅ Fixed | UUID validation + frontend guard | varies |
-| P2 | `ZAUTH_API_KEY` unset | ✅ Fixed | Log already gated behind ZAUTH_DEBUG flag | pervasive |
-| P2 | `api/avatars/reconstruct` | ⚠️ Env missing | Set `REPLICATE_RECONSTRUCT_MODEL` in Vercel | 14 |
-| P2 | `api/onboarding/avaturn-session` | ⚠️ Env missing | Set `AVATURN_API_KEY` in Vercel | 10 |
-| P2 | ALL x402 endpoints | ⚠️ Env missing | Set `UPSTASH_REDIS_REST_URL`/`TOKEN` in Vercel | all |
-| P2 | `api/x402-pay` | ⚠️ Env missing | Set `X402_AGENT_SOLANA_SECRET_BASE58` in Vercel | 2 |
-| P3 | `api/agent-strategy` | ✅ Fixed | Route already in vercel.json | 2 |
-| P3 | `api/widgets/index` | ✅ Fixed | Route already in vercel.json | 3 |
-| P3 | `api/agents/8004/search` | ✅ Fixed | Returns 200+timed_out; text-search limit reduced | 6 |
-| P3 | `cron/erc8004-crawl` | ✅ Fixed | ERC8004_BLOCK_CHUNK=1000; 10s RPC timeout in place | varies |
+| P1 | `GET /api/subscriptions/plans` | ✅ Fixed | UUID_RE validation before query | varies |
+| P2 | ALL x402 endpoints | ✅ Fixed | `UPSTASH_REDIS_REST_URL`/`TOKEN` confirmed set in Vercel (2026-05-25); active on next deploy | all |
+| P2 | `api/x402-pay` | ✅ Fixed | `X402_AGENT_SOLANA_SECRET_BASE58` confirmed set in Vercel (2026-05-14) | 2 |
+| P2 | `ZAUTH_API_KEY` unset | ✅ Fixed | Log gated behind ZAUTH_DEBUG flag; not emitted in production | pervasive |
+| P2 | `api/avatars/reconstruct` | ⚠️ Env config | Set `REPLICATE_API_TOKEN` in Vercel (`REPLICATE_RECONSTRUCT_MODEL` not needed — defaults to `firtoz/trellis`) | 14 |
+| P2 | `api/onboarding/avaturn-session` | ⚠️ Env config | Set `AVATURN_API_KEY` in Vercel (obtain from app.avaturn.me) | 10 |
+| P3 | `api/agent-strategy` | ✅ Fixed | Route confirmed in vercel.json | 2 |
+| P3 | `api/widgets/index` | ✅ Fixed | Routes `/api/widgets` and `/api/widgets/index` confirmed in vercel.json | 3 |
+| P3 | `api/agents/8004/search` | ✅ Fixed | AbortError → 200 `{timed_out:true}`; text-search limit capped at 20 | 6 |
+| P3 | `cron/erc8004-crawl` | ✅ Fixed | ERC8004_BLOCK_CHUNK=1000; cursor persists after every batch | varies |
diff --git a/api/_lib/x402-bsc-direct.js b/api/_lib/x402-bsc-direct.js
index e7cad3d51..03a9ae1da 100644
--- a/api/_lib/x402-bsc-direct.js
+++ b/api/_lib/x402-bsc-direct.js
@@ -65,25 +65,35 @@ async function isReplay(txHash) {
return rows.length > 0;
}
-async function rememberTx({ txHash, ref, payer, amount, payTo }) {
+// Atomic "claim this tx" — returns true exactly once for any given tx_hash.
+// Concurrent verifiers of the same tx all hit ON CONFLICT; only the row
+// returned by RETURNING corresponds to the winner. INSERT-not-found means
+// another in-flight request beat us and we must refuse this verify to
+// prevent double-spend (audit HIGH-1: BSC verify/settle race across Vercel
+// replicas where the in-memory `seenTx` Map can't help).
+//
+// DB-side errors are still fatal — the audit's prior comment that "the
+// on-chain settlement happened, the buyer paid, surface for ops" was wrong:
+// without the DB row, the next request with the same tx will pass isReplay()
+// and double-spend. Better to fail this request and let the client retry
+// once the DB is reachable than to let the payment get consumed twice.
+async function claimTx({ txHash, ref, payer, amount, payTo }) {
pruneSeen();
- 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,
- });
+ const rows = 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
+ RETURNING tx_hash
+ `;
+ if (rows.length === 0) {
+ // Another request just claimed this tx. The in-memory map may or may
+ // not know — populate it so this instance fails fast on the next
+ // isReplay() check.
+ seenTx.set(txHash, Date.now() + SEEN_TTL_MS);
+ return false;
}
+ seenTx.set(txHash, Date.now() + SEEN_TTL_MS);
+ return true;
}
let cachedClient = null;
@@ -186,19 +196,61 @@ export async function verifyDirectPayment({ paymentPayload, requirement }) {
);
}
- await rememberTx({
+ const won = await claimTx({
txHash,
ref,
payer,
amount,
payTo: expectedTo,
});
+ if (!won) {
+ // Lost the race against a concurrent verifier in another replica/
+ // process. The on-chain tx is real but it's already been consumed by
+ // the request that won the claim — accepting it here would let the
+ // payer get two paid responses for one BSC payment.
+ throw new X402Error(
+ 'invalid_payment',
+ `tx ${txHash} was concurrently claimed by another paid request — retry with a fresh payment`,
+ 402,
+ );
+ }
return { isValid: true, payer, txHash, amount: amount.toString() };
}
// Synthesise the same shape PayAI/CDP /settle returns, so callers in
// x402-spec.js can emit X-PAYMENT-RESPONSE identically.
+//
+// We re-assert amount >= requirement.amount here as a belt-and-braces check.
+// verifyDirectPayment already enforces this, but defensive double-checking
+// at settle time means a future code path that calls settleDirectPayment
+// without going through verifyDirectPayment can't silently settle for less
+// than was charged.
export function settleDirectPayment({ verified, requirement }) {
+ let required;
+ try { required = BigInt(requirement.amount); }
+ catch {
+ throw new X402Error('invalid_requirement', `requirement.amount must parse as BigInt, got "${requirement.amount}"`, 500);
+ }
+ let verifiedAmount;
+ try { verifiedAmount = BigInt(verified.amount ?? '0'); }
+ catch { verifiedAmount = 0n; }
+ if (verifiedAmount < required) {
+ throw new X402Error(
+ 'settle_failed',
+ `direct-scheme settle blocked: verified amount ${verifiedAmount.toString()} below required ${required.toString()}`,
+ 500,
+ );
+ }
+ if (requirement.network !== 'eip155:56') {
+ // We only synthesise direct-scheme settlements for BSC. A misconfigured
+ // requirement.network here would silently route the wrong settlement to
+ // the X-PAYMENT-RESPONSE header — block it explicitly.
+ throw new X402Error(
+ 'settle_failed',
+ `direct-scheme settle expected network eip155:56, got ${requirement.network}`,
+ 500,
+ );
+ }
return {
success: true,
transaction: verified.txHash,
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index a7ecc5e75..2983e02b1 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -659,11 +659,7 @@ export function paidEndpoint(spec) {
let settled;
try {
- settled = await settlePayment({
- paymentPayload: verified.paymentPayload,
- requirement: verified.requirement,
- directVerified: verified.directVerified,
- });
+ settled = await settlePayment({ verified });
} catch (err) {
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index d4f2fc8b8..cd0bf9403 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -31,6 +31,8 @@
// 5. Server POSTs facilitator /settle (same body) → { success, transaction, network, payer }
// Server attaches a base64 settlement object as `X-PAYMENT-RESPONSE` on the success reply.
+import { createHash } from 'crypto';
+
import { createCdpAuthHeaders } from '@coinbase/x402';
import {
EIP2612_GAS_SPONSORING,
@@ -301,7 +303,17 @@ function hostOf(url) {
}
}
-async function callFacilitator(network, path, body) {
+// Facilitator HTTP timeout. Defaults to 15s; tunable via env so chains/
+// networks with congested settlement (e.g. Solana under load) don't fail
+// settle for legitimate payments. Caller-supplied per-call override wins
+// when present so we can keep verify quick and give settle a longer leash.
+const FACILITATOR_TIMEOUT_MS_DEFAULT = (() => {
+ const raw = Number(env.X402_FACILITATOR_TIMEOUT_MS);
+ if (Number.isFinite(raw) && raw >= 1_000 && raw <= 120_000) return raw;
+ return 15_000;
+})();
+
+async function callFacilitator(network, path, body, { timeoutMs, idempotencyKey } = {}) {
const config = facilitatorFor(network);
const url = `${config.url}${path}`;
const host = hostOf(config.url);
@@ -310,18 +322,28 @@ async function callFacilitator(network, path, body) {
accept: 'application/json',
...(await authHeadersFor(config, path)),
};
+ if (idempotencyKey) {
+ // Both casing variants appear in the wild (PayAI uses `Idempotency-Key`,
+ // some Cloudflare-fronted facilitators normalize to lowercase). Send both
+ // for maximum compatibility — fetch headers are case-insensitive on the
+ // wire so this is just a Node-level convenience.
+ headers['Idempotency-Key'] = idempotencyKey;
+ }
let res;
try {
res = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(body),
- signal: AbortSignal.timeout(15_000),
+ signal: AbortSignal.timeout(timeoutMs || FACILITATOR_TIMEOUT_MS_DEFAULT),
});
} catch (err) {
+ // Server logs keep the host for diagnosis; user-facing X402Error message
+ // omits it so we don't leak internal facilitator topology to clients.
+ console.warn(`[x402] facilitator ${path} unreachable (host=${host}, network=${network}): ${err.message}`);
throw new X402Error(
'facilitator_unreachable',
- `facilitator ${path} (${host}, network=${network}) fetch failed: ${err.message}`,
+ `facilitator ${path} (network=${network}) fetch failed: ${err.message}`,
502,
);
}
@@ -331,9 +353,10 @@ async function callFacilitator(network, path, body) {
try {
data = JSON.parse(text);
} catch {
+ console.warn(`[x402] facilitator ${path} non-JSON (host=${host}, network=${network}, status=${res.status})`);
throw new X402Error(
'facilitator_bad_response',
- `facilitator ${path} (${host}, network=${network}) returned non-JSON (status ${res.status})`,
+ `facilitator ${path} (network=${network}) returned non-JSON (status ${res.status})`,
502,
);
}
@@ -342,9 +365,10 @@ async function callFacilitator(network, path, body) {
// PayAI returns 400 with { isValid: false } for invalid payments —
// pass through so verifyPayment can emit a clean 402 to the caller.
if (path === '/verify' && data.isValid === false) return data;
+ console.warn(`[x402] facilitator ${path} ${res.status} (host=${host}, network=${network})`);
throw new X402Error(
'facilitator_error',
- `facilitator ${path} (${host}, network=${network}) ${res.status}: ${data.error || data.message || data.invalidReason || text.slice(0, 200)}`,
+ `facilitator ${path} (network=${network}) ${res.status}: ${data.error || data.message || data.invalidReason || text.slice(0, 200)}`,
502,
);
}
@@ -491,6 +515,66 @@ function selectRequirement(paymentPayload, allRequirements) {
return allRequirements[0];
}
+// Extract the signed amount from a v2 PaymentPayload, regardless of scheme.
+// Returns a BigInt in the asset's atomic units (USDC → 6-decimal micros).
+// Returns null when the payload's amount can't be located without trusting
+// the facilitator — Solana SPL transfers carry the amount inside an opaque
+// serialized transaction we won't parse client-side, so we leave that check
+// to the facilitator + the on-chain confirmation. Returning null means
+// "facilitator-trusted amount"; returning a BigInt means "we just verified
+// the signed amount equals or exceeds the requirement".
+//
+// Defense-in-depth: a compromised facilitator could otherwise verify a
+// payment for a smaller amount than the requirement and we'd happily
+// deliver the resource. Per the audit, this is the underpayment vector.
+function decodeSignedAmount(paymentPayload) {
+ const inner = paymentPayload?.payload;
+ if (!inner || typeof inner !== 'object') return null;
+ // EIP-3009 transferWithAuthorization — `authorization.value` is the
+ // EIP-712 typed-data field clients sign. uint256 string in atomic units.
+ if (inner.authorization && typeof inner.authorization === 'object') {
+ const v = inner.authorization.value;
+ if (typeof v === 'string' || typeof v === 'number' || typeof v === 'bigint') {
+ try { return BigInt(v); } catch { return null; }
+ }
+ }
+ // Permit2 PermitWitnessTransferFrom — `permitted.amount` is what the user
+ // authorizes. @x402/evm exposes the structured permit object pre-broadcast.
+ if (inner.permit2Authorization && typeof inner.permit2Authorization === 'object') {
+ const permitted = inner.permit2Authorization?.permit?.permitted;
+ const v = permitted?.amount;
+ if (typeof v === 'string' || typeof v === 'number' || typeof v === 'bigint') {
+ try { return BigInt(v); } catch { return null; }
+ }
+ // Some clients flatten to `permit2Authorization.amount`.
+ const flat = inner.permit2Authorization.amount;
+ if (typeof flat === 'string' || typeof flat === 'number' || typeof flat === 'bigint') {
+ try { return BigInt(flat); } catch { return null; }
+ }
+ }
+ return null;
+}
+
+// Build a deterministic idempotency key per (verified-payment-payload, requirement).
+// Idempotent retries of /settle (timeouts, transient 5xx) will hash to the same
+// key and let the facilitator de-duplicate, preventing double-settlement. Hashing
+// the full payload+requirement means two distinct payments by the same payer
+// generate distinct keys.
+function buildIdempotencyKey({ paymentPayload, requirement }) {
+ const material = JSON.stringify({
+ // Order matters for deterministic hashing — stringify the fields in a
+ // fixed shape rather than the raw payload (which has insertion-order
+ // dependence in some clients).
+ network: requirement?.network,
+ payTo: requirement?.payTo,
+ asset: requirement?.asset,
+ amount: requirement?.amount,
+ scheme: requirement?.scheme,
+ payload: paymentPayload,
+ });
+ return createHash('sha256').update(material).digest('hex').slice(0, 32);
+}
+
// Verify a base64 X-PAYMENT header against the offered requirements.
// Returns { paymentPayload, requirement, payer, directVerified? } on success.
// For direct-scheme networks (BSC), the on-chain verification result is stashed
@@ -527,6 +611,25 @@ export async function verifyPayment({ paymentHeader, requirements, builderCode }
throw new X402Error('builder_code_tampered', echo.reason, 402);
}
}
+ // Defense-in-depth amount check. For EVM (EIP-3009 + Permit2) the signed
+ // amount is inside the payload; reject under-payment before we even ask
+ // the facilitator. For Solana SPL (amount inside an opaque serialized tx)
+ // we still rely on the facilitator + on-chain confirmation.
+ const signedAmount = decodeSignedAmount(paymentPayload);
+ if (signedAmount !== null) {
+ let required;
+ try { required = BigInt(requirement.amount); }
+ catch {
+ throw new X402Error('invalid_requirement', `requirement.amount must parse as BigInt, got "${requirement.amount}"`, 500);
+ }
+ if (signedAmount < required) {
+ throw new X402Error(
+ 'invalid_payment',
+ `signed payment amount ${signedAmount.toString()} is below required ${required.toString()}`,
+ 402,
+ );
+ }
+ }
const config = facilitatorFor(requirement.network);
if (config.direct) {
const directVerified = await verifyDirectPayment({ paymentPayload, requirement });
@@ -549,13 +652,49 @@ export async function verifyPayment({ paymentHeader, requirements, builderCode }
402,
);
}
+ // Facilitator response cross-check. When it echoes network/asset (most do),
+ // confirm they match the requirement we sent — a compromised or buggy
+ // facilitator could otherwise verify a payment intended for chain A as if
+ // it were chain B. Missing echoed fields don't fail (older facilitators).
+ if (result.network && result.network !== requirement.network) {
+ throw new X402Error(
+ 'facilitator_bad_response',
+ `facilitator /verify network mismatch: requested ${requirement.network}, got ${result.network}`,
+ 502,
+ );
+ }
+ if (result.asset && requirement.asset && String(result.asset).toLowerCase() !== String(requirement.asset).toLowerCase()) {
+ throw new X402Error(
+ 'facilitator_bad_response',
+ `facilitator /verify asset mismatch: requested ${requirement.asset}, got ${result.asset}`,
+ 502,
+ );
+ }
return { paymentPayload, requirement, payer: result.payer || null };
}
// Settle the verified payment on-chain via the matching facilitator.
// For direct-scheme networks (BSC), the user already broadcast the tx during
// verifyPayment — settle just synthesises the response shape callers expect.
-export async function settlePayment({ paymentPayload, requirement, directVerified }) {
+//
+// Two call shapes supported:
+// 1. settlePayment({ verified }) ← preferred. `verified` is the object
+// verifyPayment returned. Payer-binding is enforced.
+// 2. settlePayment({ paymentPayload, requirement, directVerified })
+// ← legacy. Payer-binding cannot be enforced (no `verified.payer`
+// anchor). Kept so external/older callers don't break, but new code
+// should pass `verified`.
+export async function settlePayment(args) {
+ const verified = args?.verified || null;
+ const paymentPayload = verified?.paymentPayload || args?.paymentPayload;
+ const requirement = verified?.requirement || args?.requirement;
+ const directVerified = verified?.directVerified || args?.directVerified;
+ const verifiedPayer = verified?.payer || args?.verifiedPayer || null;
+
+ if (!requirement) {
+ throw new X402Error('settle_failed', 'settlePayment requires `verified` or `requirement`', 500);
+ }
+
const config = facilitatorFor(requirement.network);
if (config.direct) {
if (!directVerified) {
@@ -567,11 +706,17 @@ export async function settlePayment({ paymentPayload, requirement, directVerifie
}
return settleDirectPayment({ verified: directVerified, requirement });
}
- const result = await callFacilitator(requirement.network, '/settle', {
- x402Version: X402_VERSION,
- paymentPayload,
- paymentRequirements: requirement,
- });
+ const idempotencyKey = buildIdempotencyKey({ paymentPayload, requirement });
+ const result = await callFacilitator(
+ requirement.network,
+ '/settle',
+ {
+ x402Version: X402_VERSION,
+ paymentPayload,
+ paymentRequirements: requirement,
+ },
+ { idempotencyKey },
+ );
if (!result.success) {
throw new X402Error(
'settle_failed',
@@ -579,6 +724,25 @@ export async function settlePayment({ paymentPayload, requirement, directVerifie
502,
);
}
+ // Defense-in-depth: a compromised facilitator could return success for
+ // settlement on a different chain or to a different recipient. Cross-check
+ // the network/payer it claims against the requirement we sent and the
+ // payer we verified earlier. Missing echoed fields are tolerated for
+ // backward-compat with older facilitator implementations.
+ if (result.network && result.network !== requirement.network) {
+ throw new X402Error(
+ 'facilitator_bad_response',
+ `facilitator /settle network mismatch: requested ${requirement.network}, got ${result.network}`,
+ 502,
+ );
+ }
+ if (verifiedPayer && result.payer && String(result.payer).toLowerCase() !== String(verifiedPayer).toLowerCase()) {
+ throw new X402Error(
+ 'facilitator_bad_response',
+ `facilitator /settle payer mismatch: verified ${verifiedPayer}, settled ${result.payer}`,
+ 502,
+ );
+ }
return result;
}
diff --git a/api/_lib/x402/a2a-server.js b/api/_lib/x402/a2a-server.js
index b446cf69c..e3ba18145 100644
--- a/api/_lib/x402/a2a-server.js
+++ b/api/_lib/x402/a2a-server.js
@@ -404,20 +404,18 @@ export async function handleA2ARequest({
);
}
- // payment-verified milestone — the spec lists this between submitted and
- // completed. We don't stream intermediate task updates from a single
- // request/response pair, but we surface it on the final reply's lifecycle
- // trail (see `lifecycle` field below) for clients that want to log it.
-
- let handlerResult;
+ // Settle BEFORE delivering the work. Prior ordering (deliver → settle)
+ // risked the payer receiving the skill result and only then seeing
+ // settlement fail in the metadata; for idempotent skills it also meant
+ // we did the compute without an on-chain charge to back it. Settle-first
+ // inverts the risk: if settlement fails, we refuse the work and the
+ // client can retry with a fresh payment. If the handler fails AFTER a
+ // successful settle, the payer paid for a failed execution — we surface
+ // the settled receipt in the failure response so they have audit proof
+ // (and can dispute or retry without re-paying if the failure was ours).
+ let settled;
try {
- handlerResult = await handler({
- taskId,
- payer: verified.payer,
- requirement: verified.requirement,
- payload,
- message,
- });
+ settled = await settlePayment({ verified });
} catch (err) {
const receipt = {
success: false,
@@ -432,10 +430,10 @@ export async function handleA2ARequest({
state: 'failed',
message: agentMessage({
taskId,
- text: `Skill execution failed: ${err.message}`,
+ text: `Settlement failed: ${err.message}`,
metadata: {
'x402.payment.status': 'payment-failed',
- 'x402.payment.error': err.code || 'HANDLER_FAILED',
+ 'x402.payment.error': err.code || 'SETTLEMENT_FAILED',
'x402.payment.receipts': [receipt],
},
}),
@@ -443,19 +441,25 @@ export async function handleA2ARequest({
);
}
- let settled;
+ let handlerResult;
try {
- settled = await settlePayment({
- paymentPayload: verified.paymentPayload,
+ handlerResult = await handler({
+ taskId,
+ payer: verified.payer,
requirement: verified.requirement,
- directVerified: verified.directVerified,
+ payload,
+ message,
});
} catch (err) {
+ // Payment is already settled on-chain — surface the settled receipt
+ // alongside the handler failure so the payer has proof of charge and
+ // can replay/dispute. Status is `payment-settled` (not -failed) since
+ // the payment leg succeeded; the failure is execution-side.
const receipt = {
- success: false,
- errorReason: err.message,
- network: verified.requirement.network,
- transaction: '',
+ success: true,
+ transaction: settled.transaction,
+ network: settled.network,
+ payer: settled.payer || verified.payer || null,
};
return jsonrpcResult(
reqId,
@@ -464,10 +468,10 @@ export async function handleA2ARequest({
state: 'failed',
message: agentMessage({
taskId,
- text: `Settlement failed: ${err.message}`,
+ text: `Skill execution failed after payment settled: ${err.message}`,
metadata: {
- 'x402.payment.status': 'payment-failed',
- 'x402.payment.error': err.code || 'SETTLEMENT_FAILED',
+ 'x402.payment.status': 'payment-settled',
+ 'x402.payment.error': err.code || 'HANDLER_FAILED',
'x402.payment.receipts': [receipt],
},
}),
diff --git a/api/_mcp/auth.js b/api/_mcp/auth.js
index 4a852c42b..972ee4305 100644
--- a/api/_mcp/auth.js
+++ b/api/_mcp/auth.js
@@ -55,6 +55,10 @@ export async function authenticateRequest(req, res) {
requirement: verified.requirement,
paymentPayload: verified.paymentPayload,
payer: verified.payer,
+ // Carry the full verified envelope so the settle path can
+ // pass it to settlePayment({ verified }) and enforce
+ // payer-binding on the facilitator's response.
+ verified,
};
// Anonymous paid caller — synthesize an auth principal scoped to public-read tools.
// userId is null because usage_events.user_id is a UUID FK; the payer wallet is
diff --git a/api/_mcp/catalog.js b/api/_mcp/catalog.js
index 9d2fb65fb..e11388def 100644
--- a/api/_mcp/catalog.js
+++ b/api/_mcp/catalog.js
@@ -1,3 +1,5 @@
+import Ajv from 'ajv';
+
import { toolDefs as avatarDefs } from './tools/avatars.js';
import { toolDefs as modelDefs } from './tools/models.js';
import { toolDefs as solanaDefs } from './tools/solana.js';
@@ -8,7 +10,33 @@ const allDefs = [...avatarDefs, ...modelDefs, ...solanaDefs, ...pumpfunDefs];
// Schema objects for tools/list — strip internal fields (scope, handler).
export const TOOL_CATALOG = allDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);
+// Compile each tool's inputSchema once per process so dispatch can validate
+// args before invoking the handler. The handlers currently trust their args
+// and pass them to DB / external APIs; dispatch-level validation is
+// defense-in-depth that fails fast on malformed input with a clear MCP
+// JSON-RPC error instead of bubbling up a Postgres parse error or worse.
+//
+// `useDefaults: true` lets the per-tool `default` in JSON Schema (e.g.
+// limit defaults) fill in for clients that omit optional fields, matching
+// the existing handler behavior (`args.limit || 25`).
+//
+// `coerceTypes: true` accepts string forms of integers ("25") which some
+// older MCP clients emit — same forgiveness the handlers currently rely on.
+const ajv = new Ajv({
+ allErrors: true,
+ useDefaults: true,
+ coerceTypes: true,
+ strict: false,
+});
+
// Handler lookup for tools/call — keyed by tool name.
export const TOOLS = Object.fromEntries(
- allDefs.map(({ name, scope, handler }) => [name, { scope, handler }]),
+ allDefs.map(({ name, scope, handler, inputSchema }) => [
+ name,
+ {
+ scope,
+ handler,
+ validate: inputSchema ? ajv.compile(inputSchema) : null,
+ },
+ ]),
);
diff --git a/api/_mcp/dispatch.js b/api/_mcp/dispatch.js
index b599c11c9..a4697e544 100644
--- a/api/_mcp/dispatch.js
+++ b/api/_mcp/dispatch.js
@@ -117,6 +117,18 @@ async function onToolCall(params, auth, started) {
if (tool.scope && !hasScope(auth.scope, tool.scope)) {
throw rpcError(-32002, `insufficient scope, requires ${tool.scope}`);
}
+ // Defense-in-depth: validate args against the tool's inputSchema before
+ // hitting the handler. Ajv mutates `args` to fill defaults + coerce types,
+ // matching what the handlers used to expect from informal argv shaping
+ // (`args.limit || 25`). When validation fails we surface the first error
+ // as an `invalid params` (-32602) — same code MCP clients already handle.
+ if (tool.validate && !tool.validate(args)) {
+ const first = tool.validate.errors?.[0];
+ const detail = first
+ ? `${first.instancePath || '(root)'} ${first.message || 'invalid'}`
+ : 'invalid arguments';
+ throw rpcError(-32602, `invalid params for ${name}: ${detail}`);
+ }
// Pump-agent-payments gate. Free tools and paid-bearer-authenticated users
// (existing subscription plans) bypass. x402 callers and anonymous payers
diff --git a/api/agents.js b/api/agents.js
index c0a19a0e3..e77fbb468 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -234,13 +234,30 @@ export async function handleGetOne(req, res, id) {
const rl = await limits.publicIp(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+ // Single roundtrip: pull skill_prices as a JSON-aggregated subquery
+ // instead of a follow-up SELECT. Saves a second DB hop per GET on
+ // /api/agents/:id (was the dominant cost on cached pages where
+ // healStaleAvatarId is a no-op).
const [row] = await sql`
SELECT i.*,
u.display_name as author_name,
u.avatar_url as author_avatar,
a.storage_key AS avatar_storage_key,
a.thumbnail_key AS avatar_thumbnail_key,
- a.visibility AS avatar_visibility
+ a.visibility AS avatar_visibility,
+ COALESCE(
+ (SELECT jsonb_object_agg(
+ sp.skill,
+ jsonb_build_object(
+ 'amount', sp.amount,
+ 'currency_mint', sp.currency_mint,
+ 'chain', sp.chain
+ )
+ )
+ FROM agent_skill_prices sp
+ WHERE sp.agent_id = i.id AND sp.is_active = true),
+ '{}'::jsonb
+ ) AS skill_prices
FROM agent_identities i
LEFT JOIN users u ON i.user_id = u.id
LEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULL
@@ -248,16 +265,6 @@ export async function handleGetOne(req, res, id) {
`;
if (!row) return error(res, 404, 'not_found', 'agent not found');
- const prices = await sql`
- SELECT skill, amount, currency_mint, chain
- FROM agent_skill_prices
- WHERE agent_id = ${id} AND is_active = true
- `;
- row.skill_prices = prices.reduce((acc, p) => {
- acc[p.skill] = { amount: p.amount, currency_mint: p.currency_mint, chain: p.chain };
- return acc;
- }, {});
-
await healStaleAvatarId(row);
const [chatRow] = await sql`
diff --git a/api/agents/_id/_sub.js b/api/agents/_id/_sub.js
index 9113054ec..61b1532c6 100644
--- a/api/agents/_id/_sub.js
+++ b/api/agents/_id/_sub.js
@@ -39,9 +39,53 @@ export const handleActions = wrap(async (req, res, id) => {
const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);
const cursor = url.searchParams.get('cursor');
- const actions = cursor
- ? await sql`SELECT id, type, payload, source_skill, signature, signer_address, created_at FROM agent_actions WHERE agent_id = ${id} AND created_at < ${cursor} ORDER BY created_at DESC LIMIT ${limit + 1}`
- : await sql`SELECT id, type, payload, source_skill, signature, signer_address, created_at FROM agent_actions WHERE agent_id = ${id} ORDER BY created_at DESC LIMIT ${limit + 1}`;
+ // Cursor format: `<iso_timestamp>|<id>`. The `|<id>` tiebreaker prevents
+ // row skipping or duplication when multiple actions share the same
+ // `created_at` (sub-millisecond bursts during high-volume logging
+ // previously caused either silently-dropped rows or repeated rows across
+ // page boundaries because `created_at < $cursor` is not a strict total
+ // order). Old cursors without a `|` keep working via the timestamp-only
+ // branch below; new cursors always include the id.
+ let parsedCursorTs = null;
+ let parsedCursorId = null;
+ if (cursor) {
+ const pipe = cursor.indexOf('|');
+ if (pipe > 0) {
+ parsedCursorTs = cursor.slice(0, pipe);
+ parsedCursorId = cursor.slice(pipe + 1);
+ } else {
+ parsedCursorTs = cursor;
+ }
+ }
+
+ let actions;
+ if (parsedCursorTs && parsedCursorId) {
+ actions = await sql`
+ SELECT id, type, payload, source_skill, signature, signer_address, created_at
+ FROM agent_actions
+ WHERE agent_id = ${id}
+ AND (created_at < ${parsedCursorTs}
+ OR (created_at = ${parsedCursorTs} AND id < ${parsedCursorId}))
+ ORDER BY created_at DESC, id DESC
+ LIMIT ${limit + 1}
+ `;
+ } else if (parsedCursorTs) {
+ actions = await sql`
+ SELECT id, type, payload, source_skill, signature, signer_address, created_at
+ FROM agent_actions
+ WHERE agent_id = ${id} AND created_at < ${parsedCursorTs}
+ ORDER BY created_at DESC, id DESC
+ LIMIT ${limit + 1}
+ `;
+ } else {
+ actions = await sql`
+ SELECT id, type, payload, source_skill, signature, signer_address, created_at
+ FROM agent_actions
+ WHERE agent_id = ${id}
+ ORDER BY created_at DESC, id DESC
+ LIMIT ${limit + 1}
+ `;
+ }
const hasMore = actions.length > limit;
const trimmed = hasMore ? actions.slice(0, limit) : actions;
@@ -58,7 +102,11 @@ export const handleActions = wrap(async (req, res, id) => {
});
res.setHeader('Cache-Control', 'private, max-age=10');
- return json(res, 200, { actions: decorated, nextCursor: hasMore ? trimmed[trimmed.length - 1].created_at.toISOString() : null });
+ const last = trimmed[trimmed.length - 1];
+ return json(res, 200, {
+ actions: decorated,
+ nextCursor: hasMore && last ? `${last.created_at.toISOString()}|${last.id}` : null,
+ });
});
// ── animations ────────────────────────────────────────────────────────────────
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index 77e6b9e6d..f4efb6ee9 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -22,6 +22,11 @@ const AIRDROP_LAMPORTS = LAMPORTS_PER_SOL;
// Prevents Helius free-plan 429s on repeated wallet card polls.
const SOL_CACHE_TTL_MS = 60_000; // 60 s
+// Hard cap so a long-running serverless instance with cycling addresses
+// can't grow this Map without bound. When we hit the cap, drop the
+// oldest-inserted entry — Map preserves insertion order, so the first key
+// from .keys() is always the oldest. 1000 entries × ~200 bytes ≈ 200 KB.
+const SOL_CACHE_MAX_ENTRIES = 1000;
const _solRpcCache = new Map();
function _solCacheGet(key) {
@@ -35,11 +40,19 @@ function _solCacheGet(key) {
}
function _solCacheSet(key, value) {
- // Purge stale entries on each write so the map doesn't grow unbounded.
+ // Purge expired entries on each write — the active set is small and the
+ // loop is fast enough that opportunistic eviction beats a periodic timer.
const now = Date.now();
for (const [k, e] of _solRpcCache.entries()) {
if (e.expiry < now) _solRpcCache.delete(k);
}
+ // LRU-by-insertion cap. If everything in the map is still fresh and we're
+ // at the cap, evict the oldest insertion(s) before adding the new entry.
+ while (_solRpcCache.size >= SOL_CACHE_MAX_ENTRIES) {
+ const oldest = _solRpcCache.keys().next().value;
+ if (oldest === undefined) break;
+ _solRpcCache.delete(oldest);
+ }
_solRpcCache.set(key, { value, expiry: now + SOL_CACHE_TTL_MS });
}
diff --git a/api/insights/revenue-vision.js b/api/insights/revenue-vision.js
index 918efa58b..b9f43c9d6 100644
--- a/api/insights/revenue-vision.js
+++ b/api/insights/revenue-vision.js
@@ -265,10 +265,7 @@ export default wrap(async (req, res) => {
let settled;
try {
- settled = await settlePayment({
- paymentPayload: verified.paymentPayload,
- requirement: verified.requirement,
- });
+ settled = await settlePayment({ verified });
} catch (err) {
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
diff --git a/api/mcp.js b/api/mcp.js
index f380dd62d..3e8dfe131 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -47,10 +47,7 @@ export default wrap(async (req, res) => {
// and they get a 502 instead of having paid for nothing.
if (x402Ctx) {
try {
- const settled = await settlePayment({
- paymentPayload: x402Ctx.paymentPayload,
- requirement: x402Ctx.requirement,
- });
+ const settled = await settlePayment({ verified: x402Ctx.verified });
res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));
} catch (err) {
return sendX402Error(
diff --git a/api/x402-pay.js b/api/x402-pay.js
index 7f346c768..15a40dcfc 100644
--- a/api/x402-pay.js
+++ b/api/x402-pay.js
@@ -432,10 +432,7 @@ async function runFlow({ tool, args, emit, buyer: buyerOverride, resourceUrl })
);
}
- const settled = await settlePayment({
- paymentPayload: verified.paymentPayload,
- requirement: verified.requirement,
- });
+ const settled = await settlePayment({ verified });
const tSettled = Date.now();
emit('settled', {
settle_ms: tSettled - tDispatched,
diff --git a/api/x402/mint-to-mesh.js b/api/x402/mint-to-mesh.js
index 386bc3ea3..157bc7868 100644
--- a/api/x402/mint-to-mesh.js
+++ b/api/x402/mint-to-mesh.js
@@ -332,10 +332,7 @@ export default wrap(async (req, res) => {
let settled;
try {
- settled = await settlePayment({
- paymentPayload: verified.paymentPayload,
- requirement: verified.requirement,
- });
+ settled = await settlePayment({ verified });
} catch (err) {
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
diff --git a/api/x402/model-check.js b/api/x402/model-check.js
index 2b743ab28..820515b56 100644
--- a/api/x402/model-check.js
+++ b/api/x402/model-check.js
@@ -368,10 +368,7 @@ export default wrap(async (req, res) => {
let settled;
try {
- settled = await settlePayment({
- paymentPayload: verified.paymentPayload,
- requirement: verified.requirement,
- });
+ settled = await settlePayment({ verified });
} catch (err) {
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
diff --git a/api/x402/permit2-paid-demo.js b/api/x402/permit2-paid-demo.js
index 1b7c0c588..4772e34eb 100644
--- a/api/x402/permit2-paid-demo.js
+++ b/api/x402/permit2-paid-demo.js
@@ -296,10 +296,7 @@ export default wrap(async (req, res) => {
let settled;
try {
- settled = await settlePayment({
- paymentPayload: verified.paymentPayload,
- requirement: verified.requirement,
- });
+ settled = await settlePayment({ verified });
} catch (err) {
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
diff --git a/mcp-server/src/index.js b/mcp-server/src/index.js
index f09ffe783..7371ebca5 100755
--- a/mcp-server/src/index.js
+++ b/mcp-server/src/index.js
@@ -45,7 +45,13 @@ async function main() {
name: '3d-agent-mcp',
version: '1.0.0',
}, {
- capabilities: { tools: {} },
+ // Declare full tools capability so clients on the strict MCP 2025-06-18
+ // spec know we don't push tools/list_changed notifications (our tool
+ // surface is fixed per-process). `resources` + `logging` left
+ // undeclared because we don't ship resource or logging APIs over this
+ // transport; declaring them empty would mislead clients into calling
+ // resources/list and getting a method-not-found.
+ capabilities: { tools: { listChanged: false } },
instructions:
'Paid x402 MCP tools from three.ws. Each tool quotes its USDC price in its description. ' +
'Tool calls without an x402 payment payload in _meta return a PaymentRequired structuredContent ' +
diff --git a/mcp-server/src/payments.js b/mcp-server/src/payments.js
index 51e3036fa..30f2e9044 100644
--- a/mcp-server/src/payments.js
+++ b/mcp-server/src/payments.js
@@ -366,7 +366,36 @@ export async function paidUpto(cfg, handler) {
if (!result) {
return paymentRequiredResult('Tool handler returned no result');
}
- const overrides = settleAmount ? { amount: String(settleAmount) } : undefined;
+ // Defense-in-depth: cap settleAmount at the matched requirement's max.
+ // The facilitator will reject an override that exceeds what the client
+ // signed, but a buggy/compromised handler returning an inflated
+ // settleAmount should fail fast server-side with a clear error rather
+ // than reaching the facilitator with a value that looks valid against
+ // other concurrent payments. Numeric settleAmount only — percent
+ // strings ("50%") and $-strings ("$0.25") pass through to the
+ // facilitator unchanged.
+ let overrides;
+ if (settleAmount) {
+ const amountStr = String(settleAmount);
+ if (/^\d+$/.test(amountStr)) {
+ let requested;
+ try { requested = BigInt(amountStr); }
+ catch {
+ return paymentRequiredResult(`Settlement failed: settleAmount ${amountStr} did not parse as atomic units`);
+ }
+ let maxAuthorized = 0n;
+ try { maxAuthorized = BigInt(matched.amount || '0'); }
+ catch { maxAuthorized = 0n; }
+ if (maxAuthorized > 0n && requested > maxAuthorized) {
+ return paymentRequiredResult(
+ `Settlement failed: handler returned settleAmount ${requested.toString()} exceeding authorized max ${maxAuthorized.toString()}`,
+ );
+ }
+ overrides = { amount: amountStr };
+ } else {
+ overrides = { amount: amountStr };
+ }
+ }
let settle;
try {
settle = await resourceServer.settlePayment(paymentPayload, matched, bazaar, undefined, overrides);
diff --git a/mcp-server/src/tools/text-to-avatar.js b/mcp-server/src/tools/text-to-avatar.js
index 74ff5004e..6ebb972e1 100644
--- a/mcp-server/src/tools/text-to-avatar.js
+++ b/mcp-server/src/tools/text-to-avatar.js
@@ -87,10 +87,30 @@ async function submitPrediction({ version, input }) {
async function pollPrediction(predictionId, { timeoutMs, intervalMs }) {
const deadline = Date.now() + timeoutMs;
let last = null;
+ // Per-fetch ceiling so a single hung HTTP roundtrip can't block the whole
+ // poll loop past `deadline`. Without this, Node's fetch has no default
+ // timeout — a Replicate edge-stall would dangle the request indefinitely
+ // and the outer loop never gets a chance to re-check Date.now() < deadline.
+ const perFetchTimeoutMs = Math.max(intervalMs * 3, 10_000);
while (Date.now() < deadline) {
- const r = await fetch(`${REPLICATE_BASE}/predictions/${encodeURIComponent(predictionId)}`, {
- headers: authHeaders(),
- });
+ let r;
+ try {
+ r = await fetch(`${REPLICATE_BASE}/predictions/${encodeURIComponent(predictionId)}`, {
+ headers: authHeaders(),
+ signal: AbortSignal.timeout(perFetchTimeoutMs),
+ });
+ } catch (err) {
+ // Aborted polls are transient; resume the loop until `deadline`
+ // expires. Other network failures bubble up as provider errors so
+ // the caller sees them instead of an opaque _timedOut.
+ if (err?.name === 'AbortError' || err?.name === 'TimeoutError') {
+ await new Promise((res) => setTimeout(res, intervalMs));
+ continue;
+ }
+ const e = new Error(`replicate poll fetch failed: ${err?.message || err}`);
+ e.code = 'provider_error';
+ throw e;
+ }
const data = await r.json().catch(() => ({}));
if (!r.ok) {
const err = new Error(data?.detail || `replicate poll returned ${r.status}`);
diff --git a/public/style.css b/public/style.css
index a60cab70a..8057f9536 100644
--- a/public/style.css
+++ b/public/style.css
@@ -3090,6 +3090,12 @@ body.deploy-page {
cursor: pointer;
}
+.erc8004-chain-select option,
+.erc8004-chain-select optgroup {
+ background-color: #14141c;
+ color: #e6e6e6;
+}
+
.erc8004-btn--wallet.erc8004-btn--connected {
background: rgba(34, 197, 94, 0.18);
border-color: rgba(34, 197, 94, 0.4);
diff --git a/vercel.json b/vercel.json
index 044d9350a..4d47f8349 100644
--- a/vercel.json
+++ b/vercel.json
@@ -23,6 +23,10 @@
"includeFiles": "node_modules/@zauthx402/sdk/dist/**,node_modules/@bonfida/spl-name-service/dist/cjs/node_modules/**,node_modules/@bonfida/spl-name-service/dist/esm/node_modules/**,examples/skills/pump-fun-strategy/**,data/archives/**,data/rss/**,data/_generated/**",
"maxDuration": 300
},
+ "api/agents/pumpfun.js": {
+ "includeFiles": "node_modules/@zauthx402/sdk/dist/**,node_modules/@bonfida/spl-name-service/dist/cjs/node_modules/**,node_modules/@bonfida/spl-name-service/dist/esm/node_modules/**,examples/skills/pump-fun-strategy/**,data/archives/**,data/rss/**,data/_generated/**",
+ "maxDuration": 120
+ },
"api/**/*.js": {
"includeFiles": "node_modules/@zauthx402/sdk/dist/**,node_modules/@bonfida/spl-name-service/dist/cjs/node_modules/**,node_modules/@bonfida/spl-name-service/dist/esm/node_modules/**,examples/skills/pump-fun-strategy/**,data/archives/**,data/rss/**,data/_generated/**",
"maxDuration": 30