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.

Pending changes exported from your codespace

nich5ed01e8d379c
diff --git a/.scratch-audit/boot.mjs b/.scratch-audit/boot.mjs
new file mode 100644
index 000000000..cec0dc809
--- /dev/null
+++ b/.scratch-audit/boot.mjs
@@ -0,0 +1,4 @@
+import { config } from 'dotenv';
+config({ path: '/workspaces/three.ws/.env' });
+config({ path: '/workspaces/three.ws/.env.local' });
+await import('/workspaces/three.ws/server/index.mjs');
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 101078e5c..f79ea38b1 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -3346,7 +3346,7 @@ Tiers: **CRITICAL** = `req()` in `api/_lib/env.js` (cold-start throw) or prod-fa
- **Voice / 3D gen:** `ELEVENLABS_API_KEY`, `NVIDIA_ASR_FUNCTION_ID`/`NVIDIA_A2F_FUNCTION_ID`/`NVIDIA_COSMOS_INVOKE_URL`, `LIVEKIT_API_KEY`/`_SECRET`/`_SERVER_URL`, `GCP_PROJECT`/`GCP_REGION`/`GCP_SERVICE_ACCOUNT_JSON`, `GCP_RECONSTRUCTION_URL`/`_KEY`, `GCP_TRIPOSG_URL`/`GCP_HUNYUAN3D_URL`/`GCP_REMESH_URL`/`GCP_TEXTURE_URL`/`GCP_STYLIZE_URL`/`GCP_SEGMENT_URL`/`GCP_REMBG_URL`/`GCP_TEXT2MOTION_URL`, `HF_TOKEN`/`HF_RECONSTRUCT_SPACE(S)`, `REPLICATE_API_TOKEN`/`_RECONSTRUCT_MODEL`/`_RERIG_MODEL`/`_POLL_MS`/`_TIMEOUT_MS`/`_WEBHOOK_URL`/`_WEBHOOK_SIGNING_KEY`, `NIM_TRELLIS_URL`/`_KEY`/`MODEL_TRELLIS_URL`, `TRIPO_MODEL_VERSION`, `VERTEX_IMAGEN_MODEL`, `CHROMIUM_PACK_URL`/`CHROME_PATH`/`PUPPETEER_EXECUTABLE_PATH`, `AVATURN_API_KEY`/`_API_URL`/`_SEED_ENABLED`, `MIXAMO_TOKEN`, `AVATAR_REGEN_PROVIDER`, `AUTO_RIG_DAILY_PER_USER`/`_GLOBAL_HOURLY`/`_PRIVATE`/`_REQUIRE_TIER`, `FORGE_ORIGIN`/`FORGE_PREFER_FREE`/`FORGE_FREE_POLL_MS`/`FORGE_PAID_GLOBAL_HOURLY`.
- **Pump.fun / $THREE / treasury:** `PUMP_X402_LAUNCHER_SECRET_KEY_B64`, `PUMP_CRON_RELAYER_SECRET_KEY_B64`, `PUMP_DEFAULT_AGENT_MINT`/`_NETWORK`, `PUMP_PLATFORM_FEE_BPS`/`_WALLET`, `PUMP_GRADUATIONS_SOURCE`/`GRADUATIONS_LIST_KEY`/`_MAX_LEN`, `PUMPFUN_BOT_TOKEN`/`_URL`/`PUMPFUN_MCP_URL`, `PUMP_COINS_V2_BASE`/`PUMP_FRONTEND_BASE`, `PUMPKIT_WEBHOOK_SECRET`, `THREE_WS_MARK_ENFORCE`/`ALLOW_UNMARKED_MINT`, `THREE_TOKEN_MINT`/`THREE_MINT`/`THREE_TOKEN_DECIMALS`, `THREE_PRIZE_PAYOUT_KEY`, `THREE_BURN_ADDRESS`, `THREE_QUOTE_TTL_S`, `THREE_ALLOWANCE_DELEGATE_SECRET_KEY_B64`, `THREE_BUYBACK_ENABLED`/`_SECRET_KEY_B64`/`_MIN_USD`/`_MAX_USD`/`_COMMIT_BPS`/`_SLIPPAGE_BPS`, `BUYBACK_BPS`, `PLATFORM_FEE_BPS`, `REWARDS_DISTRIBUTOR_SECRET`, `REFLECTION_DAILY_CAP`/`_DEBOUNCE_MS`/`REFLECT_SWEEP_BATCH`, `REFERRAL_COMMISSION_BPS`, `RIDER_VAULT_ADDRESS`/`_HELIUS_WEBHOOK_SECRET`, `CREDITS_DEPOSIT_WALLET_SOLANA`, `PURCHASE_RECEIPT_KEY`, `VANITY_SERVICE_KEY`/`VANITY_BOUNTY_PAYOUT_KEY`/`VANITY_DROP_FUNDING_KEY`, `COIN_TREASURY_SECRET_KEY_B64`, `COSMETIC_SPLIT_TREASURY_SECRET_KEY_B64`, `CLUB_SOLANA_TREASURY_SECRET_KEY_B64`/`CLUB_EVM_TREASURY_PRIVATE_KEY`/`CLUB_BASE_RPC_URL`/`CLUB_SWEEP_DUST_ATOMICS`.
- **Comms / observability:** `TELEGRAM_BOT_TOKEN`/`TELEGRAM_CHANGELOG_CHAT_ID`/`_ALERTS_CHAT_ID`/`_ORACLE_CHAT_ID`/`_SNIPER_CHAT_ID`, `RESEND_API_KEY`/`_AUDIENCE_ID`, `EMAIL_FROM`/`_REPLY_TO`, `SENTRY_DSN`/`_ENVIRONMENT`/`_RELEASE`, `AXIOM_TOKEN`/`_DATASET`/`_URL`, `VAPID_PUBLIC_KEY`/`_PRIVATE_KEY`/`_SUBJECT`, `DEV_TO_API_KEY`, `MEDIUM_INTEGRATION_TOKEN`/`_AUTHOR_ID`, `THREEWS_TWITTER_URL`.
-- **Cron / multiplayer / games / ops:** `CRON_SECRET`, `WEBHOOK_SECRET`/`ALLOW_UNSIGNED_WEBHOOKS`, `IRL_FIX_SECRET`/`IRL_X402_ALLOWED_HOSTS`, `X402_SWEEP_MAX_PRICE_USD`, `NODE_ENV`/`VERCEL_ENV`, `PUBLIC_APP_ORIGIN`, `MULTIPLAYER_SHARED_SECRET`/`_INTERNAL_URL`/`_URL`/`_API_BASE`, `REALM_TRANSFER_SECRET`, `WORLD_URL`/`WORLDS_URL`/`WORLD_API_BASE`, `GAME_SERVER_URL`, `WALK_URL`/`WALK_BASE`/`WALK_EMBED_BASE`, `GAME_TOKEN_MINT`/`_DECIMALS`/`_TREASURY`/`_SECRET`/`_REWARDS`, `PLAY_GATE_MINT`/`_MIN`/`_SYMBOL`, `HOLDER_MIN_USD`, `AGORA_MAINNET_ENABLED`/`_RECONCILE_MS`/`_DEVNET_MAX_SOL_PER_TASK`/`_MAX_THREE_PER_TASK`/`_THREE_MINT`/`_THREE_TOKEN_ACCOUNT`, `ORACLE_*` (MODE/NETWORK/GLOBAL_KILL/MAX_TRADE_SOL/USE_JITO/ALERT_MIN_TIER/intervals), `SNIPER_MODE`/`_NETWORK`/`_HEARTBEAT_MS`, `ORDERS_MODE`/`_NETWORK`/`SETTLE_MS`, `DCA_ALLOWED_TOKEN_OUT`/`_CHAIN_ID`, `CIRCULATION_*`, `SMART_GRAPH`/`_INTERVAL_MS`, `CLASH_*` (EPOCH_MS/MAX_FACTIONS/MAX_POWER_PER_WALLET/PASS_SECRET/WAR_RESULT_SECRET), `AUTOPILOT_COMPUTE_TREASURY`, `AGENT_WALLET_ALLOWED_ORIGINS`/`_MAX_USDC_MICROS`/`_DAILY_USDC_MICROS`, `AGENT_TRADE_NETWORK`/`_PRICE_SOL`/`AGENT_INVOCATION_NETWORK`/`_PROGRAM_ID`, `LABOR_ESCROW_SECRET_BASE58`/`LABOR_SKILL_ROYALTY_BPS`, `SKILL_LICENSE_ENFORCE`/`_MINTER_KEY`/`_PROGRAM_ID`/`SKILL_NFT_NETWORK`, `ATTEST_AGENT_SECRET_KEY`/`SAS_AUTHORITY_SECRET`, `CUSTODY_ANCHOR_NETWORK`/`_SNAPSHOT_NETWORK`, `ALLOWED_ORIGINS`, `COINBASE_PAY_APP_ID`, `VITE_WALLETCONNECT_PROJECT_ID`, `CZ_REGISTRY_CONTRACT`/`CZ_AGENT_ID`/`_NAME`, `SDP_API_BASE`/`_KEY`, `STUDIO_API_BASE`/`_PUBLIC_BASE`, `THREEWS_API_BASE`/`_ORIGIN`/`THREE_WS_API_BASE`/`_BASE`/`_API_KEY`.
+- **Cron / multiplayer / games / ops:** `CRON_SECRET`, `WEBHOOK_SECRET`/`ALLOW_UNSIGNED_WEBHOOKS`, `IRL_FIX_SECRET`/`IRL_X402_ALLOWED_HOSTS`, `X402_SWEEP_MAX_PRICE_USD`, `NODE_ENV`/`VERCEL_ENV`, `PUBLIC_APP_ORIGIN`, `MULTIPLAYER_SHARED_SECRET`/`_INTERNAL_URL`/`_URL`/`_API_BASE`, `REALM_TRANSFER_SECRET`, `WORLD_URL`/`WORLDS_URL`/`WORLD_API_BASE`, `GAME_SERVER_URL`, `WALK_URL`/`WALK_BASE`/`WALK_EMBED_BASE`, `GAME_TOKEN_MINT`/`_DECIMALS`/`_TREASURY`/`_SECRET`/`_REWARDS`, `PLAY_GATE_MINT`/`_MIN`/`_SYMBOL`, `HOLDER_MIN_USD`, `AGORA_MAINNET_ENABLED`/`_RECONCILE_MS`/`_DEVNET_MAX_SOL_PER_TASK`/`_MAX_THREE_PER_TASK`/`_THREE_MINT`/`_THREE_TOKEN_ACCOUNT`, `ORACLE_*` (MODE/NETWORK/GLOBAL_KILL/MAX_TRADE_SOL/USE_JITO/ALERT_MIN_TIER/intervals), `SNIPER_MODE`/`_NETWORK`/`_HEARTBEAT_MS`, `ORDERS_MODE`/`_NETWORK`/`SETTLE_MS`, `DCA_ALLOWED_TOKEN_OUT`/`_CHAIN_ID`, `CIRCULATION_*`, `SMART_GRAPH`/`_INTERVAL_MS`, `CLASH_*` (EPOCH_MS/MAX_FACTIONS/MAX_POWER_PER_WALLET/PASS_SECRET/WAR_RESULT_SECRET), `AUTOPILOT_COMPUTE_TREASURY`, `AGENT_WALLET_ALLOWED_ORIGINS`/`_MAX_USDC_MICROS`/`_DAILY_USDC_MICROS`, `AGENT_TRADE_NETWORK`/`_PRICE_SOL`/`AGENT_INVOCATION_NETWORK`/`_PROGRAM_ID`, `LABOR_ESCROW_SECRET_BASE58`/`LABOR_SKILL_ROYALTY_BPS`, `SKILL_LICENSE_ENFORCE`/`_MINTER_KEY`/`_PROGRAM_ID`/`SKILL_NFT_NETWORK`, `ATTEST_AGENT_SECRET_KEY`/`SAS_AUTHORITY_SECRET`, `CUSTODY_ANCHOR_NETWORK`/`_SNAPSHOT_NETWORK`, `ALLOWED_ORIGINS`, `VITE_WALLETCONNECT_PROJECT_ID`, `CZ_REGISTRY_CONTRACT`/`CZ_AGENT_ID`/`_NAME`, `SDP_API_BASE`/`_KEY`, `STUDIO_API_BASE`/`_PUBLIC_BASE`, `THREEWS_API_BASE`/`_ORIGIN`/`THREE_WS_API_BASE`/`_BASE`/`_API_KEY`.
- **Test/Ops only (not request surface):** `SMOKE_*`, `X402_BUYER_*`/`X402_TEST_*`/`X402_PAYER_*`, `TEST_EMAIL`/`_PASSWORD`, `GH_TOKEN`/`GITHUB_TOKEN`, `CC_*`, `DEV_API_PROXY`/`DEV_API_UPSTREAM`, `CI`/`DEBUG`/`DRY_RUN`/`HEADED`/`STRICT_A11Y`/`SKIP_NETWORK_TESTS`/`CONFIRM_MAINNET*`/`VERIFY_ONCHAIN_CHAINS`, Vercel/Codespaces platform vars.
> Fallback chains: secrets cascade `dedicated → WALLET_ENCRYPTION_KEY → JWT_SECRET`; Redis `UPSTASH_REDIS_REST_* → three_KV_* → KV_*`; Base RPC `BASE_RPC_URL → CLUB_BASE_RPC_URL → RPC_URL_8453`; `HELIUS_API_KEY` auto-derives from `SOLANA_RPC_URL`.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 73417db85..63668c1f8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Docs · Recurring payments** (`/docs/recurring-payments`): Sign one permission, then a fixed USDC amount moves every day or week, or gets swapped into a token on a schedule. The lifecycle, the API, what every kind of failed charge does to a schedule, and the operator config settlement needs.
- **Docs · The Agent Index** (`/docs/agent-index`): The platform's own cross-chain index of agent registrations, token launches, reputation attestations, transfers and delegations, Solana first: one public endpoint, absolute on-chain timestamps, and published index freshness.
- **A bounty that does not exist now says so, instead of blaming pump.fun**: The bounty board at /bounties mirrors the public pump.fun GO board. When you opened a bounty link that had been deleted or mistyped, the page reported it the same way it reports pump.fun being down, so there was no way to tell a dead link from an outage. A bounty that genuinely is not there now answers as not found, and a real upstream problem keeps its own separate answer. A second, quieter case got fixed with it: when the submissions list for a bounty failed to load, the page showed the bounty with zero submissions and said nothing, which looks identical to a bounty nobody has entered. That failure is now recorded, so a pump.fun outage shows up as an outage rather than as a board that suddenly looks unpopular. (`/bounties`) `[fix]`
+- **Apps that sign in with a client secret can now revoke and inspect their own tokens**: If you connect an app to three.ws over OAuth and registered it with a client secret sent in the Authorization header (client_secret_basic, the standard choice for server-side apps), only the token endpoint accepted those credentials. Revoking a token or checking whether one is still valid answered that the client_id was missing, and answered that the credentials were bad the moment you added it, so a confidential app had no way to sign a user out or verify a token it owned. All three endpoints now take the same credentials, in the header or in the form body, exactly as the OAuth revocation and introspection standards require. Dynamic client registration also now returns client_secret_expires_at alongside a new secret, so your client can tell that a three.ws secret never expires rather than guessing from a missing field. (`/docs/authentication`) `[fix, security]`
- **Avatar likeness is now measured against your photos, not assumed**: The promise behind the selfie flow is that the avatar looks like you, and until now nothing on the platform checked that. Two quality systems already existed and neither answered the question: one scores whether a generated model looks photorealistic, which a beautiful model of a stranger passes easily, and the other scores the head's shape offline against a synthetic test set and kept no record per avatar. Every finished reconstruction is now rendered from three angles and compared to the photos it was built from using the same kind of face-recognition model a phone uses to decide a face unlocks it. That produces a score out of 5 filed against the generation itself, and the scale is anchored to the model's own published cut-off for "same person" rather than to anyone's opinion, so 4 out of 5 means confidently you and not arguably you. A weekly sweep keeps the numbers current, and one of the three angles is a turned head on purpose: an avatar built by painting a photo onto a template can look right face-on and fall apart the moment it turns, and that is now a number somebody can see. The score is a measurement, never a guess: when the photos have no usable face, or the finished model has no recognisable face at all, it says which, instead of quietly reporting a bad score. `[infra, improvement, docs]`
- **Buying a skill from your phone no longer needs SOL in your wallet**: The QR code in the skill payment modal now hands your wallet a transaction we build for you, instead of asking the wallet to compose the transfer itself. Three things change for the buyer: three.ws pays the Solana network fee, so a wallet holding only USDC can complete the purchase; a creator who has never received this token before no longer causes the payment to fail, because the missing token account is created in the same transaction; and the whole payment still settles under one signature. Wallets that do not support this newer Solana Pay flow are one click away from the classic direct-transfer QR, which stays available under the code. (`/marketplace`) `[improvement, fix]`
- **Controls that promised an action and did nothing now actually do it**: Several buttons across the site were links pointing at nothing, so clicking them moved the page to the top and nothing else happened. On a coin or category page whose market data failed to load, "Reload the page" was one of them: the one control offered for recovery had no handler at all, so a reader who hit a data outage had no way out of it. It now re-runs the real request in place, skeletons and all, so a recovered feed repaints without a full page load. The "+ Link wallet" button on your account page was the same kind of dead end, pointing back at the section it already sat in; it now opens your Solana wallet, signs the ownership message, and links the wallet to your account, including moving a wallet that is currently linked somewhere else once your signature has proved it is yours. Clear filter on derivatives, Show all on stablecoins, Retry on search and on the world generator, skip for now in the dashboard checklist, Create one in the agent registry, and View more in Related Agents were all links pretending to be buttons; they are real buttons now, which means they answer the space bar, sit in the tab order where you expect, and show a visible focus ring. Picking a coin in the compare search is announced properly to a screen reader as you arrow through the list. `[fix, improvement]`
diff --git a/api/_lib/migrations/20260814020000_plugins_platform_identifier_uniq.sql b/api/_lib/migrations/20260814020000_plugins_platform_identifier_uniq.sql
new file mode 100644
index 000000000..3b1692708
--- /dev/null
+++ b/api/_lib/migrations/20260814020000_plugins_platform_identifier_uniq.sql
@@ -0,0 +1,61 @@
+-- Collapse the duplicated built-in plugins and make the duplication impossible.
+--
+-- `plugins` carries `unique (identifier, author_id)` and both seed migrations
+-- (2026-05-01-plugins.sql, 2026-05-21-plugins.sql) end their seed insert with
+-- `on conflict (identifier, author_id) do nothing`. That guard never fires for
+-- the built-ins, because they are platform-owned rows with `author_id IS NULL`
+-- and in a unique index NULL never equals NULL. So the second seed run inserted
+-- a complete second copy of all seven built-ins instead of skipping them.
+--
+-- The result was visible to every visitor: /api/plugins/list and the marketplace
+-- grid rendered "Calculator", "Weather", "Web Search" and the rest twice each,
+-- 14 rows where there are 7 plugins, and /api/plugins/categories reported
+-- doubled per-category counts.
+--
+-- The seed files are not edited. scripts/apply-migrations.mjs records a sha256
+-- per applied file and refuses to run when an applied migration's bytes change,
+-- so this rolls the fix forward instead.
+--
+-- Nothing references plugins(id) by foreign key, so collapsing a duplicate pair
+-- is a pure delete: keep the oldest row (the id that has existed longest and is
+-- therefore the one any bookmark or shared link points at) and carry the highest
+-- install_count of the group onto it so no counted install is lost.
+
+WITH ranked AS (
+ SELECT id,
+ identifier,
+ install_count,
+ row_number() OVER (PARTITION BY identifier ORDER BY created_at, id) AS rn
+ FROM plugins
+ WHERE author_id IS NULL
+),
+survivors AS (
+ SELECT identifier, id FROM ranked WHERE rn = 1
+),
+merged AS (
+ SELECT s.id, max(r.install_count) AS install_count
+ FROM survivors s
+ JOIN ranked r ON r.identifier = s.identifier
+ GROUP BY s.id
+)
+UPDATE plugins p
+SET install_count = m.install_count
+FROM merged m
+WHERE p.id = m.id AND p.install_count <> m.install_count;
+
+DELETE FROM plugins p
+USING (
+ SELECT id,
+ row_number() OVER (PARTITION BY identifier ORDER BY created_at, id) AS rn
+ FROM plugins
+ WHERE author_id IS NULL
+) d
+WHERE p.id = d.id AND d.rn > 1;
+
+-- The guarantee the composite unique key cannot give: one live platform-owned
+-- row per identifier. Scoped to `deleted_at IS NULL` so retiring a built-in
+-- never blocks re-seeding it later. A future seed must target this index
+-- explicitly: `on conflict (identifier) where author_id is null do nothing`.
+CREATE UNIQUE INDEX IF NOT EXISTS plugins_platform_identifier_uniq
+ ON plugins (identifier)
+ WHERE author_id IS NULL AND deleted_at IS NULL;
diff --git a/api/_lib/pay/payment-session.js b/api/_lib/pay/payment-session.js
index e3587168f..9e2b5ac2a 100644
--- a/api/_lib/pay/payment-session.js
+++ b/api/_lib/pay/payment-session.js
@@ -181,7 +181,7 @@ export async function getPaymentSession(sessionId, userId) {
* List sessions for a user. Returns latest-first.
*/
export async function listPaymentSessions(userId, { status, limit = 20, cursor } = {}) {
- const lim = Math.min(Number(limit) || 20, 100);
+ const lim = Math.min(Math.max(Math.floor(Number(limit)) || 20, 1), 100);
const rows = await sql`
SELECT id, user_id, agent_id, label, budget_usdc, spent_usdc,
max_per_tx_usdc, allowed_hosts, network, status, expires_at,
@@ -270,7 +270,7 @@ export async function cancelPaymentSession(sessionId, userId) {
* List executions for a session.
*/
export async function listSessionExecutions(sessionId, userId, { limit = 20, cursor } = {}) {
- const lim = Math.min(Number(limit) || 20, 100);
+ const lim = Math.min(Math.max(Math.floor(Number(limit)) || 20, 1), 100);
const rows = await sql`
SELECT id, endpoint_url, endpoint_host, method, amount_usdc,
network, tx_hash, payer_address, payee_address,
diff --git a/api/_lib/pay/probe.js b/api/_lib/pay/probe.js
index 55b29cd81..1a78cc4d1 100644
--- a/api/_lib/pay/probe.js
+++ b/api/_lib/pay/probe.js
@@ -13,6 +13,23 @@ import { validatePublicUrl, resolvePublicHost, pinnedAgent, SsrfError } from '..
/** Canonical USDC mint on Solana mainnet. */
export const USDC_SOLANA_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+/** Canonical USDC contract on Base mainnet, for the secondary EVM rail. */
+export const USDC_BASE_ADDRESS = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';
+
+/**
+ * How a session's network name maps onto the network ids a 402 challenge uses.
+ *
+ * A session stores the short name ("solana", "base"), but the wire format is
+ * CAIP-2: every live Base endpoint advertises `eip155:8453`, never `base`.
+ * Matching the short name against the challenge by prefix alone therefore found
+ * nothing for a Base session, so the simulator reported "no base payment option"
+ * for endpoints that were charging on Base right in front of it.
+ */
+const NETWORK_ALIASES = Object.freeze({
+ solana: ['solana'],
+ base: ['base', 'eip155:8453'],
+});
+
export const DEFAULT_TIMEOUT_MS = 20_000;
export function safeJson(text) {
@@ -85,7 +102,10 @@ export function describeRail(accept) {
// Every asset we transact in uses 6 decimals; a rail that does not is
// reported with a null price rather than a wrong one.
amount_usd: atomics === null ? null : Number(atomics) / 1_000_000,
- usdc: accept?.asset === USDC_SOLANA_MINT || /usdc/i.test(String(accept?.extra?.name ?? '')),
+ usdc:
+ accept?.asset === USDC_SOLANA_MINT ||
+ String(accept?.asset ?? '').toLowerCase() === USDC_BASE_ADDRESS ||
+ /usdc/i.test(String(accept?.extra?.name ?? '')),
};
}
@@ -145,7 +165,16 @@ export async function probePrice(rawUrl, { method = 'GET', body = null, timeoutM
*/
export function selectRail(rails, network = 'solana') {
const want = String(network || 'solana').toLowerCase();
- const onNetwork = rails.filter((r) => typeof r.network === 'string' && r.network.toLowerCase().startsWith(want));
+ const ids = NETWORK_ALIASES[want] ?? [want];
+ const onNetwork = rails.filter(
+ (r) =>
+ typeof r.network === 'string' &&
+ ids.some((id) => r.network.toLowerCase().startsWith(id)),
+ );
if (onNetwork.length === 0) return null;
- return onNetwork.find((r) => r.usdc) ?? onNetwork[0];
+ // A rail whose amount could not be parsed is worse than no rail: settling on
+ // it would mean signing for a price nobody read. Prefer a readable one.
+ const readable = onNetwork.filter((r) => r.amount_atomics !== null);
+ const pool = readable.length ? readable : onNetwork;
+ return pool.find((r) => r.usdc) ?? pool[0];
}
diff --git a/api/_lib/pay/spend-governor.js b/api/_lib/pay/spend-governor.js
index 29ad34ade..c82dbaa28 100644
--- a/api/_lib/pay/spend-governor.js
+++ b/api/_lib/pay/spend-governor.js
@@ -84,15 +84,28 @@ export function hashToken(token) {
return createHmac('sha256', hmacKey()).update(String(token)).digest('hex');
}
+// A session id is a v4 UUID. The shape is checked, not just the length: the
+// value goes straight into a `uuid` column comparison, and Postgres answers a
+// non-UUID string with a cast error, not with "no rows". Without this, any
+// 36-character blob inside a token turned an unauthenticated bad-token attempt
+// into a 500 instead of the invalid_token the caller should see.
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+/** Is this string safe to compare against a uuid column? */
+export function isSessionId(value) {
+ return UUID_RE.test(String(value ?? ''));
+}
+
// Extract sessionId from a token without verifying it. Used for DB lookup before
// the constant-time hash comparison.
export function extractSessionId(token) {
const s = String(token || '');
if (!s.startsWith(TOKEN_PREFIX)) return null;
const rest = s.slice(TOKEN_PREFIX.length);
- // Format after prefix: <uuid>_<random> — uuid is exactly 36 chars
+ // Format after prefix: <uuid>_<random>, and a UUID is exactly 36 chars.
if (rest.length < 37 || rest[36] !== '_') return null;
- return rest.slice(0, 36);
+ const id = rest.slice(0, 36);
+ return isSessionId(id) ? id : null;
}
/** Turn a policy rejection from policy.js into the thrown governance error. */
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 1f268f252..442ab9356 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -1019,6 +1019,11 @@ export const limits = {
critical: true,
}).limit('global'),
avatarPatch: (userId) => getLimiter('avatar:patch', { limit: 20, window: '1 h' }).limit(userId),
+ // Attaching an avatar to an agent (api/onboarding/link-avatar). Onboarding
+ // links once and reassignment is rare, so this is generous for real use while
+ // bounding a script that churns an agent's body. Its own bucket rather than
+ // avatarPatch's: editing avatar metadata must not exhaust the link budget.
+ avatarLink: (userId) => getLimiter('avatar:link', { limit: 30, window: '1 h' }).limit(userId),
prefsWrite: (userId) => getLimiter('prefs:write', { limit: 30, window: '1 h' }).limit(userId),
// Claiming a reputation-unlocked cosmetic onto an agent (api/agents/:id/unlocks).
// A low-frequency owner action; this just bounds abusive retries.
diff --git a/api/_lib/solana-token-meta.js b/api/_lib/solana-token-meta.js
index 31779f47c..e5306fd85 100644
--- a/api/_lib/solana-token-meta.js
+++ b/api/_lib/solana-token-meta.js
@@ -170,7 +170,14 @@ export async function fetchTokenImage(imageUrl) {
* imageUrl: string|null,
* image: { bytes: Uint8Array, mimeType: string } | null,
* externalUrl: string|null,
+ * raw: object|null,
* }>}
+ *
+ * `raw` is the parsed off-chain JSON document verbatim (null when the token has
+ * no `uri` or it could not be read). The named fields above cover what a token
+ * profile needs; a caller after anything else in the document (`animation_url`,
+ * `properties.files`, attributes) would otherwise have to fetch and parse the
+ * same document a second time.
*/
export async function fetchTokenMeta(mint, { network = 'mainnet', includeImage = true } = {}) {
const pk = solanaPubkey(mint);
@@ -212,5 +219,6 @@ export async function fetchTokenMeta(mint, { network = 'mainnet', includeImage =
imageUrl,
image,
externalUrl,
+ raw: off || null,
};
}
diff --git a/api/monetization/withdrawals.js b/api/monetization/withdrawals.js
index 3068f1974..854914487 100644
--- a/api/monetization/withdrawals.js
+++ b/api/monetization/withdrawals.js
@@ -1,8 +1,10 @@
// GET /api/monetization/withdrawals?agent_id=X — list withdrawal history
// POST /api/monetization/withdrawals — request a withdrawal
//
-// Body (POST): { agent_id, amount_usdc? }
-// amount_usdc = null → withdraw all available balance
+// Body (POST): { agent_id, amount_usdc?, network? }
+// amount_usdc = null withdraw all available balance
+// network 'solana' (default) | 'base' | 'evm'; picks which saved
+// payout wallet, and therefore which balance, is drawn on
import { z } from 'zod';
import { sql } from '../_lib/db.js';
@@ -25,8 +27,36 @@ const WITHDRAWAL_STATUSES = ['pending', 'processing', 'completed', 'failed'];
const postBody = z.object({
agent_id: z.string().uuid(),
amount_usdc: z.number().finite().positive().nullable().optional(),
+ // Which payout rail to draw on. Omitted means "use the saved preference",
+ // which falls back to Solana, the home chain.
+ network: z.enum(['solana', 'base', 'evm']).optional(),
});
+// `base` and `evm` are the same rail: rows written by wallet.js carry chain
+// 'base', while older rows carry 'evm'.
+const NETWORK_CHAINS = {
+ solana: ['solana'],
+ base: ['base', 'evm'],
+ evm: ['base', 'evm'],
+};
+
+/**
+ * Choose the payout wallet a withdrawal should land on.
+ * An explicit `network` is honored exactly (no silent cross-chain fallback, so a
+ * caller asking for Base never gets paid on Solana). Otherwise the stored
+ * preference wins, then Solana, then whatever the user has configured.
+ *
+ * @param {Array<{address: string, chain: string, preferred_network: string|null}>} wallets
+ * Candidates, already ordered agent-specific first.
+ * @param {string|undefined} network
+ * @returns {{address: string, chain: string, preferred_network: string|null}|undefined}
+ */
+function pickPayoutWallet(wallets, network) {
+ const on = (net) => wallets.find((w) => (NETWORK_CHAINS[net] ?? []).includes(w.chain));
+ if (network) return on(network);
+ return on(wallets[0].preferred_network ?? 'solana') ?? on('solana') ?? wallets[0];
+}
+
async function resolveUser(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id, source: 'session' };
@@ -135,7 +165,7 @@ export default wrap(async (req, res) => {
if (!rlUser.success) return rateLimited(res, rlUser, 'too many withdrawal requests');
const body = parse(postBody, await readJson(req));
- const { agent_id, amount_usdc } = body;
+ const { agent_id, amount_usdc, network } = body;
// Verify agent ownership
const [agent] = await sql`
@@ -145,8 +175,8 @@ export default wrap(async (req, res) => {
if (!agent) return error(res, 404, 'not_found', 'Agent not found');
if (agent.user_id !== userId) return error(res, 403, 'forbidden', 'You don\'t own this agent');
- // Resolve payout wallet
- const [wallet] = await sql`
+ // Resolve payout wallet. Agent-specific rows outrank the user-level fallback.
+ const wallets = await sql`
SELECT address, chain, preferred_network
FROM agent_payout_wallets
WHERE user_id = ${userId} AND (agent_id = ${agent_id} OR agent_id IS NULL)
@@ -154,12 +184,21 @@ export default wrap(async (req, res) => {
CASE WHEN agent_id = ${agent_id} THEN 0 ELSE 1 END,
is_default DESC,
created_at DESC
- LIMIT 1
`;
- if (!wallet) {
+ if (!wallets.length) {
return error(res, 422, 'no_payout_wallet', 'Configure a payout wallet before requesting a withdrawal');
}
+ // The chain decides the currency, and the currency decides which balance is
+ // withdrawable, so picking the wrong wallet strands real earnings. Taking the
+ // most recently saved row did exactly that: a user who added an EVM address
+ // after their Solana one could no longer withdraw Solana revenue, because the
+ // balance was then read in Base USDC and came back as zero.
+ const wallet = pickPayoutWallet(wallets, network);
+ if (!wallet) {
+ return error(res, 422, 'no_payout_wallet', `No payout wallet configured for ${network}`);
+ }
+
// Determine currency mint based on chain
const currencyMint = wallet.chain === 'solana'
? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'
diff --git a/api/nft/resolve.js b/api/nft/resolve.js
index e144e1795..f6d210faf 100644
--- a/api/nft/resolve.js
+++ b/api/nft/resolve.js
@@ -3,6 +3,8 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import { cacheGet, cacheSet } from '../_lib/cache.js';
import { dasRpcUrl } from '../_lib/nft-gate.js';
import { resolveGateway } from '../_lib/solana-agents-normalize.js';
+import { fetchTokenMeta } from '../_lib/solana-token-meta.js';
+import { evmFallbackProvider } from '../_lib/evm/rpc.js';
// NFT metadata is effectively immutable, but the Helius `getAsset` (DAS) and
// Alchemy `getNFTMetadata` calls behind this endpoint are billed per request and
@@ -37,6 +39,81 @@ async function readJsonBody(resp) {
}
}
+// Metadata documents are small JSON files; anything larger is not one.
+const MAX_METADATA_BYTES = 512 * 1024;
+
+/**
+ * Read an NFT metadata document from a token `uri`.
+ *
+ * Handles the three forms in the wild: an https URL, a decentralized pointer
+ * (ipfs:// or ar://, normalized to a gateway), and a fully on-chain
+ * `data:application/json` URI. Returns null on anything unreadable, so callers
+ * treat a bad document the same as a missing one.
+ */
+async function fetchMetadataDoc(uri) {
+ if (!uri) return null;
+ const raw = String(uri).trim();
+ if (raw.startsWith('data:application/json')) {
+ const comma = raw.indexOf(',');
+ if (comma < 0) return null;
+ const payload = raw.slice(comma + 1);
+ const body = /;base64/i.test(raw.slice(0, comma))
+ ? Buffer.from(payload, 'base64').toString('utf8')
+ : decodeURIComponent(payload);
+ try {
+ return JSON.parse(body);
+ } catch {
+ return null;
+ }
+ }
+ const url = resolveGateway(raw);
+ if (!url || !/^https?:\/\//i.test(url)) return null;
+ let resp;
+ try {
+ resp = await fetch(url, {
+ redirect: 'follow',
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
+ });
+ } catch {
+ return null;
+ }
+ if (!resp.ok) return null;
+ if (Number(resp.headers.get('content-length') || 0) > MAX_METADATA_BYTES) return null;
+ const text = await resp.text().catch(() => '');
+ if (!text || text.length > MAX_METADATA_BYTES) return null;
+ try {
+ return JSON.parse(text);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Pick the 3D model out of a metadata document.
+ *
+ * `properties.files[]` with a `model/*` type is the Metaplex convention our own
+ * mints write; `animation_url` pointing at a .glb/.gltf is what most EVM
+ * collections use. Test the extension against the path only, since a gateway
+ * URL carries a query string after it.
+ */
+function pickModel(doc) {
+ const files = Array.isArray(doc?.properties?.files) ? doc.properties.files : [];
+ const modelFile = files.find((f) => {
+ const t = f?.type || f?.mime;
+ return typeof t === 'string' && t.startsWith('model/') && f?.uri;
+ });
+ if (modelFile) return { model: resolveGateway(modelFile.uri), mime: modelFile.type || modelFile.mime };
+ const animation = typeof doc?.animation_url === 'string' ? doc.animation_url : null;
+ if (animation && /\.(glb|gltf)(\?|$)/i.test(animation)) {
+ return {
+ model: resolveGateway(animation),
+ mime: /\.gltf(\?|$)/i.test(animation) ? 'model/gltf+json' : 'model/gltf-binary',
+ };
+ }
+ return { model: null, mime: null };
+}
+
const ALCHEMY_NFT_HOST = {
1: 'eth-mainnet',
10: 'opt-mainnet',
@@ -54,6 +131,90 @@ const ALCHEMY_NFT_HOST = {
11155420: 'opt-sepolia',
};
+/**
+ * Keyless Solana rung: read the Metaplex metadata account over the platform's
+ * ordinary RPC failover chain and follow its `uri`.
+ *
+ * Helius DAS is metered, and on 2026-08-14 the account was capped ("max usage
+ * reached" on every getAsset), which took this endpoint to a blanket 502 with
+ * no way back. An NFT's metadata is public data on a public chain: nothing about
+ * reading it requires a billed indexer. This rung is slower (an account read
+ * plus a document fetch instead of one indexed call), so it runs only after DAS
+ * has failed.
+ *
+ * @returns {Promise<object|null>} the resolved descriptor, or null when the
+ * token exists but names no metadata document.
+ */
+async function resolveSolanaOnChain(id) {
+ const meta = await fetchTokenMeta(id, { includeImage: false });
+ const doc = meta.raw;
+ if (!doc && !meta.name) return null;
+ const { model, mime } = pickModel(doc);
+ return {
+ name: meta.name || id,
+ image: resolveGateway(meta.imageUrl) || null,
+ model: model || null,
+ mime: mime || null,
+ source: 'solana-rpc',
+ };
+}
+
+// ERC-721 and ERC-1155 both expose the metadata pointer, under different names.
+// Probing tokenURI first matches the far more common standard for 3D collectibles.
+const NFT_URI_ABI = [
+ 'function tokenURI(uint256 tokenId) view returns (string)',
+ 'function uri(uint256 id) view returns (string)',
+ 'function name() view returns (string)',
+];
+
+/**
+ * Keyless EVM rung: read the token's own metadata pointer through the chain's
+ * RPC failover list, for the same reason as the Solana rung above (Alchemy
+ * answered "Monthly capacity limit exceeded" on every getNFTMetadata call).
+ *
+ * @returns {Promise<object|null>} the resolved descriptor, or null when neither
+ * metadata interface answers.
+ */
+async function resolveEvmOnChain(chainId, contractAddress, tokenId) {
+ const { Contract } = await import('ethers');
+ const provider = await evmFallbackProvider(chainId);
+ const contract = new Contract(contractAddress, NFT_URI_ABI, provider);
+
+ let uri = null;
+ for (const method of ['tokenURI', 'uri']) {
+ try {
+ uri = await contract[method](tokenId);
+ if (uri) break;
+ } catch {
+ uri = null;
+ }
+ }
+ if (!uri) return null;
+
+ // ERC-1155 metadata URIs carry a literal {id} placeholder the client must
+ // substitute with the zero-padded 64-hex token id.
+ if (uri.includes('{id}')) {
+ uri = uri.replace('{id}', BigInt(tokenId).toString(16).padStart(64, '0'));
+ }
+
+ const doc = await fetchMetadataDoc(uri);
+ if (!doc) return null;
+ const { model, mime } = pickModel(doc);
+ let collection = null;
+ try {
+ collection = await contract.name();
+ } catch {
+ collection = null;
+ }
+ return {
+ name: doc.name || collection || `${contractAddress}:${tokenId}`,
+ image: resolveGateway(doc.image || doc.image_url) || null,
+ model: model || null,
+ mime: mime || null,
+ source: 'evm-rpc',
+ };
+}
+
export default wrap(async (req, res) => {
if (cors(req, res)) return;
if (!method(req, res, ['POST'])) return;
@@ -90,9 +251,21 @@ export default wrap(async (req, res) => {
await cacheSet(staleKey, result, RESOLVE_STALE_TTL_SECONDS).catch(() => {});
return result;
};
- // Provider unreachable → serve the last-known-good descriptor if we have one,
- // else fall through to the caller's error. Immutable metadata makes this safe.
- const serveStaleOr = async (onMiss) => {
+ // Indexer unusable (unreachable, capped, or misconfigured) → in order: read the
+ // chain directly, then serve the last-known-good descriptor, then surface the
+ // caller's error. The direct read comes first because it is authoritative and
+ // current; the stale tier is safe only because metadata is effectively
+ // immutable, so it is the second choice, not the first.
+ const rescue = async (onChain, onMiss) => {
+ try {
+ const direct = await onChain();
+ if (direct) return json(res, 200, await store(direct));
+ } catch (err) {
+ if (err?.code === 'mint_not_found' || err?.code === 'invalid_mint') {
+ return error(res, err.status === 400 ? 400 : 404, err.status === 400 ? 'bad_request' : 'not_found', err.message);
+ }
+ console.error('[nft/resolve] direct chain read failed', err?.message);
+ }
const lastGood = await cacheGet(staleKey).catch(() => null);
if (lastGood) {
console.warn('[nft/resolve] upstream unreachable, serving last-known-good for %s', cacheKey);
@@ -102,6 +275,8 @@ export default wrap(async (req, res) => {
};
if (chain === 'solana') {
+ const solanaRescue = (onMiss) => rescue(() => resolveSolanaOnChain(id), onMiss);
+
// `getAsset` is a DAS method, and Helius is the only provider in our stack
// that serves it. Reading SOLANA_RPC_URL here pointed the call at whatever
// general-purpose RPC was configured (production runs magicblock), which
@@ -111,11 +286,13 @@ export default wrap(async (req, res) => {
// dedicated HELIUS_API_KEY.
const rpcUrl = dasRpcUrl();
if (!rpcUrl) {
- return error(
- res,
- 503,
- 'not_configured',
- 'HELIUS_API_KEY not configured; solana nft resolution is unavailable',
+ return solanaRescue(() =>
+ error(
+ res,
+ 503,
+ 'not_configured',
+ 'HELIUS_API_KEY not configured and the token names no readable metadata',
+ ),
);
}
let resp;
@@ -128,21 +305,21 @@ export default wrap(async (req, res) => {
});
} catch (err) {
console.error('[nft/resolve] Helius network error', err?.message);
- return serveStaleOr(() =>
+ return solanaRescue(() =>
serverError(res, 502, 'upstream_error', new Error('Helius unreachable')),
);
}
if (!resp.ok) {
const txt = await resp.text().catch(() => '');
console.error('[nft/resolve] Helius error', resp.status, txt);
- return serveStaleOr(() =>
+ return solanaRescue(() =>
serverError(res, 502, 'upstream_error', new Error(`Helius error ${resp.status}`)),
);
}
const data = await readJsonBody(resp);
if (!data) {
console.error('[nft/resolve] Helius returned a non-JSON body');
- return serveStaleOr(() =>
+ return solanaRescue(() =>
serverError(res, 502, 'upstream_error', new Error('Helius returned a non-JSON body')),
);
}
@@ -152,7 +329,7 @@ export default wrap(async (req, res) => {
// misconfiguration. Only a real DAS miss is a 404.
if (data.error.code === -32601) {
console.error('[nft/resolve] configured RPC does not serve DAS getAsset');
- return serveStaleOr(() =>
+ return solanaRescue(() =>
serverError(res, 502, 'upstream_error', new Error(`DAS getAsset unsupported: ${msg}`)),
);
}
@@ -198,6 +375,17 @@ export default wrap(async (req, res) => {
if (!host) {
return error(res, 400, 'bad_request', `unsupported evm chainId ${parts[0]}`);
}
+ // Both the Alchemy call and the on-chain rung take these verbatim, so reject a
+ // malformed pair here rather than paying an upstream round-trip to be told.
+ if (!/^0x[0-9a-fA-F]{40}$/.test(contractAddress)) {
+ return error(res, 400, 'bad_request', 'evm contract must be a 0x-prefixed 20-byte address');
+ }
+ if (!/^(0x[0-9a-fA-F]+|\d+)$/.test(tokenId)) {
+ return error(res, 400, 'bad_request', 'evm tokenId must be decimal or 0x-hex');
+ }
+
+ const evmRescue = (onMiss) =>
+ rescue(() => resolveEvmOnChain(chainId, contractAddress, tokenId), onMiss);
// `env` exposes no ALCHEMY getter, so the previous `env.ALCHEMY_API_KEY` read
// was undefined in every environment: the whole EVM branch built a URL with a
@@ -206,7 +394,14 @@ export default wrap(async (req, res) => {
// scene/gate-check.js do) and say plainly when it is missing.
const apiKey = process.env.ALCHEMY_API_KEY;
if (!apiKey) {
- return error(res, 503, 'not_configured', 'ALCHEMY_API_KEY not configured; evm nft resolution is unavailable');
+ return evmRescue(() =>
+ error(
+ res,
+ 503,
+ 'not_configured',
+ 'ALCHEMY_API_KEY not configured and the token names no readable metadata',
+ ),
+ );
}
const url = `https://${host}.g.alchemy.com/nft/v3/${apiKey}/getNFTMetadata?contractAddress=${encodeURIComponent(contractAddress)}&tokenId=${encodeURIComponent(tokenId)}`;
let resp;
@@ -214,7 +409,7 @@ export default wrap(async (req, res) => {
resp = await fetch(url, { signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) });
} catch (err) {
console.error('[nft/resolve] Alchemy network error', err?.message);
- return serveStaleOr(() =>
+ return evmRescue(() =>
serverError(res, 502, 'upstream_error', new Error('Alchemy unreachable')),
);
}
@@ -224,14 +419,14 @@ export default wrap(async (req, res) => {
return error(res, 404, 'not_found', `Alchemy error ${resp.status}: ${txt}`);
}
console.error('[nft/resolve] Alchemy error', resp.status, txt);
- return serveStaleOr(() =>
+ return evmRescue(() =>
serverError(res, 502, 'upstream_error', new Error(`Alchemy error ${resp.status}`)),
);
}
const data = await readJsonBody(resp);
if (!data) {
console.error('[nft/resolve] Alchemy returned a non-JSON body');
- return serveStaleOr(() =>
+ return evmRescue(() =>
serverError(res, 502, 'upstream_error', new Error('Alchemy returned a non-JSON body')),
);
}
diff --git a/api/notifications/README.md b/api/notifications/README.md
index 65a5619c4..6342ba44f 100644
--- a/api/notifications/README.md
+++ b/api/notifications/README.md
@@ -11,12 +11,12 @@ Every route requires authentication and answers `401 { "error": "unauthorized" }
| Route | Does | Notes |
| --- | --- | --- |
| `GET /api/notifications?limit&type&before` | List recent notifications, newest first | `limit` 1..50 (default 20); `type` filters one notification type (e.g. `?type=pump_alert`, validated against `^[a-z0-9_]{1,40}$`); `before` is a `created_at` cursor for "load more" on [`pages/notifications.html`](../../pages/notifications.html). Returns `{ notifications, unread_count, has_more }` |
-| `POST /api/notifications/:id/read` | Mark a single notification as read | Idempotent (`read_at = coalesce(read_at, now())`); returns `{ id, read_at }`, 404 if the row is not the caller's. Handler: [`[id]/read.js`](./%5Bid%5D/read.js) |
+| `POST /api/notifications/:id/read` | Mark a single notification as read | Idempotent (`read_at = coalesce(read_at, now())`); returns `{ id, read_at }`, 400 if `:id` is not a uuid, 404 if the row is not the caller's. Handler: [`[id]/read.js`](./%5Bid%5D/read.js) |
| `DELETE /api/notifications/:id` | Permanently remove one notification | The bell's dismiss action and the MCP `delete_notification` tool; returns `{ ok, id, deleted }`. Handler: [`[id]/index.js`](./%5Bid%5D/index.js) |
| `POST /api/notifications/read-all` | Mark every unread notification as read | Returns `{ marked_read: <count> }` |
| `POST /api/notifications/track` | Record a re-engagement funnel event | Body `{ notification_id?, channel: 'push'\|'in_app', event: 'opened'\|'returned' }`. Closes the sent-to-opened-to-returned loop: the service worker ([`public/push-sw.js`](../../public/push-sw.js)) fires `opened` on push click, the app fires `returned` when it boots from `?source=push`. Session-auth only, CSRF-exempt idempotent beacon (deduped by a partial unique index); `sent` rows are written server-side by [`../_lib/notify.js`](../_lib/notify.js) |
| `GET /api/notifications/preferences` | Read the full resolved preference matrix | Returns `{ categories, channels, prefs, push: { subscribed_devices } }`, everything the settings UI renders from |
-| `PUT /api/notifications/preferences` | Save preference overrides | Body `{ categories: { <cat>: { <channel>: bool } }, telegram_chat_id? }`; sanitised sparse overlay, unknown keys dropped, returns the re-resolved matrix |
+| `PUT /api/notifications/preferences` | Save preference overrides | Body `{ categories: { <cat>: { <channel>: bool } }, telegram_chat_id? }`; sanitised sparse overlay, unknown keys dropped, returns the re-resolved matrix. **Partial:** the body merges onto what is stored, so a key you omit keeps its saved value. Send `telegram_chat_id: null` (or `''`) to disconnect Telegram deliberately. A malformed body is a 400 that writes nothing, never a silent reset |
## The preference matrix
@@ -25,6 +25,7 @@ Defaults and resolution live in [`../_lib/notify-prefs.js`](../_lib/notify-prefs
- `CATEGORIES`: the seven user-facing groups every notification type maps into: `sales`, `purchases`, `social`, `irl`, `alerts`, `creations`, `account` (each with a label and description for the UI). `categoryForType()` maps any notification `type` to its category; unmapped types fall back to `account` so a new type is never silently undeliverable.
- `CHANNELS`: `in_app` (the bell inbox, on by default for every category), `push` (Web Push, on by default but only reaches users who subscribed a device), `email` (defaults on only for money and security categories), `telegram` (opt-in, needs a linked chat id).
- `resolvePrefs(userId)` overlays the user's stored sparse prefs (table `notification_preferences`) onto the defaults, so a user who has never saved gets a sensible matrix and new categories appear automatically. `channelEnabled(prefs, type, channel)` is the single delivery gate the send path consults.
+- `readStoredPrefs(userId)` returns that stored sparse row untouched, without the defaults overlaid. The `PUT` merges onto it rather than onto the resolved matrix, so saving one category never freezes today's defaults for every other category into the row.
Muting `in_app` for a category really does silence the bell for it: [`../_lib/notify.js`](../_lib/notify.js) checks `channelEnabled(prefs, type, 'in_app')` *before* inserting into `user_notifications`, so a muted category writes no row, contributes nothing to `unread_count`, and never appears in `GET /api/notifications`. The other channels are independent: a user who mutes the bell for `social` but leaves push on still gets the OS notification (its payload simply carries a null `notificationId`). Turning `in_app` back on affects new notifications only; nothing is backfilled.
diff --git a/api/og/agent.js b/api/og/agent.js
index 895af7b7f..b3313e3c8 100644
--- a/api/og/agent.js
+++ b/api/og/agent.js
@@ -177,7 +177,10 @@ export default wrap(async (req, res) => {
const solAddress = typeof row.meta?.solana_address === 'string' ? row.meta.solana_address : null;
// ── Real enrichments, each timeout-guarded so the card always renders ──────
- const [balances, rep, pnl, tipsCount, achievements] = await Promise.all([
+ // The avatar fetch belongs in this batch, not after it: it is an independent
+ // CDN read, so awaiting it separately added its own budget on top of the
+ // slowest enrichment on every cold unfurl instead of overlapping with them.
+ const [balances, rep, pnl, tipsCount, achievements, avatarData] = await Promise.all([
solAddress ? withTimeout(getBalances({ chain: 'solana', address: solAddress }), 3000, null) : null,
withTimeout(getAgentReputation(id, { lite: true }), 3000, null),
withTimeout(realizedPnlFor(id), 2000, { sol: 0, wins: 0 }),
@@ -185,9 +188,9 @@ export default wrap(async (req, res) => {
// Best-effort: a warm cache (the profile page just loaded it) makes this
// free; a cold miss that overruns the budget just omits the badge.
withTimeout(loadAgentAchievements(id), 2500, null),
+ loadAvatarImage(row),
]);
- const avatarData = await loadAvatarImage(row);
const svg = renderCard({ id, row, solAddress, balances, rep, pnl, tipsCount, achievements, avatarData });
res.statusCode = 200;
diff --git a/api/og/three-token-badge.js b/api/og/three-token-badge.js
index b1c42fd1a..b7774055c 100644
--- a/api/og/three-token-badge.js
+++ b/api/og/three-token-badge.js
@@ -9,11 +9,14 @@
* with image/svg+xml + a CDN cache header, no heavy canvas/satori deps in the
* serverless bundle. Social crawlers accept image/svg+xml for og:image.
*
- * Every figure on the card is real, and read from the same two sources that back
- * GET /api/three-token/stats (what the /three-token page renders), so the card
- * and the page can never disagree:
+ * Every figure on the card is real, and read from the same three sources that
+ * back GET /api/three-token/stats (what the /three-token page renders), so the
+ * card and the page can never disagree:
* market data, fetchTokenMarketData() (Birdeye → DexScreener → GeckoTerminal
* failover with a stale cache)
+ * holders, threeHolderCount() (our own snapshot, then a keyless rung),
+ * because the market sources that answer without a Birdeye key
+ * carry no holder count at all
* agent count, the same agent_identities count the stats endpoint runs
* Nothing is hardcoded. $THREE is the only coin this card ever references.
*
@@ -32,6 +35,7 @@
import { cors, wrap } from '../_lib/http.js';
import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';
import { fetchTokenMarketData } from '../_lib/market/token-market.js';
+import { threeHolderCount } from '../_lib/coin/three-holders.js';
import { sql } from '../_lib/db.js';
// Edge-cache the card: 60s fresh, 10m at the CDN, serve-stale-while-revalidate.
@@ -107,17 +111,23 @@ function fmtPct(n) {
// Resolve every datum the card shows from real sources, each independently
// resilient so one failing provider blanks a single figure rather than the card.
async function loadBadgeData() {
- const [market, agentRow] = await Promise.all([
+ const [market, agentRow, holderCount] = await Promise.all([
fetchTokenMarketData(THREE_MINT).catch(() => null),
sql`SELECT count(*)::int AS total FROM agent_identities WHERE deleted_at IS NULL`
.catch(() => [{ total: null }]),
+ // Same holder source /api/three-token/stats reads, and for the same reason:
+ // the keyless market rungs (DexScreener / GeckoTerminal) carry no holder
+ // count, so whenever Birdeye is unkeyed or quota-benched this is the only
+ // thing standing between the card and a permanently blank HOLDERS cell.
+ // Omitting it here is what let the card and the page disagree.
+ threeHolderCount().catch(() => null),
]);
return {
price: market?.price_usd ?? null,
change24h: market?.price_change_24h ?? null,
marketCap: market?.market_cap ?? null,
volume24h: market?.volume_24h ?? null,
- holders: market?.holders ?? null,
+ holders: market?.holders ?? holderCount ?? null,
agents: agentRow?.[0]?.total ?? null,
};
}
diff --git a/api/okx/3d/[service].js b/api/okx/3d/[service].js
index bfb871f1c..64ae7a41a 100644
--- a/api/okx/3d/[service].js
+++ b/api/okx/3d/[service].js
@@ -157,13 +157,19 @@ async function healthReport() {
// report briefly and let concurrent callers share the in-flight probe, so a
// poll loop costs the subsystems one sweep per window instead of one per
// request. Same shape /api/forge?health uses. `checkedAt` in the body tells the
-// caller how old the reading is.
-const HEALTH_TTL_MS = 30_000;
+// caller how old the reading is, and OKX_HEALTH_TTL_MS tunes the window (0
+// disables the memo and probes on every request).
+const HEALTH_TTL_DEFAULT_MS = 30_000;
let healthMemo = { at: 0, report: null };
let healthInFlight = null;
+function healthTtlMs() {
+ const raw = Number(process.env.OKX_HEALTH_TTL_MS);
+ return Number.isFinite(raw) && raw >= 0 ? raw : HEALTH_TTL_DEFAULT_MS;
+}
+
async function cachedHealthReport() {
- if (healthMemo.report && Date.now() - healthMemo.at < HEALTH_TTL_MS) return healthMemo.report;
+ if (healthMemo.report && Date.now() - healthMemo.at < healthTtlMs()) return healthMemo.report;
if (!healthInFlight) {
healthInFlight = healthReport()
.then((report) => {
diff --git a/api/onboarding/[action].js b/api/onboarding/[action].js
index d96749f0a..ac3e74866 100644
--- a/api/onboarding/[action].js
+++ b/api/onboarding/[action].js
@@ -17,19 +17,39 @@ const avaturnSchema = z.object({
avatar_type: z.enum(['v1', 'v2']).default('v1'),
});
-async function resolveAvaturnUser(req) {
+// Both onboarding actions write on the caller's behalf (one spends the avatar
+// provider's quota, the other repoints which body an agent wears), so both take
+// the same credential rules: a browser session, or a bearer credential carrying
+// the avatars:write grant. Keeping that in one resolver is what stops the two
+// from drifting apart: link-avatar previously accepted ANY bearer credential, so
+// a read-only `avatars:read` API key could rewrite an agent's avatar link even
+// though the handler directly above it had always demanded avatars:write.
+//
+// A bearer that authenticates but lacks the grant is a scope failure (403), not
+// an identity failure (401): answering 401 sends a machine client back to a token
+// exchange that would mint the exact same token again. Mirrors the 403
+// `insufficient_scope` answer in api/erc8004/[action].js and api/agents.js.
+// Returns the user id, or null after having already written the error response.
+async function resolveOnboardingUser(req, res, signInMessage) {
const session = await getSessionUser(req);
if (session) return session.id;
- const bearer = await authenticateBearer(extractBearer(req), { audience: undefined });
- if (!bearer || !hasScope(bearer.scope, 'avatars:write')) return null;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (!bearer) {
+ error(res, 401, 'unauthorized', signInMessage);
+ return null;
+ }
+ if (!hasScope(bearer.scope, 'avatars:write')) {
+ error(res, 403, 'insufficient_scope', 'avatars:write scope required');
+ return null;
+ }
return bearer.userId;
}
async function handleAvaturnSession(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const userId = await resolveAvaturnUser(req);
- if (!userId) return error(res, 401, 'unauthorized', 'sign in to create an avatar');
+ const userId = await resolveOnboardingUser(req, res, 'sign in to create an avatar');
+ if (!userId) return;
const rlUser = await limits.upload(userId);
if (!rlUser.success) return rateLimited(res, rlUser, 'too many avatar attempts, try again later');
const rlIp = await limits.authIp(clientIp(req));
@@ -37,29 +57,66 @@ async function handleAvaturnSession(req, res) {
if (!env.AVATURN_API_KEY) return error(res, 501, 'not_configured', 'Avatar editor is not available right now. Please try again later.');
const body = parse(avaturnSchema, await readJson(req, 8_000_000));
try {
- const url = `${env.AVATURN_API_URL}/api/v1/sessions`;
- const upstream = await fetch(url, {
- method: 'POST',
- headers: { authorization: `Bearer ${env.AVATURN_API_KEY}`, 'content-type': 'application/json', accept: 'application/json' },
- body: JSON.stringify({ external_user_id: userId, photos: body.photos, body_type: body.body_type, version: body.avatar_type }),
- });
- if (!upstream.ok) {
- const text = await upstream.text().catch(() => '');
- const err = new Error(`avaturn upstream ${upstream.status}: ${text.slice(0, 200)}`);
- err.status = upstream.status >= 500 ? 502 : upstream.status;
- err.code = upstream.status === 401 ? 'upstream_auth' : 'upstream_error';
- throw err;
- }
- const data = await upstream.json();
- const sessionUrl = data?.session_url || data?.url || data?.iframe_url;
- if (!sessionUrl) { const e = new Error('avaturn response missing session_url'); e.status = 502; e.code = 'upstream_error'; throw e; }
- return json(res, 200, { session_url: sessionUrl, expires_at: data.expires_at ?? null });
+ const session = await createProviderSession(userId, body);
+ return json(res, 200, { session_url: session.sessionUrl, expires_at: session.expiresAt });
} catch (err) {
- if (err.status >= 500) console.error('[avaturn-session] upstream failure:', err);
- return error(res, err.status || 502, err.code || 'upstream_error', err.message || 'avatar provider rejected request');
+ // A bare fetch rejection (DNS, TLS, socket timeout) carries no status; it is
+ // still our side of the call failing, so it takes the 502 path below.
+ const status = err.status || 502;
+ if (status >= 500) console.error(`[avaturn-session] provider call failed: ${err.message}`);
+ if (status === 429) {
+ return json(
+ res,
+ 429,
+ { error: 'upstream_busy', error_description: 'the avatar provider is busy, try again shortly' },
+ { 'cache-control': 'no-store', 'retry-after': err.retryAfter },
+ );
+ }
+ // Never hand a provider-side fault down as the caller's own message: it is
+ // ours to fix and its text can carry provider internals.
+ if (status >= 500) return error(res, 502, 'upstream_error', 'the avatar provider is unavailable right now');
+ return error(res, status, err.code || 'upstream_rejected', err.message);
}
}
+// Statuses that mean the CALLER's photos were the problem, so the provider's own
+// wording is worth passing through. Everything else (401/403 from our
+// AVATURN_API_KEY, 404 from our URL, any 5xx from their outage) is a server-side
+// fault. The first version mirrored those statuses verbatim, which meant a
+// rejected API key reached the browser as a 401 and src/avaturn-client.js mapped
+// it to its 'auth' code, pushing a correctly signed-in user at a sign-in that
+// could never fix anything. Worse, only >=500 was logged, so a revoked key failed
+// silently and looked like a user problem in every report.
+const CALLER_FIXABLE_UPSTREAM = new Set([400, 413, 415, 422]);
+
+async function createProviderSession(userId, body) {
+ const upstream = await fetch(`${env.AVATURN_API_URL}/api/v1/sessions`, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${env.AVATURN_API_KEY}`, 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify({ external_user_id: userId, photos: body.photos, body_type: body.body_type, version: body.avatar_type }),
+ });
+ if (!upstream.ok) {
+ const detail = (await upstream.text().catch(() => '')).slice(0, 200);
+ if (CALLER_FIXABLE_UPSTREAM.has(upstream.status)) {
+ throw Object.assign(new Error(detail || 'the avatar provider rejected these photos'), {
+ status: 400,
+ code: 'upstream_rejected',
+ });
+ }
+ if (upstream.status === 429) {
+ throw Object.assign(new Error(`avaturn upstream 429: ${detail}`), {
+ status: 429,
+ retryAfter: upstream.headers.get('retry-after') || '30',
+ });
+ }
+ throw Object.assign(new Error(`avaturn upstream ${upstream.status}: ${detail}`), { status: 502 });
+ }
+ const data = await upstream.json().catch(() => null);
+ const sessionUrl = data?.session_url || data?.url || data?.iframe_url;
+ if (!sessionUrl) throw Object.assign(new Error('avaturn response carried no session url'), { status: 502 });
+ return { sessionUrl, expiresAt: data.expires_at ?? null };
+}
+
// ── link-avatar ───────────────────────────────────────────────────────────────
const linkAvatarSchema = z.object({ avatarId: z.string().uuid(), force: z.boolean().default(false) });
@@ -67,10 +124,10 @@ const linkAvatarSchema = z.object({ avatarId: z.string().uuid(), force: z.boolea
async function handleLinkAvatar(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const session = await getSessionUser(req);
- const bearer = session ? null : await authenticateBearer(extractBearer(req));
- if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
- const userId = session?.id ?? bearer.userId;
+ const userId = await resolveOnboardingUser(req, res, 'sign in required');
+ if (!userId) return;
+ const rl = await limits.avatarLink(userId);
+ if (!rl.success) return rateLimited(res, rl, 'too many avatar link attempts, try again later');
const body = parse(linkAvatarSchema, await readJson(req));
const [avatar] = await sql`select id from avatars where id = ${body.avatarId} and owner_id = ${userId} and deleted_at is null limit 1`;
if (!avatar) return error(res, 404, 'not_found', 'avatar not found or not owned by you');
diff --git a/api/ops/money-health.js b/api/ops/money-health.js
index 154f3d816..836adf52e 100644
--- a/api/ops/money-health.js
+++ b/api/ops/money-health.js
@@ -38,7 +38,7 @@ const SUBSYSTEMS = [
// other failure (a renamed column, a dead connection) is a bug, and it rethrows
// so the board 500s loudly instead of reporting a silent, permanent null. Same
// convention as the verdict query below.
-async function lastActivity(table, ts) {
+export async function lastActivity(table, ts) {
if (!table) return null;
try {
const rows = await sql(`SELECT extract(epoch from max(${ts})) * 1000 AS ms FROM ${table}`);
diff --git a/api/oracle/og.js b/api/oracle/og.js
index 5150d5725..d69fb00dd 100644
--- a/api/oracle/og.js
+++ b/api/oracle/og.js
@@ -11,6 +11,8 @@
* hero right — name, symbol, category
* center — conviction score (large), tier badge
* pillars — four labeled bars (Who / How / What / Move)
+ * right lower — market cap (live for an unresolved coin, last recorded once
+ * it graduated or rugged)
* bottom-right — smart wallet count, graduated/live pill
* footer — "proof.not.promises"
*/
@@ -41,6 +43,16 @@ function shortMint(m) {
return `${m.slice(0, 6)}…${m.slice(-4)}`;
}
+/** Compact USD for the card: $1.2M / $845K / $912. Null for anything unusable. */
+function fmtUsd(v) {
+ const n = Number(v);
+ if (!Number.isFinite(n) || n <= 0) return null;
+ if (n >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;
+ if (n >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;
+ if (n >= 1e3) return `$${Math.round(n / 1e3)}K`;
+ return `$${Math.round(n)}`;
+}
+
function tierColor(tier) {
if (tier === 'prime') return '#c084fc';
if (tier === 'strong') return '#34d399';
@@ -121,26 +133,40 @@ async function buildCardData(mint) {
} catch { /* non-fatal */ }
}
- // Fetch live market cap if not yet resolved
- let liveMcap = null;
- if (!outcome?.graduated && !outcome?.rugged) {
- try {
- const r = await fetch(`${PUMP_FRONTEND_V3}/coins-v2/${mint}`, {
- headers: { accept: 'application/json' },
- signal: AbortSignal.timeout(3000),
- });
- if (r.ok) {
- const d = await r.json();
- liveMcap = d?.market_cap_in_usd ?? null;
- }
- } catch { /* non-fatal */ }
- }
+ // Live market cap, but only while the coin is still on the curve: a graduated
+ // or rugged coin reads its number off the recorded outcome instead.
+ const wantsLiveMcap = !outcome?.graduated && !outcome?.rugged;
- const logoBase64 = await fetchLogoBase64(imageUri);
+ // Two independent 3s-bounded round-trips, so the card costs one of them,
+ // not both in series.
+ const [logoBase64, liveMcap] = await Promise.all([
+ fetchLogoBase64(imageUri),
+ wantsLiveMcap ? fetchLiveMarketCap(mint) : Promise.resolve(null),
+ ]);
return { cv, outcome, name, symbol, logoBase64, category, liveMcap };
}
+// Live USD market cap for a coin still on the curve. pump.fun emits
+// `usd_market_cap` (with `market_cap_usd` as the v2 alias); this card used to ask
+// for a `market_cap_in_usd` key that does not exist, so the number was fetched on
+// every render and always came back null. Any failure returns null and the card
+// falls back to the recorded outcome cap, or omits the block.
+async function fetchLiveMarketCap(mint) {
+ try {
+ const r = await fetch(`${PUMP_FRONTEND_V3}/coins-v2/${mint}`, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(3000),
+ });
+ if (!r.ok) return null;
+ const d = await r.json();
+ const mcap = Number(d?.usd_market_cap ?? d?.market_cap_usd);
+ return Number.isFinite(mcap) && mcap > 0 ? mcap : null;
+ } catch {
+ return null;
+ }
+}
+
function pillarBar(label, val, color, x0, y0) {
const v = val != null ? Math.round(Number(val)) : null;
const barW = 230;
@@ -153,7 +179,7 @@ function pillarBar(label, val, color, x0, y0) {
<text x="${x0 + barW + 12}" y="${y0 + 17}" fill="${color}" font-size="14" font-weight="700">${x(txt)}</text>`;
}
-function renderCard(mint, d) {
+export function renderCard(mint, d) {
const { cv, outcome, name, symbol, logoBase64, category, liveMcap } = d;
const score = cv?.score != null ? Math.round(Number(cv.score)) : null;
@@ -188,6 +214,20 @@ function renderCard(mint, d) {
: `<rect x="80" y="148" width="112" height="112" rx="56" fill="#1a1d2e"/>
<text x="136" y="225" text-anchor="middle" fill="#4b5563" font-size="44">${x((displaySym || displayName)[0] || '?')}</text>`;
+ // Market cap. A live coin gets the price the pump.fun frontend reports right
+ // now; a graduated/rugged one gets the last cap the outcome tracker recorded,
+ // which is the only honest figure once the curve is gone.
+ const mcapValue = fmtUsd(liveMcap) || fmtUsd(outcome?.last_market_cap_usd);
+ const mcapLabel = liveMcap != null ? 'MARKET CAP' : 'LAST MARKET CAP';
+ const mcapBlock = mcapValue
+ ? `<text x="730" y="424" fill="rgba(229,229,229,0.35)"
+ font-family="Inter,-apple-system,system-ui,sans-serif"
+ font-size="13" letter-spacing="2">${x(mcapLabel)}</text>
+ <text x="730" y="466" fill="#e5e5e5"
+ font-family="Inter,-apple-system,system-ui,sans-serif"
+ font-size="36" font-weight="600" letter-spacing="-0.5">${x(mcapValue)}</text>`
+ : '';
+
// Smart wallet count badge
const smBadge = smCount != null
? `<rect x="80" y="468" width="${String(smCount).length * 14 + 120}" height="34" rx="8" fill="rgba(192,132,252,0.12)"/>
@@ -271,6 +311,9 @@ function renderCard(mint, d) {
${pillarBar('WHAT · NARRATIVE', pillar('narrative'), '#fbbf24', 730, 272)}
${pillarBar('MOVE · MOMENTUM', pillar('momentum'), '#f472b6', 730, 334)}
+ <!-- Market cap -->
+ ${mcapBlock}
+
<!-- Smart wallet count -->
${smBadge}
diff --git a/api/oracle/test-alert.js b/api/oracle/test-alert.js
index b8e93605e..de53cc59d 100644
--- a/api/oracle/test-alert.js
+++ b/api/oracle/test-alert.js
@@ -8,7 +8,8 @@
* supplied Telegram chat ID so the user can confirm their setup is working
* before they arm their agent and wait for a real signal.
*
- * Auth: session cookie or bearer token. Rate-limited to 2/min per IP.
+ * Auth: session cookie or bearer token. Rate-limited per IP by
+ * limits.oracleTelegramTestIp (see api/_lib/rate-limit.js for the ceiling).
*/
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
diff --git a/api/oracle/trades.js b/api/oracle/trades.js
index b0f7de84e..849c9758e 100644
--- a/api/oracle/trades.js
+++ b/api/oracle/trades.js
@@ -13,7 +13,7 @@
* Max duration: 45 s (client must reconnect on 'bye').
*/
-import { cors, method, rateLimited } from '../_lib/http.js';
+import { cors, method, rateLimited, error } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
import { knownWallet } from '../_lib/oracle/known-wallets.js';
@@ -28,18 +28,26 @@ const PING_INTERVAL_MS = 12_000;
// ── wallet annotation cache ───────────────────────────────────────────────────
// Pre-load the known traders for this coin once; annotate each trade in memory.
+// `pump_coin_wallets` is keyed on mint alone (no network column — the roster is
+// per-coin and a mint only ever exists on one network), while the reputation
+// ledger is keyed on (wallet, network). Joining them with `using (wallet,
+// network)` therefore fails outright, and the reputation score column is
+// `smart_money_score`, not `score`. Both mistakes were silent: the catch below
+// swallowed the error and every trade streamed with a null label, which is the
+// one thing this endpoint exists to provide. `tag` is seed-only — the ledger
+// has no such column.
async function loadWalletRoster(mint, network) {
try {
const rows = await sql`
select
w.wallet,
- coalesce(r.label, 'unproven') as label,
- coalesce(r.score, 0)::numeric as score,
- r.win_rate,
- r.tag
+ coalesce(r.label, 'unproven') as label,
+ coalesce(r.smart_money_score, 0)::numeric as score,
+ r.win_rate
from pump_coin_wallets w
- left join wallet_reputation r using (wallet, network)
- where w.mint = ${mint} and w.network = ${network}
+ left join wallet_reputation r on r.wallet = w.wallet and r.network = ${network}
+ where w.mint = ${mint}
+ order by (w.buy_lamports - w.sell_lamports) desc
limit 200
`;
const map = new Map();
@@ -47,15 +55,16 @@ async function loadWalletRoster(mint, network) {
// Fold in the seed if the live DB doesn't have a label yet.
let label = r.label;
let score = Number(r.score);
- let tag = r.tag;
+ let tag = null;
if (label === 'unproven' || !label) {
const known = knownWallet(r.wallet);
- if (known) { label = known.label; score = known.score; tag = known.tag || tag; }
+ if (known) { label = known.label; score = known.score; tag = known.tag || null; }
}
map.set(r.wallet, { label, score, win_rate: r.win_rate, tag });
}
return map;
- } catch {
+ } catch (e) {
+ console.warn('[oracle/trades] roster load failed:', e?.message);
return new Map();
}
}
@@ -100,11 +109,7 @@ export default async function handleOracleTrades(req, res) {
const mint = url.searchParams.get('mint') || '';
const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';
- if (!MINT_RE.test(mint)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'invalid mint' }));
- return;
- }
+ if (!MINT_RE.test(mint)) return error(res, 400, 'validation_error', 'a valid base58 mint is required');
// Pre-load the roster (non-blocking — if it fails we still stream trades).
const roster = await loadWalletRoster(mint, network);
diff --git a/api/oracle/watch.js b/api/oracle/watch.js
index 16cdf37d0..00b33647f 100644
--- a/api/oracle/watch.js
+++ b/api/oracle/watch.js
@@ -18,6 +18,7 @@ import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
+import { isUuid } from '../_lib/validate.js';
import { z } from 'zod';
import { getWatch, upsertWatch, recentActions, actionsSummary } from '../_lib/oracle/store.js';
@@ -74,6 +75,10 @@ export default wrap(async (req, res) => {
const agentId = (url.searchParams.get('agent_id') || '').trim();
const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';
if (!agentId) return error(res, 400, 'validation_error', 'agent_id is required');
+ // A non-uuid can never match agent_identities.id — without this the query
+ // below throws `invalid input syntax for type uuid`, the catch swallows it,
+ // and the caller is told they do not own an agent that cannot exist.
+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a uuid');
if (!(await ownsAgent(userId, agentId))) return error(res, 403, 'forbidden', 'you do not own this agent');
const [watch, actions, summary] = await Promise.all([
diff --git a/api/oracle/wins.js b/api/oracle/wins.js
index 96defa79c..b5689861a 100644
--- a/api/oracle/wins.js
+++ b/api/oracle/wins.js
@@ -7,7 +7,7 @@
* &tier=called|prime|strong|lean|watch|avoid|all default: called
* &min_ath=1 minimum ATH multiple to include
* &limit=50 max 100
- * &before=<iso> pagination cursor (scored_at <)
+ * &before=<cursor> pagination cursor, echoed from next_before
*
* Returns oracle_conviction rows that have a resolved outcome in
* pump_coin_outcomes, ordered by ATH multiple descending. This is the
@@ -27,18 +27,50 @@
* Public, IP rate-limited, 5-min CDN cache.
*/
-import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
+import { isoTimestamp } from '../_lib/validate.js';
import { QUOTE_MINT_LIST } from '../_lib/quote-mints.js';
const NETWORKS = new Set(['mainnet', 'devnet']);
const TIERS = new Set(['called', 'prime', 'strong', 'lean', 'watch', 'avoid', 'all']);
const PERIODS = { '7d': 7, '30d': 30, '90d': 90, 'all': null };
+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const NUMERIC_RE = /^\d+(\.\d+)?$/;
// The tiers the oracle actually tells people to act on.
const CALLED_TIERS = ['lean', 'strong', 'prime'];
+// ── keyset pagination ─────────────────────────────────────────────────────────
+// The gallery is ordered by ATH multiple, not by time, so a scored_at-only
+// cursor silently drops every remaining row that happens to be newer than the
+// last row of the previous page — on a 3-row page of the live feed that was 4
+// of the next 6 wins, gone. The cursor therefore carries the whole sort key:
+// "<ath_multiple>|<scored_at ISO>|<mint>". The ATH component is kept as the
+// exact numeric string Postgres returned, never a float round-trip, so the row
+// comparison lands on the same row the previous page ended on.
+
+function parseCursor(raw) {
+ if (!raw) return { ok: true, cursor: null };
+ const parts = String(raw).split('|');
+ // A bare timestamp is a cursor minted before the sort key landed (an open
+ // tab, a bookmarked call). Honour it on scored_at alone rather than 400ing.
+ if (parts.length === 1) {
+ const ts = isoTimestamp(parts[0]);
+ return ts ? { ok: true, cursor: { ath: null, ts, mint: null } } : { ok: false, cursor: null };
+ }
+ if (parts.length !== 3) return { ok: false, cursor: null };
+ const [ath, rawTs, mint] = parts;
+ const ts = isoTimestamp(rawTs);
+ if (!NUMERIC_RE.test(ath) || !ts || !MINT_RE.test(mint)) return { ok: false, cursor: null };
+ return { ok: true, cursor: { ath, ts, mint } };
+}
+
+function encodeCursor(row) {
+ return `${row.ath_multiple}|${new Date(row.scored_at).toISOString()}|${row.mint}`;
+}
+
function shapeRow(r) {
return {
mint: r.mint,
@@ -80,13 +112,17 @@ export default wrap(async (req, res) => {
const tier = TIERS.has(params.get('tier')) ? params.get('tier') : 'called';
const minAth = Math.max(1, Number(params.get('min_ath')) || 2);
const limit = Math.max(1, Math.min(100, parseInt(params.get('limit'), 10) || 50));
- const before = params.get('before') || null;
+
+ const { ok: cursorOk, cursor } = parseCursor(params.get('before'));
+ if (!cursorOk) return error(res, 400, 'validation_error', 'before must be a cursor echoed from next_before');
const tierFilter = tier === 'all' ? sql``
: tier === 'called' ? sql`and c.tier = any(${CALLED_TIERS}::text[])`
: sql`and c.tier = ${tier}`;
const periodFilter = days != null ? sql`and c.scored_at >= now() - (${days} || ' days')::interval` : sql``;
- const beforeFilter = before ? sql`and c.scored_at < ${before}::timestamptz` : sql``;
+ const beforeFilter = !cursor ? sql``
+ : cursor.ath == null ? sql`and c.scored_at < ${cursor.ts}::timestamptz`
+ : sql`and (o.ath_multiple, c.scored_at, c.mint) < (${cursor.ath}::numeric, ${cursor.ts}::timestamptz, ${cursor.mint})`;
const rows = await sql`
select
@@ -102,7 +138,7 @@ export default wrap(async (req, res) => {
${tierFilter}
${periodFilter}
${beforeFilter}
- order by o.ath_multiple desc nulls last, c.scored_at desc
+ order by o.ath_multiple desc, c.scored_at desc, c.mint desc
limit ${limit}
`.catch((e) => {
throw new Error(`wins query failed: ${e.message}`);
@@ -128,7 +164,7 @@ export default wrap(async (req, res) => {
const s = summary[0] || {};
const items = rows.map(shapeRow);
- const next_before = items.length >= limit ? items[items.length - 1].scored_at : null;
+ const next_before = rows.length >= limit ? encodeCursor(rows[rows.length - 1]) : null;
return json(res, 200, {
network,
diff --git a/api/pay/deal.js b/api/pay/deal.js
deleted file mode 100644
index f7dbb057f..000000000
--- a/api/pay/deal.js
+++ /dev/null
@@ -1,350 +0,0 @@
-// GET /api/pay/deal?service=brief&token=<mint|pool>
-// ─────────────────────────────────────────────────────────────────────────────
-// Server-Sent Events stream for an agent-to-agent deal on Solana.
-//
-// Agent A (this server's AVATAR_WALLET_SECRET) pays Agent B (AGENT_B_ADDRESS,
-// fallback: AVATAR_DEFAULT_RECIPIENT) for a real service — a live market brief
-// powered by GeckoTerminal data and, when watsonx is configured, narrated by
-// IBM Granite.
-//
-// Events emitted (text/event-stream):
-// event: line data: { speaker:'A'|'B', text, emotion }
-// event: quote data: { sol, usd, service, from, to }
-// event: paying data: { from, to, sol, lamports, memo }
-// event: paid data: { signature, explorer, sol, usd, from, to, network }
-// event: deliver data: { service, token, brief, source, governed? }
-// event: error data: { message }
-// event: done data: {}
-//
-// No mock paths. Every run executes a real on-chain SOL transfer.
-import { cors, method, wrap, error, rateLimited } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import {
- avatarWalletConfig,
- loadAvatarKeypair,
- getConnection,
- getSolBalance,
- solUsdPrice,
- sendSol,
- isValidPubkey,
- explorerTxUrl,
- LAMPORTS_PER_SOL,
-} from '../_lib/avatar-wallet.js';
-import { trendingPools, fetchOhlcv } from '../_lib/market/ohlcv.js';
-import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';
-
-const isBase58 = (s) => /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s);
-const FEE_BUFFER_LAMPORTS = 15_000;
-const DEAL_AMOUNT_USD = 0.01; // $0.01 per brief — real but tiny
-
-// ─── SSE helpers ─────────────────────────────────────────────────────────────
-function sseInit(res) {
- res.statusCode = 200;
- res.setHeader('content-type', 'text/event-stream; charset=utf-8');
- res.setHeader('cache-control', 'no-cache, no-transform');
- res.setHeader('connection', 'keep-alive');
- res.setHeader('x-accel-buffering', 'no');
- res.flushHeaders?.();
-}
-
-function emit(res, event, data) {
- if (res.writableEnded) return;
- res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
-}
-
-function line(res, speaker, text, emotion = 'patience') {
- emit(res, 'line', { speaker, text, emotion });
-}
-
-// ─── Market data ──────────────────────────────────────────────────────────────
-async function fetchBrief(tokenOrPool) {
- // Resolve to a pool address if a token mint was given.
- let pool = tokenOrPool;
- let tokenName = 'Solana market';
-
- // Get the top trending pool if nothing specific requested.
- try {
- const trending = await trendingPools('solana', 1);
- if (!tokenOrPool && trending[0]) {
- pool = trending[0].pool;
- tokenName = trending[0].name;
- }
- } catch {
- // Proceed with whatever we have.
- }
-
- if (!pool) return { tokenName, candles: [], summary: null };
-
- try {
- const { candles, base } = await fetchOhlcv({
- pool,
- network: 'solana',
- timeframe: 'hour',
- limit: 48,
- });
- if (base?.name) tokenName = `${base.name}${base.symbol ? ` (${base.symbol})` : ''}`;
- const closes = candles.map((c) => c.c).filter(Number.isFinite);
- if (!closes.length) return { tokenName, candles: [], summary: null };
-
- const current = closes[closes.length - 1];
- const open = closes[0];
- const high = Math.max(...closes);
- const low = Math.min(...closes);
- const changePct = ((current - open) / open) * 100;
- const direction = changePct > 0 ? 'up' : changePct < 0 ? 'down' : 'flat';
-
- const fmt = (n) =>
- n >= 1
- ? `$${n.toLocaleString(undefined, { maximumFractionDigits: 4 })}`
- : `$${n.toPrecision(4)}`;
-
- return {
- tokenName,
- pool,
- candles,
- summary: {
- current,
- open,
- high,
- low,
- changePct,
- direction,
- horizonHours: 48,
- formatted: {
- current: fmt(current),
- high: fmt(high),
- low: fmt(low),
- change: `${changePct >= 0 ? '+' : ''}${changePct.toFixed(2)}%`,
- },
- },
- };
- } catch {
- return { tokenName, candles: [], summary: null };
- }
-}
-
-// ─── Optional Granite narration ───────────────────────────────────────────────
-async function narrateBrief(tokenName, summary) {
- const cfg = watsonxConfig();
- if (!cfg.configured || !summary) return null;
-
- const { formatted, direction, changePct, horizonHours } = summary;
- const system =
- 'You are a concise AI market oracle. Summarize the given market data in exactly two short, ' +
- 'vivid sentences. State the direction and key levels. No hashtags, no emojis, no financial advice.';
- const user =
- `Token: ${tokenName}. Current: ${formatted.current}. ` +
- `48h change: ${formatted.change} (${direction}). High: ${formatted.high}, Low: ${formatted.low}. ` +
- `Summarize.`;
-
- try {
- const { text } = await watsonxChatComplete(cfg, {
- messages: [
- { role: 'system', content: system },
- { role: 'user', content: user },
- ],
- maxTokens: 120,
- temperature: 0.5,
- });
- return (text || '').trim() || null;
- } catch {
- return null;
- }
-}
-
-// ─── Main handler ─────────────────────────────────────────────────────────────
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
- if (!method(req, res, ['GET'])) return;
-
- const rl = await limits.publicIp(clientIp(req));
- if (!rl.success) return rateLimited(res, rl);
-
- // Wallet A
- const cfg = avatarWalletConfig();
- if (!cfg.configured) {
- return error(
- res,
- 503,
- 'wallet_unconfigured',
- 'Agent A wallet not configured — set AVATAR_WALLET_SECRET. Run: node scripts/gen-avatar-wallet.mjs',
- );
- }
-
- // Wallet B recipient
- const agentBAddress =
- (process.env.AGENT_B_ADDRESS || '').trim() || cfg.defaultRecipient || null;
- if (!agentBAddress || !isValidPubkey(agentBAddress)) {
- return error(
- res,
- 503,
- 'agent_b_unconfigured',
- 'Agent B address not configured — set AGENT_B_ADDRESS (any valid Solana pubkey; fund it to see received payments).',
- { agentAAddress: cfg.address },
- );
- }
-
- // Parse params
- const params = new URL(req.url, 'http://x').searchParams;
- const tokenOrPool = (params.get('token') || params.get('pool') || '').trim();
- const validTarget = tokenOrPool && isBase58(tokenOrPool) ? tokenOrPool : null;
-
- // Start SSE stream
- sseInit(res);
-
- try {
- // 1. Get SOL price
- let solPriceUsd;
- try {
- solPriceUsd = await solUsdPrice();
- } catch {
- emit(res, 'error', { message: 'Could not fetch SOL price — try again shortly.' });
- res.end();
- return;
- }
-
- const solAmount = DEAL_AMOUNT_USD / solPriceUsd;
- const lamports = Math.round(solAmount * LAMPORTS_PER_SOL);
- const fmtSol = solAmount.toFixed(6);
- const fmtUsd = `$${DEAL_AMOUNT_USD.toFixed(2)}`;
-
- // 2. Fetch market data (in parallel with opening dialogue so there's no wait)
- const briefPromise = fetchBrief(validTarget);
-
- // 3. Opening negotiation dialogue
- await new Promise((r) => setTimeout(r, 180));
- line(
- res,
- 'A',
- "Oracle, I need a live Solana market brief. What's your price?",
- 'curiosity',
- );
- await new Promise((r) => setTimeout(r, 900));
-
- // Resolve brief early for the quote
- const brief = await briefPromise;
- const { tokenName, summary } = brief;
-
- line(
- res,
- 'B',
- `For ${tokenName} — currently ${summary ? summary.formatted.change + ' over 48h' : 'live on-chain'} — I charge ${fmtSol} SOL (${fmtUsd}). Deal?`,
- 'curiosity',
- );
- await new Promise((r) => setTimeout(r, 700));
-
- // 4. Emit quote
- emit(res, 'quote', {
- sol: solAmount,
- usd: DEAL_AMOUNT_USD,
- service: `${tokenName} market brief`,
- from: cfg.address,
- to: agentBAddress,
- });
- await new Promise((r) => setTimeout(r, 500));
-
- line(res, 'A', `Deal. Transferring ${fmtSol} SOL on Solana now…`, 'curiosity');
- await new Promise((r) => setTimeout(r, 400));
-
- // 5. Check balance
- const connection = getConnection(cfg.rpcUrl);
- const keypair = loadAvatarKeypair(process.env.AVATAR_WALLET_SECRET);
- const { lamports: balance } = await getSolBalance(connection, keypair.publicKey);
-
- if (balance < lamports + FEE_BUFFER_LAMPORTS) {
- emit(res, 'error', {
- message: `Agent A wallet needs ~${((lamports + FEE_BUFFER_LAMPORTS) / LAMPORTS_PER_SOL).toFixed(5)} SOL. Balance: ${(balance / LAMPORTS_PER_SOL).toFixed(5)} SOL. Fund: ${cfg.address}`,
- fundAddress: cfg.address,
- fundUrl: `https://solscan.io/account/${cfg.address}`,
- balance: balance / LAMPORTS_PER_SOL,
- needed: (lamports + FEE_BUFFER_LAMPORTS) / LAMPORTS_PER_SOL,
- });
- res.end();
- return;
- }
-
- // 6. Emit paying
- const memo = `three.ws agent deal · ${tokenName} brief · ${fmtUsd}`;
- emit(res, 'paying', {
- from: cfg.address,
- to: agentBAddress,
- sol: solAmount,
- lamports,
- memo,
- });
-
- // 7. Execute the real on-chain transfer
- let signature;
- try {
- signature = await sendSol({
- connection,
- fromKeypair: keypair,
- to: agentBAddress,
- lamports,
- memo,
- });
- } catch (sendErr) {
- emit(res, 'error', {
- message: `On-chain transfer failed: ${sendErr?.message || 'unknown error'}`,
- });
- res.end();
- return;
- }
-
- const explorer = explorerTxUrl(signature, cfg.network);
-
- // 8. Emit paid
- emit(res, 'paid', {
- signature,
- explorer,
- sol: solAmount,
- usd: DEAL_AMOUNT_USD,
- from: cfg.address,
- to: agentBAddress,
- network: cfg.network,
- });
-
- await new Promise((r) => setTimeout(r, 400));
- line(
- res,
- 'B',
- `Payment confirmed — ${signature.slice(0, 8)}… on-chain. Delivering your brief now.`,
- 'celebration',
- );
- await new Promise((r) => setTimeout(r, 600));
-
- // 9. Narrate with Granite (optional, non-blocking)
- const narration = await narrateBrief(tokenName, summary);
- const briefText =
- narration ||
- (summary
- ? `${tokenName} is trading at ${summary.formatted.current}, ${summary.formatted.change} over 48 hours. ` +
- `High: ${summary.formatted.high}, Low: ${summary.formatted.low}.`
- : `${tokenName} data unavailable — live on Solana.`);
-
- // 10. Deliver
- emit(res, 'deliver', {
- service: `${tokenName} market brief`,
- token: tokenName,
- brief: briefText,
- source: narration ? 'GeckoTerminal + IBM Granite' : 'GeckoTerminal',
- governed: Boolean(narration),
- });
-
- line(
- res,
- 'B',
- briefText,
- summary?.direction === 'up'
- ? 'celebration'
- : summary?.direction === 'down'
- ? 'concern'
- : 'patience',
- );
- } catch (err) {
- emit(res, 'error', { message: err?.message || 'unexpected error' });
- }
-
- emit(res, 'done', {});
- res.end();
-});
diff --git a/api/pay/execute.js b/api/pay/execute.js
index cee2391c3..fe8fc8774 100644
--- a/api/pay/execute.js
+++ b/api/pay/execute.js
@@ -1,4 +1,4 @@
-// POST /api/pay/execute — execute an x402 payment using a Payment Session token.
+// POST /api/pay/execute: execute an x402 payment using a Payment Session token.
//
// This is the core "agent proposes spend, governance enforces" endpoint.
// The agent presents:
@@ -22,8 +22,7 @@
// token, which is a time-bounded spending grant, not wallet access.
import {
- Connection, PublicKey, Keypair, TransactionMessage, VersionedTransaction,
- ComputeBudgetProgram,
+ PublicKey, TransactionMessage, VersionedTransaction, ComputeBudgetProgram,
} from '@solana/web3.js';
import {
getAssociatedTokenAddressSync,
@@ -46,7 +45,6 @@ import {
} from '../_lib/pay/probe.js';
import { solanaConnection } from '../_lib/solana/connection.js';
import {
- usdToAtomics,
atomicsToUsd,
verifySessionToken,
reserveSessionSpend,
@@ -132,21 +130,45 @@ async function probe402(rawUrl, { method, body }) {
status: 422, code: 'missing_fee_payer',
});
}
+ if (!accept.payTo) {
+ throw Object.assign(new Error('Solana 402 challenge is missing payTo'), {
+ status: 422, code: 'missing_pay_to',
+ });
+ }
+
+ // The price is third-party input and every later step treats it as a BigInt:
+ // it sizes the budget reservation and the transfer instruction. Parsing it
+ // here means a challenge quoting "1.5" or "free" is a 422 about the service,
+ // not an uncaught throw that reserves nothing and reports a 500.
+ let amountAtomics;
+ try {
+ amountAtomics = BigInt(accept.amount);
+ } catch {
+ throw Object.assign(
+ new Error(`Service quoted an unreadable price (${accept.amount})`),
+ { status: 422, code: 'invalid_amount', detail: { amount: accept.amount ?? null } },
+ );
+ }
+ if (amountAtomics <= 0n) {
+ throw Object.assign(
+ new Error('Service quoted a non-positive price, which cannot be paid'),
+ { status: 422, code: 'invalid_amount', detail: { amount: String(amountAtomics) } },
+ );
+ }
const resource =
challenge.resource && typeof challenge.resource === 'object'
? challenge.resource
: { url: typeof challenge.resource === 'string' ? challenge.resource : rawUrl };
- return { challenge, accept, resource };
+ return { challenge, accept, resource, amountAtomics };
}
// ── Build and sign the Solana USDC transfer ─────────────────────────────────
-async function buildSolanaPayload({ accept, buyer, conn, resourceUrl }) {
+async function buildSolanaPayload({ accept, amount, buyer, conn, resourceUrl }) {
const mint = new PublicKey(accept.asset);
const payTo = new PublicKey(accept.payTo);
const feePayer = new PublicKey(accept.extra.feePayer);
- const amount = BigInt(accept.amount);
const senderAta = getAssociatedTokenAddressSync(
mint, buyer.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
@@ -220,7 +242,11 @@ export default wrap(async (req, res) => {
const idempotencyKey = body.idempotency_key ?? null;
try {
- validatePublicUrl(targetUrl);
+ // allowHttp is pinned off rather than left to the default, which relaxes
+ // to http outside production. This endpoint hands a caller-chosen URL a
+ // signed payment; a plaintext hop is not something a dev box should allow
+ // when the error message promises https.
+ validatePublicUrl(targetUrl, { allowHttp: false });
} catch {
return error(res, 400, 'invalid_url', 'url must be a public https endpoint');
}
@@ -246,7 +272,7 @@ export default wrap(async (req, res) => {
return error(res, err.status ?? 502, err.code ?? 'probe_failed', err.message, err.detail);
}
- // Endpoint is free — return the result directly without touching the session
+ // Endpoint is free: return the result directly without touching the session
if (probeResult.free) {
return json(res, 200, {
ok: true,
@@ -257,11 +283,10 @@ export default wrap(async (req, res) => {
});
}
- const { accept, resource } = probeResult;
- const amountAtomics = BigInt(accept.amount);
+ const { accept, resource, amountAtomics } = probeResult;
const amountUsd = atomicsToUsd(amountAtomics);
- // Phase 2: governance enforcement — check session, allowlist, budget (atomic)
+ // Phase 2: governance enforcement (check session, allowlist, budget) is atomic
let sessionRecord, reservationId;
try {
const reservation = await reserveSessionSpend({
@@ -287,13 +312,22 @@ export default wrap(async (req, res) => {
keypair = loadSolanaKeypair();
} catch (err) {
await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});
- return error(res, 503, 'wallet_unconfigured', 'Platform Solana payment wallet is not configured');
+ // loadSolanaKeypair separates "no key configured" from "key present but
+ // undecodable". Collapsing both into wallet_unconfigured sent an operator
+ // looking for a missing env var that was in fact already set.
+ return error(
+ res,
+ err.status ?? 503,
+ err.code ?? 'wallet_unconfigured',
+ err.message || 'Platform Solana payment wallet is not configured',
+ );
}
payerAddress = keypair.publicKey.toBase58();
const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
try {
paymentPayload = await buildSolanaPayload({
accept,
+ amount: amountAtomics,
buyer: keypair,
conn,
resourceUrl: resource.url || targetUrl,
@@ -341,7 +375,7 @@ export default wrap(async (req, res) => {
const payer = settled?.payer || payerAddress;
const durationMs = Date.now() - t0;
- // Explicit pre-settlement rejection — no funds moved, safe to roll back
+ // Explicit pre-settlement rejection: no funds moved, safe to roll back
if (paid.status === 402) {
await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});
await recordExecution({
@@ -365,7 +399,7 @@ export default wrap(async (req, res) => {
typeof paidJson === 'object' ? paidJson : null);
}
- // Non-402 non-success — chain state uncertain
+ // Non-402 non-success: chain state uncertain
if (!paid.ok) {
await recordExecution({
sessionId: sessionRecord.id,
@@ -385,10 +419,10 @@ export default wrap(async (req, res) => {
idempotencyKey,
}).catch(() => {});
return error(res, 502, 'upstream_error',
- `Endpoint returned HTTP ${paid.status} after payment — check wallet activity before retrying.`);
+ `Endpoint returned HTTP ${paid.status} after payment. Check wallet activity before retrying.`);
}
- // Phase 5: success — record the settled execution
+ // Phase 5: success, record the settled execution
await recordExecution({
sessionId: sessionRecord.id,
userId: sessionRecord.user_id,
diff --git a/api/pay/session.js b/api/pay/session.js
index 2c0c1b387..f60555743 100644
--- a/api/pay/session.js
+++ b/api/pay/session.js
@@ -1,16 +1,16 @@
-// Agent Payment Session API — create, inspect, and cancel payment sessions.
+// Agent Payment Session API: create, inspect, and cancel payment sessions.
//
// A PaymentSession is a platform-managed spend envelope: developer funds a
// budget from their credits, receives a bearer token, and hands it to an agent.
-// The agent spends against the session budget by calling /api/pay/execute —
+// The agent spends against the session budget by calling /api/pay/execute, with
// no private key required. The platform's wallet signs the x402 transactions.
//
-// POST /api/pay/session — create a new session
-// GET /api/pay/session/:id — inspect a session (owner only)
-// PATCH /api/pay/session/:id — update label / allowlist / per-tx cap
-// DELETE /api/pay/session/:id — cancel + refund un-spent budget
-// GET /api/pay/session/:id/executions — list payments made in a session
-// GET /api/pay/session — list all sessions for the caller
+// POST /api/pay/session create a new session
+// GET /api/pay/session/:id inspect a session (owner only)
+// PATCH /api/pay/session/:id update label / allowlist / per-tx cap
+// DELETE /api/pay/session/:id cancel + refund un-spent budget
+// GET /api/pay/session/:id/executions list payments made in a session
+// GET /api/pay/session list all sessions for the caller
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
@@ -24,6 +24,7 @@ import {
listSessionExecutions,
getPaymentStats,
} from '../_lib/pay/payment-session.js';
+import { isSessionId } from '../_lib/pay/spend-governor.js';
async function resolveUser(req, res) {
const session = await getSessionUser(req, res);
@@ -41,6 +42,22 @@ function parsePath(req) {
return m ? { id: m[1], sub: m[2] ?? null } : { id: null, sub: null };
}
+/**
+ * Read `limit` and `cursor` off the query string, clamped to values the SQL can
+ * actually take. Both reach Postgres verbatim otherwise: a negative limit
+ * becomes `LIMIT -4` and a non-date cursor becomes a timestamptz cast error, and
+ * either one turns a caller's typo into a 500.
+ */
+function parsePagination(req) {
+ const url = new URL(req.url, 'http://x');
+ const rawLimit = Number(url.searchParams.get('limit'));
+ const limit = Number.isFinite(rawLimit) && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 100) : 20;
+
+ const rawCursor = url.searchParams.get('cursor');
+ const cursor = rawCursor && Number.isFinite(Date.parse(rawCursor)) ? rawCursor : null;
+ return { limit, cursor, cursorRejected: Boolean(rawCursor) && cursor === null };
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS', credentials: true })) return;
@@ -53,7 +70,7 @@ export default wrap(async (req, res) => {
const { id, sub } = parsePath(req);
const httpMethod = req.method?.toUpperCase();
- // POST /api/pay/session — create
+ // POST /api/pay/session: create
if (!id && httpMethod === 'POST') {
if (!method(req, res, ['POST'])) return;
const body = await readJson(req, res);
@@ -75,7 +92,7 @@ export default wrap(async (req, res) => {
} catch (err) {
if (err.code === 'insufficient_credits') {
return error(res, 402, 'insufficient_credits',
- `Insufficient credits — need $${err.required_usd?.toFixed(4)}, have $${err.available_usd?.toFixed(4)}`
+ `Insufficient credits: need $${err.required_usd?.toFixed(4)}, have $${err.available_usd?.toFixed(4)}`
);
}
if (err.status === 400 || err.code?.startsWith('invalid_')) {
@@ -91,12 +108,14 @@ export default wrap(async (req, res) => {
});
}
- // GET /api/pay/session — list all sessions
+ // GET /api/pay/session: list all sessions
if (!id && httpMethod === 'GET') {
const url = new URL(req.url, 'http://x');
const status = url.searchParams.get('status') || null;
- const limit = parseInt(url.searchParams.get('limit') || '20', 10);
- const cursor = url.searchParams.get('cursor') || null;
+ const { limit, cursor, cursorRejected } = parsePagination(req);
+ if (cursorRejected) {
+ return error(res, 400, 'invalid_cursor', 'cursor must be an ISO 8601 timestamp');
+ }
const [sessions, stats] = await Promise.all([
listPaymentSessions(user.id, { status, limit, cursor }),
@@ -106,16 +125,33 @@ export default wrap(async (req, res) => {
return json(res, 200, { ...sessions, stats });
}
- if (!id) return error(res, 400, 'bad_request', 'session id required');
+ // The collection route only answers POST (create) and GET (list). Anything
+ // else is a method problem, not a missing-id problem, so say which.
+ if (!id) {
+ return error(
+ res,
+ 405,
+ 'method_not_allowed',
+ `${httpMethod} on the session collection is not supported. Use POST to create or GET to list.`,
+ );
+ }
+
+ // Every id lands in a `uuid` column comparison, where Postgres answers a
+ // malformed value with a cast error rather than "no rows". Rejecting the
+ // shape here is what keeps /api/pay/session/not-a-uuid a 404 and not a 500.
+ if (!isSessionId(id)) {
+ return error(res, 404, 'not_found', 'session not found');
+ }
// GET /api/pay/session/:id/executions
if (sub === 'executions' && httpMethod === 'GET') {
const session = await getPaymentSession(id, user.id);
if (!session) return error(res, 404, 'not_found', 'session not found');
- const url = new URL(req.url, 'http://x');
- const limit = parseInt(url.searchParams.get('limit') || '20', 10);
- const cursor = url.searchParams.get('cursor') || null;
+ const { limit, cursor, cursorRejected } = parsePagination(req);
+ if (cursorRejected) {
+ return error(res, 400, 'invalid_cursor', 'cursor must be an ISO 8601 timestamp');
+ }
const result = await listSessionExecutions(id, user.id, { limit, cursor });
return json(res, 200, result);
}
@@ -127,7 +163,7 @@ export default wrap(async (req, res) => {
return json(res, 200, { session });
}
- // PATCH /api/pay/session/:id — update mutable fields on an active session
+ // PATCH /api/pay/session/:id: update mutable fields on an active session
if (httpMethod === 'PATCH') {
const body = await readJson(req, res);
if (!body) return;
diff --git a/api/pay/simulate.js b/api/pay/simulate.js
index b7fc125c4..a94f22c62 100644
--- a/api/pay/simulate.js
+++ b/api/pay/simulate.js
@@ -1,4 +1,4 @@
-// POST /api/pay/simulate — dry-run a payment session policy against real prices.
+// POST /api/pay/simulate: dry-run a payment session policy against real prices.
//
// The problem this solves: authorizing an agent budget is a guess. You pick
// $10 and a $0.50 per-transaction cap because those are round numbers, hand the
@@ -268,8 +268,25 @@ export function buildSteps(calls, priced, network) {
error_message: `No ${network} payment option (offered: ${offered.join(', ') || 'none'})`,
networks_offered: offered,
};
+ } else if (entry.rail.amount_atomics === null) {
+ // describeRail reports a null price rather than guessing zero when a
+ // challenge quotes something that is not an integer of atomic units.
+ // Coercing that to 0n here would put a "settles for free" row in the
+ // timeline for a call the executor refuses outright.
+ problems.push({
+ url: call.url,
+ code: 'unreadable_price',
+ message: `Endpoint charges on ${entry.rail.network ?? network} but quoted a price that could not be read`,
+ });
+ pricing = {
+ source: 'unpriced',
+ amount_usd: null,
+ network: entry.rail.network,
+ error: 'unreadable_price',
+ error_message: 'Endpoint quoted a price that is not a whole number of atomic units',
+ };
} else {
- amountAtomics = BigInt(entry.rail.amount_atomics ?? 0);
+ amountAtomics = BigInt(entry.rail.amount_atomics);
pricing = {
source: 'probed',
amount_usd: entry.rail.amount_usd,
diff --git a/api/pinning/[action].js b/api/pinning/[action].js
index 0b2ac43ab..bbb5e2af8 100644
--- a/api/pinning/[action].js
+++ b/api/pinning/[action].js
@@ -124,7 +124,19 @@ function ensurePinsTable() {
return pinsTableReady;
}
-/** Ask each configured provider whether it is holding this CID. */
+/**
+ * Ask each configured provider whether it is holding this CID.
+ *
+ * Every check reports one of three outcomes, and the third is the reason this
+ * does not just return a boolean. A provider that answers "I am not holding it"
+ * and a provider that never answered at all (expired token, rate limit, network
+ * fault) are different facts, and collapsing them into `pinned: false` reports a
+ * broken checker as a missing file. A rotated Pinata JWT made this concrete
+ * during the audit of this endpoint: every request 401'd upstream and the
+ * endpoint kept replying `pinned: false, provider: null`, with a 200.
+ *
+ * @returns {Promise<{holders: string[], failures: string[], answered: number}>}
+ */
async function checkProviders(cid) {
const pinataJwt = process.env.PINATA_JWT;
const w3sToken = process.env.WEB3_STORAGE_TOKEN;
@@ -137,12 +149,12 @@ async function checkProviders(cid) {
{ headers: { Authorization: `Bearer ${pinataJwt}` }, signal: AbortSignal.timeout(10000) },
)
.then(async (r) => {
- if (!r.ok) return null;
+ if (!r.ok) return { provider: 'pinata', failed: true };
const data = await r.json();
const pinned = (data.rows || []).some((row) => row.ipfs_pin_hash === cid);
- return pinned ? 'pinata' : null;
+ return { provider: 'pinata', held: pinned };
})
- .catch(() => null),
+ .catch(() => ({ provider: 'pinata', failed: true })),
);
}
@@ -153,15 +165,20 @@ async function checkProviders(cid) {
signal: AbortSignal.timeout(10000),
})
.then(async (r) => {
- if (!r.ok) return null;
+ if (!r.ok) return { provider: 'web3.storage', failed: true };
const data = await r.json();
- return data.cid === cid ? 'web3.storage' : null;
+ return { provider: 'web3.storage', held: data.cid === cid };
})
- .catch(() => null),
+ .catch(() => ({ provider: 'web3.storage', failed: true })),
);
}
- return (await Promise.all(checks)).filter(Boolean);
+ const results = await Promise.all(checks);
+ return {
+ holders: results.filter((r) => r.held).map((r) => r.provider),
+ failures: results.filter((r) => r.failed).map((r) => r.provider),
+ answered: results.filter((r) => !r.failed).length,
+ };
}
export default wrap(async (req, res) => {
@@ -297,12 +314,28 @@ export default wrap(async (req, res) => {
);
}
- const activeProviders = await checkProviders(cid);
+ const { holders, failures, answered } = await checkProviders(cid);
+
+ // No provider managed to answer: same rule as the unconfigured case above.
+ // Reporting `pinned: false` here would blame the document for a fault in
+ // the checker.
+ if (answered === 0) {
+ return error(
+ res,
+ 503,
+ 'pinning_check_failed',
+ `could not reach any pinning provider (${failures.join(', ')}); retry shortly`,
+ );
+ }
return json(res, 200, {
cid,
- pinned: activeProviders.length > 0,
- provider: activeProviders[0] || null,
+ pinned: holders.length > 0,
+ provider: holders[0] || null,
+ // A partial answer is still an answer, but the caller has to be able to
+ // see that one provider was never asked before treating `pinned: false`
+ // as proof the CID is gone.
+ unreachableProviders: failures,
gatewayUrls: gatewayUrlsFor(cid),
});
}
diff --git a/api/portfolio/[action].js b/api/portfolio/[action].js
index 5a4982e8b..cbc773d98 100644
--- a/api/portfolio/[action].js
+++ b/api/portfolio/[action].js
@@ -2,6 +2,7 @@
//
// GET /api/portfolio/summary?snapshot=1 → live aggregated balances; opt. snapshot
// GET /api/portfolio/history?days=30 → past snapshots for the chart
+// GET /api/portfolio/asset?chain&id&days → one token across every agent wallet
// POST /api/portfolio/send → server-signed transfer from an agent wallet
//
// All endpoints require a session cookie and operate only on agents owned by
@@ -21,6 +22,10 @@ import { getBalances, walletUsdTotal, invalidateBalances } from '../_lib/balance
import { recoverAgentKey, recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
import { reverseLookupAddress, resolveSolanaRecipient } from '../../src/solana/sns.js';
import { geckoFetch, htmlToText } from '../_lib/coingecko.js';
+import { fetchTokenMarketData } from '../_lib/market/token-market.js';
+import { fetchCoinPriceUsdOrNull } from '../_lib/market-fallbacks.js';
+import { solPriceUsd, solChange24hPct } from '../_lib/sol-price.js';
+import { fetchFirstOrNull } from '../../src/shared/failover-fetch.js';
import { env } from '../_lib/env.js';
import { z } from 'zod';
@@ -497,6 +502,69 @@ async function loadMarket({ metaPath, chartPath, coingeckoId, days }) {
};
}
+// Every field /asset publishes under `market`, so a fallback source that only
+// carries a price still produces the same object shape for the page.
+const EMPTY_MARKET = {
+ name: null,
+ price_usd: null,
+ change_24h_pct: null,
+ change_7d_pct: null,
+ change_30d_pct: null,
+ market_cap_usd: null,
+ total_volume_usd: null,
+ high_24h_usd: null,
+ low_24h_usd: null,
+ ath_usd: null,
+ ath_change_pct: null,
+ description: '',
+ homepage: null,
+ coingecko_id: null,
+};
+
+// CoinGecko is the only source with the full descriptive block, and it is also
+// the first to throttle: its keyless tier 429s a shared datacenter egress IP
+// within minutes, which left this page with `market: null` and a $0 valuation
+// for holdings the user really has. Fall back to the price lanes the platform
+// already runs, Solana first: the mint cascade (Birdeye, DexScreener,
+// GeckoTerminal, DefiLlama, Raydium), the SOL spot lane, the coingecko-id spot
+// lane for ETH, and DefiLlama's contract oracle for an ERC-20. These carry
+// price and (where available) 24h change, cap and volume; the descriptive
+// fields stay null and the page already degrades on those.
+async function fallbackMarket({ chain, id, isNative }) {
+ if (chain === 'solana') {
+ if (isNative) {
+ const [price, change] = await Promise.all([solPriceUsd(), solChange24hPct()]);
+ return price > 0 ? { name: 'Solana', price_usd: price, change_24h_pct: change } : null;
+ }
+ const md = await fetchTokenMarketData(id);
+ if (!md?.price_usd) return null;
+ return {
+ price_usd: md.price_usd,
+ change_24h_pct: md.price_change_24h ?? null,
+ market_cap_usd: md.market_cap ?? null,
+ total_volume_usd: md.volume_24h ?? null,
+ };
+ }
+ if (isNative) {
+ const price = await fetchCoinPriceUsdOrNull('ethereum');
+ return price > 0 ? { name: 'Ethereum', price_usd: price } : null;
+ }
+ const price = await fetchFirstOrNull(
+ [
+ {
+ name: 'llama-contract',
+ url: `https://coins.llama.fi/prices/current/ethereum:${id}`,
+ parse: async (r) => {
+ const p = Number((await r.json())?.coins?.[`ethereum:${id}`]?.price);
+ return Number.isFinite(p) && p > 0 ? p : null;
+ },
+ },
+ ],
+ { timeoutMs: 6000, label: `evm-token-price:${id.slice(0, 10)}` },
+ );
+ return price > 0 ? { price_usd: price } : null;
+}
+
async function handleAsset(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
@@ -591,7 +659,7 @@ async function handleAsset(req, res) {
// For tokens: use /coins/{platform}/contract/{address}.
const platform = chain === 'solana' ? 'solana' : 'ethereum';
const base = isNative ? `/coins/${platform}` : `/coins/${platform}/contract/${encodeURIComponent(id)}`;
- const { market, symbol: cgSymbol, logo: cgLogo, points: chartPoints } = await loadMarket({
+ let { market, symbol: cgSymbol, logo: cgLogo, points: chartPoints } = await loadMarket({
metaPath: isNative
? `${base}?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false`
: base,
@@ -602,7 +670,16 @@ async function handleAsset(req, res) {
symbol = cgSymbol || symbol;
logo = logo || cgLogo;
- // If CoinGecko gave us a more reliable spot price, use it for the holding
+ if (!market?.price_usd) {
+ try {
+ const fb = await fallbackMarket({ chain, id, isNative });
+ if (fb) market = { ...EMPTY_MARKET, ...(market || {}), ...fb };
+ } catch (e) {
+ console.error('[portfolio/asset] price fallback failed', e?.message);
+ }
+ }
+
+ // If the market lane gave us a more reliable spot price, use it for the holding
// USD calculation as well so the page is internally consistent.
if (market?.price_usd && totalAmount > 0) {
totalUsd = totalAmount * market.price_usd;
@@ -614,7 +691,11 @@ async function handleAsset(req, res) {
chain,
id,
is_native: isNative,
- symbol: symbol || (chain === 'solana' ? 'SOL' : 'ETH'),
+ // Only a native asset may fall back to the chain's coin symbol. An unknown
+ // mint or contract used to answer "SOL"/"ETH" here, so the page labelled a
+ // token nobody could price as the chain's native coin. Unlabelled tokens
+ // get a short address instead, which every consumer can render as-is.
+ symbol: symbol || (isNative ? (chain === 'solana' ? 'SOL' : 'ETH') : `${id.slice(0, 4)}..${id.slice(-4)}`),
logo,
decimals,
unit_price_usd: unitPrice,
diff --git a/api/pump/helius-stats.js b/api/pump/helius-stats.js
index e0776360f..e12d4076c 100644
--- a/api/pump/helius-stats.js
+++ b/api/pump/helius-stats.js
@@ -23,6 +23,12 @@ import { solPriceUsd, solPriceInfo, solChange24hPct } from '../_lib/sol-price.js
let _heliusCache = { value: null, at: 0 };
+// Drops the 4s probe cache. Exported for tests, which would otherwise read one
+// case's cached probe result as the next case's answer.
+export function _resetHeliusCache() {
+ _heliusCache = { value: null, at: 0 };
+}
+
const isHeliusUrl = (u) => u.includes('helius-rpc.com') || u.includes('helius.dev');
// Which RPC this panel should actually probe, and what to honestly call it.
@@ -58,6 +64,17 @@ async function getHeliusInfo() {
}),
});
clearTimeout(tid);
+ // A rejected key answers with a plain-text body ("Unauthorized"), which
+ // makes r.json() throw and would otherwise be filed as "unreachable". The
+ // status is the actionable part: rotate the key, don't chase the network.
+ if (!r.ok) {
+ value = {
+ enabled: true, slot: null, network: 'mainnet', endpoint,
+ error: `http_${r.status}`,
+ };
+ _heliusCache = { value, at: Date.now() };
+ return value;
+ }
const d = await r.json();
const slot = Number.isFinite(Number(d?.result)) ? Number(d.result) : null;
// A JSON-RPC error body is a 200 at the HTTP layer. Reporting it as a bare
diff --git a/api/pump/price-history.js b/api/pump/price-history.js
index 188023ea0..05eb23cc2 100644
--- a/api/pump/price-history.js
+++ b/api/pump/price-history.js
@@ -326,7 +326,7 @@ export default wrap(async (req, res) => {
const params = new URL(req.url, 'http://x').searchParams;
const mint = (params.get('mint') || '').trim();
if (!isPlausibleMint(mint)) {
- return error(res, 400, 'bad_mint', 'mint must be a base58 Solana address (32–44 chars)');
+ return error(res, 400, 'bad_mint', 'mint must be a base58 Solana address (32 to 44 chars)');
}
const interval = normalizeInterval(params.get('interval'));
diff --git a/data/changelog.json b/data/changelog.json
index f8172fec4..e0ccc6e0b 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,64 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-08-14",
+ "title": "Sharing a build now checks that the coin world you are sharing to is real",
+ "summary": "When you screenshot a voxel build in a coin's /play world and share it, the build is filed under that coin's address. The endpoint only checked that the address was the right length, not that it was an address at all, so anything between 32 and 64 characters was accepted and filed away under its own storage slot. It now checks the format the way every other coin-world surface does: a Solana mint or an EVM contract address gets through, anything else is turned away before it reaches storage. Real worlds are unaffected, on both Solana and the EVM chains. The live event board picked up its own test coverage in the same pass, including a check that a player's account key never appears in what the board sends to the browser.",
+ "tags": [
+ "security",
+ "fix"
+ ],
+ "link": "/play"
+ },
+ {
+ "date": "2026-08-14",
+ "title": "The internal money and platform health boards tell the truth again",
+ "summary": "Three internal dashboards watch the platform for us: one for site and cron health, one for every money subsystem, one for payment outcomes. Two of them had gone quietly wrong. The platform board judged each scheduled job against a hand-written idea of how often it should run, and three jobs that run once a day were being judged against a window of minutes, so they reported as broken for roughly 23 hours out of every day and the board could never come back all-clear; every job is now measured against the schedule it genuinely runs on. One of its probes was also posting to a payments endpoint without declaring it was sending JSON, so it had been failing on its own mistake rather than on anything real. The money board was reading the wrong timestamp column on two payment logs and showing no activity at all for a payment ring that settles thousands of payments a day. It also accepted the credential our fund-moving scheduled jobs carry as an ops password; it now takes the same admin sign-in as the other boards, so an ops credential can never be escalated into triggering a payment job.",
+ "tags": [
+ "fix",
+ "infra",
+ "security"
+ ]
+ },
+ {
+ "date": "2026-08-14",
+ "title": "Buying USDC or SOL from Add funds again opens a checkout with your wallet already filled in",
+ "summary": "The Add funds overlay builds a Coinbase checkout link for your three.ws wallet. It was still building that link the old way, passing the destination wallet in the URL, which Coinbase stopped accepting when it moved to server-minted session tokens. The link is now minted through Coinbase's current onramp API: one single-use token per click, bound to your Solana address and the asset you picked, so the checkout opens with the destination, the asset, and your chosen amount already set instead of dropping you on a generic buy page. If Coinbase is unreachable, funding does not break: you still get a working buy page and the address to send to, exactly as before. The endpoint is also rate limited now, so nobody can drive our Coinbase quota by hammering it.",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-08-14",
+ "title": "Chinese headlines no longer show up in the English crypto news feed",
+ "summary": "BlockTempo, a Taiwanese crypto publisher that writes in Traditional Chinese, was listed in our news source registry without a language tag. Untagged sources are treated as English, so its headlines were being mixed into the default feed on /markets/news, the markets hub strip, and the RSS mirror, where they read as noise to anyone browsing in English. It is now tagged Chinese: the English feed is English only, and BlockTempo shows up when you pick Chinese from the language selector, alongside PANews. Nothing else about the feed changed.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/markets/news"
+ },
+ {
+ "date": "2026-08-14",
+ "title": "Plugin marketplace: no more duplicate listings, and private plugins stay private",
+ "summary": "The plugin grid listed every built-in plugin twice (two Calculators, two Weathers, and so on) because the platform's seed rows were inserted a second time without the duplicate check ever catching them. There are now seven built-ins again, one of each, and the database refuses a duplicate outright. Three plugin API fixes ship with it: a plugin published as private was readable in full by anyone who knew its link, and its install counter could be driven by anyone; recording an install now reports the real new total instead of always answering \"ok\", and counts one install per person per plugin rather than one per click; and asking for a page of plugins with a malformed cursor now returns a plain validation error rather than a server error.",
+ "tags": [
+ "fix",
+ "security"
+ ],
+ "link": "/marketplace"
+ },
+ {
+ "date": "2026-08-14",
+ "title": "The $THREE holder count is back on the token page and its share card",
+ "summary": "The holder count on the /three-token page, and on the badge image that previews wherever a $THREE link is shared, had been showing a dash instead of a number. Our own holder snapshot is rebuilt from a Solana indexer that has been refusing the scan, and once the snapshot went stale the page correctly declined to show an out-of-date figure, so the count simply disappeared rather than being briefly missing. Holder count now falls back to a second, independent source when our snapshot cannot refresh, so the figure stays real and current through an indexer outage. The share card was also reading a narrower set of sources than the page it mirrors, which is why the two could disagree; both now read the same ones. Separately, a shared agent link unfurls noticeably faster: the card was fetching the agent's portrait only after every other lookup had finished, and now fetches it alongside them.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/three-token"
+ },
{
"date": "2026-08-14",
"title": "Apps that sign in with a client secret can now revoke and inspect their own tokens",
diff --git a/docs/api-reference.md b/docs/api-reference.md
index d4257cf18..70b7ffa2c 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -3677,6 +3677,181 @@ The budget is deliberately *not* restored on `settle_uncertain`. Releasing it wo
---
+## Monetization API
+
+```
+GET /api/monetization/prices?agent_id=… List an agent's priced and gated skills (public)
+PUT /api/monetization/prices Set or update the price/gate for one skill
+DELETE /api/monetization/prices Deactivate (or hard-delete) a skill's price
+GET /api/monetization/revenue Aggregated earnings for your agents
+GET /api/monetization/wallet Read the payout addresses on file
+PUT /api/monetization/wallet Save a Solana and/or EVM payout address
+GET /api/monetization/withdrawals Withdrawal history plus the live balance
+POST /api/monetization/withdrawals Reserve a withdrawal of the available balance
+```
+
+The seller side of the agent economy: you price a skill, buyers pay for it through the [x402 endpoints](#x402-paid-endpoints--sign-in-with-x-siwx), the platform books a revenue event with its fee split, and you withdraw the net to an address you registered in advance.
+
+All amounts on the wire are USDC. Every response carries both a human `*_usdc` float and an `*_atomic` integer (6 decimals, so `1 USDC = 1000000`); use the atomic value for anything that has to add up.
+
+**Auth.** Everything except the public price listing needs a session cookie or an API key bearer token. Writes made with a cookie also need a CSRF token (`GET /api/csrf-token`, then send it as `x-csrf-token`); bearer-token callers are exempt, because the token itself proves intent.
+
+### GET /api/monetization/prices
+
+Public and unauthenticated: this is how a buyer discovers what an agent charges. `agent_id` is required and must be a UUID.
+
+```bash
+curl "https://three.ws/api/monetization/prices?agent_id=$AGENT_ID"
+```
+
+**200 OK**
+
+```json
+{
+ "prices": [
+ {
+ "id": "9c1f…",
+ "skill_name": "summarize",
+ "price_usdc": 0.05,
+ "amount_atomic": 50000,
+ "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
+ "chain": "solana",
+ "is_active": true,
+ "gate_type": "price",
+ "nft_collection_mint": null,
+ "created_at": "2026-08-01T10:00:00.000Z",
+ "updated_at": "2026-08-01T10:00:00.000Z"
+ }
+ ]
+}
+```
+
+Only active entries are listed. An unknown `agent_id` is a `404 not_found`, not an empty list.
+
+### PUT /api/monetization/prices
+
+Owner only. Creates the entry (`201`) or updates it in place (`200`), keyed on `(agent_id, skill_name)`.
+
+| Field | Type | Default | Notes |
+| --------------------- | ------- | --------------- | ---------------------------------------------------------------------------- |
+| `agent_id` | string | required | UUID of an agent you own. |
+| `skill_name` | string | required | Up to 64 chars, alphanumeric plus `-` and `_`. |
+| `price_usdc` | number | required | Required for a price gate. 0.000001 to 1000000. Rounded to atomic units. |
+| `currency_mint` | string | Solana USDC | Mint the price is denominated in. |
+| `chain` | string | `"solana"` | `solana`, `base`, or `evm`. |
+| `gate_type` | string | `"price"` | `price` sells the skill; `nft` restricts it to holders of a collection. |
+| `nft_collection_mint` | string | `null` | Required when `gate_type` is `nft`. Base58 Solana address. |
+
+```bash
+curl -X PUT https://three.ws/api/monetization/prices \
+ -H "Authorization: Bearer $THREE_WS_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"agent_id":"'$AGENT_ID'","skill_name":"summarize","price_usdc":0.05}'
+```
+
+An NFT gate stores a zero amount: access is the holding, not a payment. A `price_usdc` below `0.000001` rounds to zero atomic units and is refused, and one above `1000000` is refused rather than overflowing the ledger column.
+
+### DELETE /api/monetization/prices
+
+Owner only. Body: `{ agent_id, skill_name, hard? }`. The default is a soft delete (the row is deactivated and disappears from the public listing, and re-pricing the skill later revives it). `hard: true` removes the row outright. Either way, a skill with no price row is a `404 not_found`.
+
+### GET /api/monetization/revenue
+
+Aggregated earnings across every agent you own, or one agent with `?agent_id=`.
+
+`period` is one of `1d`, `7d`, `30d`, `90d`, `all` and defaults to `7d`. Anything else is a `400`.
+
+```bash
+curl "https://three.ws/api/monetization/revenue?period=30d" \
+ -H "Authorization: Bearer $THREE_WS_API_KEY"
+```
+
+**200 OK**
+
+```json
+{
+ "total_usdc": 6,
+ "total_fees_usdc": 0.15,
+ "net_usdc": 5.85,
+ "event_count": 3,
+ "total_atomic": 6000000,
+ "fees_atomic": 150000,
+ "net_atomic": 5850000,
+ "by_skill": [{ "skill": "summarize", "total": 2.925, "total_atomic": 2925000, "count": 1 }],
+ "by_day": [{ "date": "2026-08-01", "total": 5.85, "total_atomic": 5850000, "count": 3 }]
+}
+```
+
+`total` is gross, `net` is what you can withdraw, and the difference is the platform fee. Scoping to an agent you do not own is a `403`.
+
+### GET /api/monetization/wallet
+
+Returns every payout row on file plus a `resolved` summary of the address a payout would actually land on per chain. The resolution matches what a withdrawal does: an agent-specific row wins, and a user-level row (saved with no agent) is the fallback.
+
+```json
+{
+ "wallets": [{ "id": "…", "agent_id": "…", "address": "FeMb…", "chain": "solana", "is_default": true, "preferred_network": "solana", "created_at": "…" }],
+ "resolved": { "evm_address": null, "solana_address": "FeMb…", "preferred_network": "solana" }
+}
+```
+
+### PUT /api/monetization/wallet
+
+Body: `{ agent_id, solana_address?, evm_address?, preferred_network? }`. At least one address is required. Addresses are validated (base58 for Solana, `0x` + 40 hex for EVM) and upserted per `(user, agent, chain)`, so re-saving replaces rather than duplicates. `preferred_network` (`solana` by default) decides which rail a withdrawal draws on when you do not name one.
+
+### GET /api/monetization/withdrawals
+
+History plus the live balance. Optional `agent_id`, `status` (`pending`, `processing`, `completed`, `failed`), `limit` (1 to 100, default 20) and `offset`. An unrecognised `status` is a `400` rather than a silently empty page.
+
+```json
+{
+ "withdrawals": [
+ {
+ "id": "…", "agent_id": "…", "amount_usdc": 4, "amount_atomic": 4000000,
+ "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
+ "chain": "solana", "destination_address": "FeMb…", "status": "pending",
+ "tx_hash": null, "error": null,
+ "requested_at": "2026-08-01T10:00:00.000Z", "processed_at": null
+ }
+ ],
+ "balance": { "earned_usdc": 5.85, "withdrawn_usdc": 0, "pending_usdc": 4, "available_usdc": 1.85 }
+}
+```
+
+`available = earned - pending - withdrawn`, so a reservation that has not settled yet is already deducted.
+
+### POST /api/monetization/withdrawals
+
+Reserves a withdrawal against the available balance. The destination is never accepted from the client: it is resolved from the payout wallets you saved, so a caller can only ever withdraw to an address they registered.
+
+| Field | Type | Default | Notes |
+| ------------- | ------ | ---------- | ------------------------------------------------------------------ |
+| `agent_id` | string | required | UUID of an agent you own. |
+| `amount_usdc` | number | whole balance | Minimum 1 USDC. Omit or send `null` to drain what is available. |
+| `network` | string | preference | `solana` (the default rail), `base`, or `evm`. |
+
+```bash
+curl -X POST https://three.ws/api/monetization/withdrawals \
+ -H "Authorization: Bearer $THREE_WS_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"agent_id":"'$AGENT_ID'","amount_usdc":4}'
+```
+
+**201 Created** returns the reserved row with `status: "pending"` and the updated balance. `/api/cron/process-withdrawals` picks it up, sends the transfer, and moves it to `processing` then `completed` (or `failed`, with `error` set).
+
+| Status | Error | Meaning |
+| ------ | ---------------------- | --------------------------------------------------------------------------- |
+| 422 | `no_payout_wallet` | No payout address saved for the chain being drawn on. |
+| 422 | `below_minimum` | Under the 1 USDC floor. |
+| 422 | `insufficient_balance` | More than `available`, or a concurrent request reserved it first. |
+| 429 | `rate_limited` | Withdrawal requests are capped at 5 per user per day, refusals included. |
+
+Naming a `network` you have no wallet on is refused rather than quietly paid out on another chain. Without one, the saved `preferred_network` decides, falling back to Solana.
+
+The reservation is serialized behind a per-(user, currency) advisory lock and re-derives the balance inside the transaction, so concurrent requests cannot both pass the balance check and over-withdraw.
+
+---
+
## Coin Market Data API
Public, unauthenticated, CORS-open proxies over CoinGecko (plus a news
@@ -4993,6 +5168,192 @@ The same stamp is served statically at `/build-info.json`.
---
+## Platform Stats API
+
+```
+GET /api/platform/stats
+```
+
+Aggregate, public-safe traction counters for the marketing home page, the
+[monitor board](/monitor), and any unauthenticated surface that wants to show
+real numbers. No auth, CORS open to any origin, every figure a count that
+exposes no individual user. Cached 5 minutes at the CDN and 5 minutes in the
+process, so a burst of home page hits costs one set of queries.
+
+**Response**
+
+```json
+{
+ "available": true,
+ "agents": 3140,
+ "views": 593,
+ "chats": 29,
+ "avatars": 25835,
+ "countries": 29,
+ "widgets": 613,
+ "chains": 12,
+ "generated": "2026-08-14T02:16:27.780Z"
+}
+```
+
+| Field | Meaning |
+|---|---|
+| `agents` | Live agent identities |
+| `views` | All-time widget views |
+| `chats` | All-time widget chat threads |
+| `avatars` | Avatars (GLBs) in the library |
+| `countries` | Distinct countries a widget view came from |
+| `widgets` | Live widgets |
+| `chains` | Mainnets carrying an indexed ERC-8004 agent, plus Solana |
+
+`chains` is derived, never a constant: it counts the distinct chain ids in the
+ERC-8004 index that the registry in `api/_lib/erc8004-chains.js` marks as
+mainnet, and adds Solana when Solana carries at least one attestation. Testnet
+ids (Sepolia, Base Sepolia, Amoy, Fuji) are excluded, which is why this reads
+lower than the raw distinct-chain count in `/api/home-stats`.
+
+**When the database is unreachable**
+
+```json
+{ "available": false, "reason": "db_unavailable" }
+```
+
+Still `200`, but cached for 15 seconds only. Check `available` before reading
+any counter: this endpoint never substitutes a zero for a number it could not
+count, so a failed read must not be rendered as "0 agents".
+
+```bash
+curl -s https://three.ws/api/platform/stats | jq 'select(.available) | {agents, avatars, chains}'
+```
+
+The sibling `/api/home-stats` uses the same `available` contract for the home
+page strip (on-chain agents, attestations, forge models).
+
+---
+
+## Referrals API
+
+Every three.ws account carries a referral code. A share link is any page URL
+with `?ref=CODE` on it. Two endpoints cover the loop: a public beacon that
+records the visit, and an authenticated read that returns the sharer's card,
+their referred users, and the funnel those visits roll up into.
+
+### Record a referral-link visit
+
+```
+POST /api/referral/visit
+```
+
+Public and unauthenticated by design: the visitor has no account yet. This is
+the top of the referral funnel, and without it only signups are visible, so the
+visit to signup conversion is unknowable.
+
+`public/referral-capture.js` fires this automatically on the auth pages when a
+`?ref=` parameter is present, so a normal three.ws share link needs no extra
+wiring. Call it directly only if you are hosting your own landing page for a
+three.ws referral link.
+
+**Request body**
+
+| Field | Type | Description |
+| ------ | ------ | ------------------------------------------------------------ |
+| `code` | string | Required. The referral code, 3-20 characters of `A-Z0-9`. Matched case-insensitively. |
+
+**Response**
+
+```json
+{ "ok": true }
+```
+
+```bash
+curl -s -X POST https://three.ws/api/referral/visit \
+ -H 'content-type: application/json' \
+ -d '{"code":"ADA99"}'
+```
+
+Privacy and counting rules, both deliberate:
+
+- No raw IP or user agent is stored. The visitor is identified only by
+ `sha256(ip + user-agent + code)`.
+- A visitor counts once per code per UTC day. A refresh or a replay returns
+ `200 {"ok": true}` and writes nothing, so the funnel cannot be inflated by
+ reloading a link.
+- An unknown code still records a visit with no referrer attached, so traffic on
+ a dead or mistyped link stays visible instead of vanishing.
+
+A malformed or missing code returns `400 invalid_code`. The endpoint is rate
+limited per IP; over the limit returns `429` with a `retry-after` header.
+
+---
+
+### Get my referral card, referrals, and funnel
+
+```
+GET /api/users/referrals
+```
+
+Requires a session cookie or a bearer token. Returns the signed-in user's
+membership card, a paginated breakdown of who they referred and what those
+referrals earned them, and the share funnel built from the visit beacons above.
+
+**Query parameters**
+
+| Parameter | Type | Description |
+| ------------- | ------- | ------------------------------------------------------------------ |
+| `limit` | integer | Referred-user page size, 1-100 (default: 20) |
+| `offset` | integer | Referred-user page offset, >= 0 (default: 0) |
+| `funnel_days` | integer | Funnel lookback in days, 1-365 (default: 30) |
+
+**Response**
+
+```json
+{
+ "referral_code": "ADA99",
+ "referred_users_count": 12,
+ "referral_earnings_usd": 41.5,
+ "reward_credits_usd": 6,
+ "position": 1204,
+ "total_members": 27745,
+ "score": 161,
+ "referred_users": {
+ "items": [],
+ "total": 12,
+ "limit": 20,
+ "offset": 0,
+ "referral_commission_bps": 500
+ },
+ "funnel": {
+ "days": 30,
+ "visits": 200,
+ "signups": 50,
+ "activations": 20,
+ "visit_to_signup_pct": 25,
+ "signup_to_activation_pct": 40
+ }
+}
+```
+
+| Funnel field | Meaning |
+|---|---|
+| `visits` | Deduped link visits recorded in the window |
+| `signups` | Accounts attributed to this referrer, created in the window |
+| `activations` | Referred users who reached their first creation in the window |
+| `visit_to_signup_pct` | `signups / visits`, one decimal |
+| `signup_to_activation_pct` | `activations / signups`, one decimal |
+
+Both percentages are `null`, never `0`, when the stage above them is empty, so a
+brand-new sharer reads as "no data yet" rather than "0% conversion". Amounts
+ending in `_usd` are dollars; the matching `_total` fields are atomic USDC units
+(6 decimals).
+
+```bash
+curl -s -b cookies.txt 'https://three.ws/api/users/referrals?funnel_days=7' | jq .funnel
+```
+
+`/dashboard/referrals` renders exactly this payload.
+
+---
+
## Solana Actions API (Blinks)
three.ws publishes a Solana Action so "Claim Your 3D Avatar" unfurls as a Blink
@@ -5207,6 +5568,168 @@ Clients should treat `404` as terminal and stop polling.
---
+## Plugin Marketplace API
+
+Tool plugins in the LobeHub / pai-chat `ToolManifest` format: the catalog behind
+the plugin grid on [/marketplace](/marketplace) and the picker on
+[/avatar](/avatar). A manifest declares an `identifier`, a `meta.title`, and a
+non-empty `api[]` of tool definitions; the platform stores it verbatim and
+re-serves it, so a client that understands the format can install straight from
+a listing.
+
+All five routes live in `api/plugins/[action].js`.
+
+### List plugins
+
+```
+GET /api/plugins
+GET /api/plugins/list?category=&q=&sort=&cursor=&limit=
+```
+
+Public, unauthenticated. Both paths are the same handler; the bare collection
+path is the canonical one.
+
+| Parameter | Default | Meaning |
+|---|---|---|
+| `category` | all | Exact category slug, as returned by `/api/plugins/categories` |
+| `q` | none | Case-insensitive substring match on name or description (first 80 chars used) |
+| `sort` | `popular` | `popular` (install count), `new` (newest first), or `az` (name). An unknown value falls back to `popular`. |
+| `limit` | `20` | 1 to 40 |
+| `cursor` | `0` | Opaque offset. Pass back the `next_cursor` from the previous page verbatim. |
+
+`cursor` must be a non-negative integer; anything else is a `400`
+(`validation_error`), never a 500. `next_cursor` is `null` on the last page.
+
+```bash
+curl -s 'https://three.ws/api/plugins/list?sort=az&limit=2' | jq '.data.items[].identifier'
+```
+
+```json
+{
+ "data": {
+ "items": [
+ {
+ "id": "764f3eb7-7691-485e-b147-53080bd9f5f9",
+ "identifier": "web-search",
+ "manifest_url": null,
+ "manifest_json": { "identifier": "web-search", "meta": {}, "api": [] },
+ "name": "Web Search",
+ "description": "Search the web for up-to-date information.",
+ "category": "web-search",
+ "tags": ["search", "web", "utility"],
+ "install_count": 0,
+ "avg_rating": 0,
+ "author": null,
+ "created_at": "2026-05-02T07:43:09.276Z",
+ "price": null
+ }
+ ],
+ "next_cursor": "20"
+ }
+}
+```
+
+`author` is `null` for the platform's built-in plugins. `price` is `null` unless
+the plugin carries an active row in `asset_prices`.
+
+### Categories
+
+```
+GET /api/plugins/categories
+```
+
+Every category that has at least one public plugin, with its count, ordered by
+count. Cached 60 seconds. `{"data":{"categories":[{"slug":"tools","count":4}]}}`.
+
+### Get a plugin
+
+```
+GET /api/plugins/:id
+```
+
+`:id` is the plugin UUID. A plugin published with `is_public: false` is visible
+only to its author (session cookie or bearer token); to everyone else it is a
+`404`, the same answer as an id that does not exist.
+
+### Record an install
+
+```
+POST /api/plugins/:id/install
+```
+
+Increments the public install counter. No auth: the marketplace fires it when a
+visitor installs a plugin into their own client.
+
+```json
+{ "data": { "ok": true, "counted": true, "install_count": 4 } }
+```
+
+Deduplicated to one counted install per (IP, plugin) per 30 minutes. A repeat
+inside that window is still a `200`, with `counted: false` and the unchanged
+total, so a client never has to special-case it. An unknown or non-visible
+plugin is a `404`.
+
+### Import a manifest by URL
+
+```
+POST /api/plugins/import
+```
+
+```json
+{ "manifest_url": "https://example.com/plugin.json" }
+```
+
+Fetches the URL server-side (so the browser is not blocked by the host's CORS
+policy), validates it as a manifest, and returns it with a `_manifest_url` field
+added. It writes nothing: the caller decides whether to install locally or
+publish. 20 requests per 5 minutes per IP.
+
+The fetch is SSRF-guarded. The host and every redirect hop is DNS-resolved and
+checked before the socket opens, and private, loopback, link-local, and cloud
+metadata ranges are refused (`400`, `validation_error`). The transfer is capped
+at 64 KB and aborted mid-stream if the host exceeds it (`422`, `fetch_failed`).
+
+**Errors:** `400` (missing / unparseable / non-http `manifest_url`, blocked
+host), `422` (`fetch_failed` for a non-2xx, unparseable, or oversized response;
+`invalid_manifest` when the JSON is not a manifest), `429`.
+
+### Publish a plugin
+
+```
+POST /api/plugins/publish
+```
+
+Requires authentication (session cookie or bearer token) and, for a cookie
+session, an `X-CSRF-Token` header from `GET /api/csrf-token`. 30 per hour per
+user.
+
+```json
+{
+ "manifest_json": {
+ "identifier": "my-plugin",
+ "meta": { "title": "My Plugin", "description": "Does a thing.", "category": "tools" },
+ "api": [{ "name": "do_thing", "description": "Does the thing" }]
+ },
+ "manifest_url": "https://example.com/plugin.json",
+ "is_public": true
+}
+```
+
+An upsert on `(identifier, author_id)`, so re-publishing the same identifier
+updates your existing row rather than creating a second one. `is_public: false`
+keeps the plugin out of the list and the category counts and restricts detail
+reads to you. Responds with the same plugin shape the list returns.
+
+**Manifest rules:** `identifier` is required, alphanumeric plus `.`, `-`, `_`,
+and at most 128 characters; `meta.title` is required; `api` must be a non-empty
+array of at most 100 tools, each with a `name` and a `description`. A violation
+is a `422` (`invalid_manifest`) naming the specific rule.
+
+**Errors:** `401` (no auth), `403` (`csrf_missing` / `csrf_invalid`), `400`
+(malformed body), `422` (`invalid_manifest`), `429`.
+
+---
+
## Pagination
Paginated list endpoints use `limit`/`offset` query parameters unless noted otherwise (each endpoint's own parameter table is authoritative; some small per-user lists, like `/api/agents` and `/api/widgets`, return everything with no pagination).
diff --git a/docs/authentication.md b/docs/authentication.md
index d60364ea8..ba84a9f8c 100644
--- a/docs/authentication.md
+++ b/docs/authentication.md
@@ -517,6 +517,27 @@ If you're building a third-party app that users authorize to access their three.
PKCE (S256) is mandatory. The authorization server metadata is at `/.well-known/oauth-authorization-server`.
+### Client authentication
+
+Public clients (`token_endpoint_auth_method: "none"`, the default from dynamic registration) get no secret and identify themselves with a `client_id` form field.
+
+Confidential clients present their secret the same way at `/api/oauth/token`, `/api/oauth/revoke`, and `/api/oauth/introspect`, using whichever method they registered:
+
+```bash
+# client_secret_basic: credentials in the Authorization header, nothing in the form
+curl -X POST https://three.ws/api/oauth/revoke \
+ -u "$CLIENT_ID:$CLIENT_SECRET" \
+ -d "token=$REFRESH_TOKEN"
+
+# client_secret_post: credentials in the form body
+curl -X POST https://three.ws/api/oauth/revoke \
+ -d "client_id=$CLIENT_ID" \
+ -d "client_secret=$CLIENT_SECRET" \
+ -d "token=$REFRESH_TOKEN"
+```
+
+Registration returns `client_secret_expires_at: 0` alongside an issued secret: three.ws secrets do not expire, so rotate one by registering a new client.
+
For most use cases, API keys are simpler. OAuth is the right choice when you're building a product where your users grant your app access to their three.ws data.
---
diff --git a/docs/marketplace.md b/docs/marketplace.md
index 94c37e1a4..ad37956c6 100644
--- a/docs/marketplace.md
+++ b/docs/marketplace.md
@@ -70,6 +70,40 @@ Both skill and asset purchases follow the same three-step pattern:
Pending rows carry an `expires_at`; an unpaid reference simply expires and a fresh
one is issued on the next prepare.
+### Paying from a phone: the transaction request
+
+Step 2 has two rails, and both settle the same pending row through the same
+`reference`, so step 3 is unchanged either way.
+
+- **Transfer request** (`solana:<recipient>?amount=…&spl-token=…&reference=…`) is
+ the plain deep link. The scanning wallet builds the transfer itself, which means
+ the buyer needs SOL for the network fee and the seller's token account must
+ already exist.
+- **Transaction request** ([`api/purchase/skill.js`](../api/purchase/skill.js)) is
+ the sponsored rail the QR encodes by default. The wallet fetches the transfer
+ from us instead of composing it:
+
+ ```
+ GET /api/purchase/skill?reference=<base58> → { label, icon }
+ POST /api/purchase/skill?reference=<base58> { "account": "<buyer base58>" }
+ → { transaction: "<base64>", message }
+ ```
+
+ Because the server composes it, the transaction can do three things the deep
+ link cannot: the marketplace payer signs as fee payer (a buyer holding only
+ USDC needs no SOL), missing associated token accounts are created idempotently,
+ and the platform fee leg rides the same signature as the seller leg.
+
+The endpoint never creates a purchase. It only serves a `pending` row that the
+authenticated `POST /api/marketplace/purchase` already wrote, so an unknown or
+expired reference is a `404` / `410` and there is no way to mint an unattributed
+purchase from an unauthenticated wallet. The seller leg is always the **last**
+instruction and carries the reference, because `validateTransfer` in step 3
+inspects only the last instruction; a fee leg is placed before it.
+
+The payment modal shows the sponsored QR first and offers a one-click swap to the
+direct-transfer QR for wallets that do not implement transaction requests.
+
## Pricing and payout
- Prices are set per listing (`set-skill-price.js`, `asset-price.js`) with an
diff --git a/docs/money-map.md b/docs/money-map.md
index 544f57e6d..2bb31a84f 100644
--- a/docs/money-map.md
+++ b/docs/money-map.md
@@ -168,7 +168,7 @@ watched for silence. One board rolls it all up.
| **Economy-master breach/tamper** | Unrecorded outbound + hash-chain integrity of the funding root | `api/cron/economy-reconcile.js` (`*/30`) |
| **Zero-activity tripwire** | Enabled-but-silent money loops (the alarm the ring outage lacked) | `api/_lib/financial-tripwire.js`, wired for `x402_autonomous_loop` in the leak-scan cron |
| **Reconciliation** | Ring settlements/sweeps + revenue vs chain | `ring-reconciliation.js`, `revenue-reconciliation.js` |
-| **Unified board** | Per-subsystem open critical/warn verdicts + last activity, one call | `GET /api/ops/money-health` (admin) |
+| **Unified board** | Per-subsystem open critical/warn verdicts + last activity, one call | `GET /api/ops/money-health` (admin session, or `x-ops-secret: $OPS_SECRET`) |
Guardrails on outflow: the economy master is funder-only with reserve/per-transfer/
per-run caps and a registry allowlist; the ring can only settle to allowlisted
diff --git a/docs/monitor.md b/docs/monitor.md
index 0f9a13d27..d3ff3b032 100644
--- a/docs/monitor.md
+++ b/docs/monitor.md
@@ -86,8 +86,11 @@ page where you would do that.
**Nothing is simulated.** There is no sample data, no placeholder row, and no
fabricated number anywhere on this page. When the platform is quiet, the board
-shows zeroes and says so. `/api/home-stats` returning `available:false` leaves
-the previous totals in place rather than rendering a made-up figure.
+shows zeroes and says so. `/api/home-stats` or `/api/platform/stats` returning
+`available:false` leaves the previous totals in place rather than rendering a
+made-up figure. Neither endpoint reports a zero it did not count: a read that
+fails answers `available:false` under a 15-second cache instead of shipping an
+all-zero payload behind the usual multi-minute one.
---
diff --git a/docs/ops/payment-outcomes.md b/docs/ops/payment-outcomes.md
index 9a47054bb..185dfd193 100644
--- a/docs/ops/payment-outcomes.md
+++ b/docs/ops/payment-outcomes.md
@@ -157,4 +157,8 @@ curl -s https://three.ws/api/x402/three-intel | jq '.accepts[].network'
inbound panel reads), `api/_lib/economy-ledger.js` (`recordAgentReclaim`, the
durable trail for every self-heal attempt).
- `/api/ops/money-health` is the complementary board: open reconciliation
- verdicts per money subsystem rather than live payment outcomes.
+ verdicts per money subsystem rather than live payment outcomes. It takes the
+ same gate as this endpoint (admin session or `x-ops-secret`). Until
+ 2026-08-14 it ran its own gate that accepted a `CRON_SECRET` bearer, so an ops
+ script pointed at it with the cron credential now gets a 401: send
+ `x-ops-secret: $OPS_SECRET` (Secret Manager: `ops-dashboard-secret`) instead.
diff --git a/prompts/swarm-100/api-pump-bounties-01.md b/prompts/swarm-100/api-pump-bounties-01.md
deleted file mode 100644
index 9c8b319d8..000000000
--- a/prompts/swarm-100/api-pump-bounties-01.md
+++ /dev/null
@@ -1,102 +0,0 @@
-# API audit: api/pump-bounties batch 01 (2 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/pump-bounties/[id].js
-- api/pump-bounties/stats.js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-pump-bounties-01.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/public/changelog.json b/public/changelog.json
index 4d269b9fb..68ae93e5e 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-14T02:25:27.033Z",
+ "generated_at": "2026-08-14T02:26:31.486Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -46,6 +46,17 @@
"fix"
]
},
+ {
+ "date": "2026-08-14",
+ "type": "update",
+ "title": "Apps that sign in with a client secret can now revoke and inspect their own tokens",
+ "summary": "If you connect an app to three.ws over OAuth and registered it with a client secret sent in the Authorization header (client_secret_basic, the standard choice for server-side apps), only the token endpoint accepted those credentials. Revoking a token or checking whether one is still valid answered that the client_id was missing, and answered that the credentials were bad the moment you added it, so a confidential app had no way to sign a user out or verify a token it owned. All three endpoints now take the same credentials, in the header or in the form body, exactly as the OAuth revocation and introspection standards require. Dynamic client registration also now returns client_secret_expires_at alongside a new secret, so your client can tell that a three.ws secret never expires rather than guessing from a missing field.",
+ "link": "/docs/authentication",
+ "tags": [
+ "fix",
+ "security"
+ ]
+ },
{
"date": "2026-08-14",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 5f8ea99e5..b6b024aae 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -38,6 +38,14 @@
<category>fix</category>
<description>The bounty board at /bounties mirrors the public pump.fun GO board. When you opened a bounty link that had been deleted or mistyped, the page reported it the same way it reports pump.fun being down, so there was no way to tell a dead link from an outage. A bounty that genuinely is not there now answers as not found, and a real upstream problem keeps its own separate answer. A second, quieter case got fixed with it: when the submissions list for a bounty failed to load, the page showed the bounty with zero submissions and said nothing, which looks identical to a bounty nobody has entered. That failure is now recorded, so a pump.fun outage shows up as an outage rather than as a board that suddenly looks unpopular.</description>
</item>
+ <item>
+ <title>Apps that sign in with a client secret can now revoke and inspect their own tokens</title>
+ <link>https://three.ws/docs/authentication</link>
+ <guid isPermaLink="false">2026-08-14:Apps that sign in with a client secret can now revoke and inspect their own tokens</guid>
+ <pubDate>Fri, 14 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>If you connect an app to three.ws over OAuth and registered it with a client secret sent in the Authorization header (client_secret_basic, the standard choice for server-side apps), only the token endpoint accepted those credentials. Revoking a token or checking whether one is still valid answered that the client_id was missing, and answered that the credentials were bad the moment you added it, so a confidential app had no way to sign a user out or verify a token it owned. All three endpoints now take the same credentials, in the header or in the form body, exactly as the OAuth revocation and introspection standards require. Dynamic client registration also now returns client_secret_expires_at alongside a new secret, so your client can tell that a three.ws secret never expires rather than guessing from a missing field.</description>
+ </item>
<item>
<title>Avatar likeness is now measured against your photos, not assumed</title>
<link>https://three.ws/changelog</link>
diff --git a/scripts/monetization-api-proof.mjs b/scripts/monetization-api-proof.mjs
index 941727dd5..3d433bc2c 100644
--- a/scripts/monetization-api-proof.mjs
+++ b/scripts/monetization-api-proof.mjs
@@ -501,24 +501,51 @@ async function main() {
&& r.json?.withdrawals?.length === 0 && r.json?.balance?.available_usdc === 0,
`status ${r.status}, available ${r.json?.balance?.available_usdc}`);
}
+ // Withdrawal POSTs are rate limited to 5 per user per day (rate-limit.js,
+ // `withdrawalPerUser`), and a refused request still spends one. So the
+ // refusal probes run as their own throwaway user, leaving the owner's whole
+ // budget for the real reservations in step 7.
+ const solo = makeHttp();
+ const soloEmail = `mon-solo-${stamp}@proof.local`;
+ const soloReg = await solo.req('POST', '/api/auth/register', { body: { email: soloEmail, password: 'proof-pass-12345', tosAccepted: true } });
+ const soloAgent = await solo.write('POST', '/api/agents', { name: `mon-solo-${stamp}`, description: 'withdrawal refusal probes' });
+ const soloAgentId = soloAgent.json?.agent?.id || soloAgent.json?.data?.id || soloAgent.json?.id;
+ check('third (refusal-probe) user and agent created', soloReg.status < 300 && !!soloAgentId,
+ soloAgentId ? `agent ${soloAgentId}` : `register ${soloReg.status}, agent ${soloAgent.status}`);
+ if (!soloAgentId) throw new Error('cannot continue without the refusal-probe agent');
+ {
+ const r = await solo.write('POST', '/api/monetization/withdrawals', { agent_id: soloAgentId, amount_usdc: 5 });
+ check('POST before any payout wallet exists -> 422 no_payout_wallet', r.status === 422 && r.json?.error === 'no_payout_wallet',
+ `status ${r.status}, ${r.json?.error}`);
+ }
+ await solo.write('PUT', '/api/monetization/wallet', { agent_id: soloAgentId, solana_address: SOL_PAYOUT });
+ {
+ const r = await solo.write('POST', '/api/monetization/withdrawals', { agent_id: soloAgentId, amount_usdc: 5, network: 'base' });
+ check('POST on a chain with no wallet -> 422 rather than paying out on another chain',
+ r.status === 422 && r.json?.error === 'no_payout_wallet', `status ${r.status}, ${r.json?.error}`);
+ }
{
- const r = await http.write('POST', '/api/monetization/withdrawals', { agent_id: agentId, amount_usdc: 5 });
+ const r = await solo.write('POST', '/api/monetization/withdrawals', { agent_id: soloAgentId, amount_usdc: 5 });
check('POST with a zero balance -> 422 insufficient_balance', r.status === 422 && r.json?.error === 'insufficient_balance',
`status ${r.status}, ${r.json?.error}`);
}
{
- const r = await http.write('POST', '/api/monetization/withdrawals', { agent_id: agentId, amount_usdc: 0.5 });
+ const r = await solo.write('POST', '/api/monetization/withdrawals', { agent_id: soloAgentId, amount_usdc: 0.5 });
check('POST below the 1 USDC minimum -> 422 below_minimum', r.status === 422 && r.json?.error === 'below_minimum',
`status ${r.status}, ${r.json?.error}`);
}
{
- const r = await http.write('POST', '/api/monetization/withdrawals', { agent_id: GHOST, amount_usdc: 5 });
+ const r = await solo.write('POST', '/api/monetization/withdrawals', { agent_id: GHOST, amount_usdc: 5 });
check('POST for an unknown agent -> 404', r.status === 404, `status ${r.status}`);
}
{
const r = await other.write('POST', '/api/monetization/withdrawals', { agent_id: agentId, amount_usdc: 5 });
check("POST against someone else's agent -> 403", r.status === 403, `status ${r.status}`);
}
+ {
+ const r = await solo.write('POST', '/api/monetization/withdrawals', { agent_id: soloAgentId, amount_usdc: 5 });
+ check('a sixth POST in a day is rate limited -> 429', r.status === 429, `status ${r.status}`);
+ }
// seeded revenue, then revenue.js and a live withdrawal
step('6. seeded revenue -> /api/monetization/revenue');
@@ -594,11 +621,16 @@ async function main() {
}
{
const r = await http.write('POST', '/api/monetization/withdrawals', { agent_id: agentId, amount_usdc: 4 });
- check('POST reserves a pending withdrawal -> 201', r.status === 201
+ // The EVM payout row was saved after the Solana one. Taking the newest row
+ // would price this withdrawal in Base USDC, where the balance is zero, and
+ // refuse it. Solana is the home chain and the saved preference, so it wins.
+ check('POST reserves a pending withdrawal -> 201, on Solana', r.status === 201
&& r.json?.withdrawal?.status === 'pending'
&& r.json.withdrawal.amount_atomic === 4_000_000
+ && r.json.withdrawal.chain === 'solana'
+ && r.json.withdrawal.currency_mint === USDC_SOL
&& r.json.withdrawal.destination_address === SOL_PAYOUT,
- `status ${r.status}, ${r.json?.withdrawal?.amount_usdc} USDC to ${r.json?.withdrawal?.destination_address?.slice(0, 8)}`);
+ `status ${r.status}, ${r.json?.withdrawal?.amount_usdc} USDC on ${r.json?.withdrawal?.chain} to ${r.json?.withdrawal?.destination_address?.slice(0, 8)}`);
}
{
const r = await http.write('POST', '/api/monetization/withdrawals', { agent_id: agentId, amount_usdc: 4 });
diff --git a/sdk/src/erc7710/abi.js b/sdk/src/erc7710/abi.js
index fafee31ab..e74d7ac01 100644
--- a/sdk/src/erc7710/abi.js
+++ b/sdk/src/erc7710/abi.js
@@ -25,7 +25,7 @@ import { loadViem } from '../peer.js';
export const DELEGATION_MANAGER_ABI = [
'function disableDelegation(bytes32 delegationHash) external',
- 'function isDelegationDisabled(bytes32 delegationHash) external view returns (bool)',
+ 'function disabledDelegations(bytes32 delegationHash) external view returns (bool)',
'event DisabledDelegation(bytes32 indexed delegationHash)',
];
diff --git a/sdk/src/permissions/toolkit.js b/sdk/src/permissions/toolkit.js
index 0eb337f67..7840a87f4 100644
--- a/sdk/src/permissions/toolkit.js
+++ b/sdk/src/permissions/toolkit.js
@@ -97,6 +97,8 @@ export async function signDelegation(unsigned, signer) {
* @param {number} opts.chainId EVM chain ID
* @param {string} [opts.rpcUrl] RPC endpoint URL
* @returns {Promise<{ valid: boolean; reason?: string }>}
+ * @throws {PermissionError} 'chain_not_supported' with no RPC or no deployment,
+ * 'rpc_error' when the chain could not answer (never reported as valid).
*/
export async function isDelegationValid({ hash, chainId, rpcUrl }) {
const url = rpcUrl ?? (typeof process !== 'undefined' ? process.env[`RPC_URL_${chainId}`] : null);
@@ -113,8 +115,9 @@ export async function isDelegationValid({ hash, chainId, rpcUrl }) {
throw new PermissionError('chain_not_supported', err.message);
}
- // eth_call: isDelegationDisabled(bytes32)
- const callData = '0x' + 'a1a5bdd0' + hash.replace('0x', '').padStart(64, '0');
+ // eth_call: disabledDelegations(bytes32) — keccak256 selector 0x2d40d052.
+ // This is the only revocation getter the deployed DelegationManager exposes.
+ const callData = '0x2d40d052' + hash.replace('0x', '').padStart(64, '0');
const res = await fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json' },
@@ -126,7 +129,16 @@ export async function isDelegationValid({ hash, chainId, rpcUrl }) {
}),
});
const json = await res.json();
- const disabled = json.result === '0x' + '1'.padStart(64, '0');
+ // Never fail open: a revocation check that could not read the chain must say
+ // so, or a caller treats an unanswered question as "still valid" and honours a
+ // delegation the owner already disabled.
+ if (json?.error || typeof json?.result !== 'string') {
+ throw new PermissionError(
+ 'rpc_error',
+ json?.error?.message || 'delegation revocation check did not return a result',
+ );
+ }
+ const disabled = BigInt(json.result || '0x0') !== 0n;
return disabled ? { valid: false, reason: 'delegation_revoked' } : { valid: true };
}
diff --git a/server/index.mjs b/server/index.mjs
index fb23316e8..6f3201ed6 100644
--- a/server/index.mjs
+++ b/server/index.mjs
@@ -501,9 +501,12 @@ app.use((err, req, res, next) => {
// Surface a specific code + human message so client error paths (which
// read error/error_description) say something actionable.
if (err?.type === 'entity.too.large' || status === 413) {
+ // Quote BODY_LIMIT rather than a literal: this said "under 4 MB" long
+ // after the cap moved to 8 MB, so a caller inside the real limit was
+ // told to shrink a payload that was already small enough.
res.status(413).json({
error: 'payload_too_large',
- error_description: 'Request body is too large. Images must be under 4 MB.',
+ error_description: `Request body is too large. Keep it under ${BODY_LIMIT.toUpperCase().replace('MB', ' MB')}.`,
message: err.message,
});
return;
diff --git a/specs/AGENT_MANIFEST.md b/specs/AGENT_MANIFEST.md
index 6339ef669..ef1a48c72 100644
--- a/specs/AGENT_MANIFEST.md
+++ b/specs/AGENT_MANIFEST.md
@@ -418,7 +418,7 @@ Hosts resolve a delegation in this order:
1. **If `envelope` is present (inline)** — use it directly. Envelope was validated at grant time; treat as equivalent to the fetched form.
2. **Else fetch from `uri`** — resolve via IPFS gateway (with fallback), Arweave, or HTTPS, using the same resolution rules as `body.uri`.
3. **Verify `hash` matches** — compute `keccak256(envelope)` and compare to the `hash` field. Abort if mismatch.
-4. **Verify signature on-chain** — call `DelegationManager.isDelegationDisabled(hash)` to confirm the delegation has not been revoked, and verify the envelope's EIP-712 signature against the delegator address before trusting.
+4. **Verify signature on-chain** — call `DelegationManager.disabledDelegations(hash)` to confirm the delegation has not been revoked, and verify the envelope's EIP-712 signature against the delegator address before trusting.
Verification occurs before any redemption attempt. If any step fails, do not proceed to redeem.
diff --git a/specs/PERMISSIONS_SPEC.md b/specs/PERMISSIONS_SPEC.md
index 0d6031868..ff3a3de75 100644
--- a/specs/PERMISSIONS_SPEC.md
+++ b/specs/PERMISSIONS_SPEC.md
@@ -128,7 +128,7 @@ Redemption is the path from a skill requesting an on-chain action to a confirmed
**Race condition.** A redemption submitted before the revoke transaction confirms, but processed concurrently, may succeed on-chain. The on-chain caveats remain the authority: if the revoke confirms first, the redemption reverts. If the redemption confirms first, it is valid. There is no off-chain mechanism to prevent this window — operators should treat `scope + expiry` as the primary blast-radius control, not the race-free revocation guarantee.
-**Verify endpoint.** `GET /api/permissions/verify?hash=0x...&chainId=N` performs a real-time on-chain read (`DelegationManager.isDelegationDisabled(hash)`) before returning `{ valid }`, giving callers a fresh view independent of the indexer lag.
+**Verify endpoint.** `GET /api/permissions/verify?hash=0x...&chainId=N` performs a real-time on-chain read (`DelegationManager.disabledDelegations(hash)`) before returning `{ valid }`, giving callers a fresh view independent of the indexer lag.
---
diff --git a/src/agent-edit.js b/src/agent-edit.js
index 5bb79330c..22ab70854 100644
--- a/src/agent-edit.js
+++ b/src/agent-edit.js
@@ -2183,22 +2183,22 @@ async function refreshBalances() {
const r = await apiFetch(`${API_BASE}/portfolio/summary`, { credentials: 'include' });
if (!r.ok) return;
const j = await r.json();
+ // /api/portfolio/summary returns each wallet as { usd, native, tokens }.
+ // This read used `usd_total` and a flat `assets` array, neither of which the
+ // route has ever sent, so the panel showed 0 / 0 / $0.00 for every agent.
const mine = (j.wallets || []).filter((w) => w.agent_id === agentId);
let solBal = null, usdcBal = null, totalUsd = 0;
for (const w of mine) {
- totalUsd += Number(w.usd_total || 0);
- for (const a of (w.assets || [])) {
- if (w.chain === 'solana') {
- if (a.symbol === 'SOL') solBal = a;
- if (a.symbol === 'USDC') usdcBal = a;
- }
- }
+ totalUsd += Number(w.usd || 0);
+ if (w.chain !== 'solana') continue;
+ if (w.native?.symbol === 'SOL') solBal = w.native;
+ usdcBal = (w.tokens || []).find((t) => t.symbol === 'USDC') || usdcBal;
}
$('wallet-sol-balance').textContent = solBal ? Number(solBal.amount).toFixed(4) : '0';
$('wallet-usdc-balance').textContent = usdcBal ? Number(usdcBal.amount).toFixed(2) : '0';
$('wallet-total-usd').textContent = `$${totalUsd.toFixed(2)}`;
} catch {
- // Balance fetch is non-fatal — addresses are still useful.
+ // Balance fetch is non-fatal, the addresses above are still useful.
}
}
@@ -2243,15 +2243,21 @@ $('send-cancel').addEventListener('click', () => { $('send-modal').hidden = true
$('send-confirm').addEventListener('click', async () => {
const status = $('send-status');
- const asset = $('send-asset').value;
- const to = $('send-to').value.trim();
- const amount = parseFloat($('send-amount').value);
- if (!to || !(amount > 0)) {
+ const picked = $('send-asset').value;
+ const recipient = $('send-to').value.trim();
+ // Send the typed decimal string, not a re-serialized float: `parseFloat(…)
+ // .toString()` turns a small amount into exponential notation ("1e-7"), which
+ // the route's amount regex rejects.
+ const amount = $('send-amount').value.trim();
+ if (!recipient || !(parseFloat(amount) > 0)) {
status.textContent = 'Recipient and positive amount required.';
status.className = 'form-status err';
return;
}
- if (!confirm(`Send ${amount} ${asset.toUpperCase()} to ${to}?`)) return;
+ // The route takes 'native' for SOL and a mint address for an SPL token; the
+ // select's raw 'sol'/'usdc' values were rejected as an unknown asset.
+ const asset = picked === 'sol' ? 'native' : USDC_MINT;
+ if (!confirm(`Send ${amount} ${picked.toUpperCase()} to ${recipient}?`)) return;
status.textContent = 'Sending…';
status.className = 'form-status';
try {
@@ -2259,11 +2265,11 @@ $('send-confirm').addEventListener('click', async () => {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
- body: JSON.stringify({ agent_id: agentId, chain: 'solana', asset, to, amount: amount.toString() }),
+ body: JSON.stringify({ agent_id: agentId, chain: 'solana', asset, recipient, amount }),
});
const j = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);
- status.textContent = `Sent. tx ${j.signature?.slice(0, 8) || ''}…`;
+ status.textContent = `Sent. tx ${j.tx_hash?.slice(0, 8) || ''}…`;
status.className = 'form-status ok';
$('send-to').value = '';
$('send-amount').value = '';
diff --git a/src/erc7710/abi.js b/src/erc7710/abi.js
index e9561267b..be824a52d 100644
--- a/src/erc7710/abi.js
+++ b/src/erc7710/abi.js
@@ -35,7 +35,9 @@ export const DELEGATION_MANAGER_ABI = [
'function disableDelegation(tuple(address delegate, address delegator, bytes32 authority, tuple(address enforcer, bytes terms, bytes args)[] caveats, uint256 salt, bytes signature) _delegation) external',
// Public mapping: true if the delegation hash has been disabled on-chain
- // (on-chain name is disabledDelegations; isDelegationDisabled in task spec maps here)
+ // The revocation getter. This exact name is what every caller must use: an
+ // ethers Contract resolves an unknown method to undefined, so a near-miss
+ // spelling throws "not a function" at call time rather than failing loudly here.
'function disabledDelegations(bytes32 delegationHash) external view returns (bool isDisabled)',
// Returns the keccak256 hash for a delegation (used for revoke checks and signing)
diff --git a/tests/api/notifications-center.test.js b/tests/api/notifications-center.test.js
index fd27befe2..5a62b19e2 100644
--- a/tests/api/notifications-center.test.js
+++ b/tests/api/notifications-center.test.js
@@ -142,6 +142,20 @@ describe('GET /api/notifications', () => {
expect(listQuery().values).toContain(20);
});
+ // NaN passes straight through Math.min/Math.max, so a junk ?limit used to
+ // reach Postgres as `limit NaN` and 500 the whole inbox.
+ it('falls back to the default page size when limit is not a number', async () => {
+ for (const limit of ['abc', '', 'NaN', '1e', '#20']) {
+ sqlCalls.length = 0;
+ const { res } = await call(listHandler, { query: { limit } });
+ expect(res.statusCode).toBe(200);
+ const bound = listQuery().values.find((v) => typeof v === 'number');
+ expect(Number.isFinite(bound)).toBe(true);
+ expect(bound).toBeGreaterThanOrEqual(1);
+ expect(bound).toBeLessThanOrEqual(50);
+ }
+ });
+
it('applies a well-formed type filter and ignores a malformed one', async () => {
await call(listHandler, { query: { type: 'pump_alert' } });
expect(listQuery().text).toMatch(/type = /);
@@ -195,7 +209,7 @@ describe('POST /api/notifications/read-all', () => {
});
it('marks the caller unread rows read and reports how many', async () => {
- dbState.marked = [{ count: 4 }, { count: 4 }, { count: 4 }, { count: 4 }];
+ dbState.marked = [{ id: 'n1' }, { id: 'n2' }, { id: 'n3' }, { id: 'n4' }];
const { res, body } = await call(readAllHandler, { method: 'POST' });
expect(res.statusCode).toBe(200);
expect(body.marked_read).toBe(4);
@@ -205,6 +219,21 @@ describe('POST /api/notifications/read-all', () => {
expect(update.values).toContain(USER.id);
});
+ // Postgres rejects a window function in RETURNING ("window functions are not
+ // allowed in RETURNING"), so the `count(*) over ()` form this used to send
+ // threw on every single call and the bell's "mark all read" was a permanent
+ // 500. The count has to come from the returned row list, not from the query.
+ it('counts the returned rows instead of aggregating inside RETURNING', async () => {
+ dbState.marked = [{ id: 'n1' }, { id: 'n2' }];
+ const { body } = await call(readAllHandler, { method: 'POST' });
+ expect(body.marked_read).toBe(2);
+
+ const [update] = sqlCalls.filter((c) => /update user_notifications/.test(c.text));
+ const returning = update.text.slice(update.text.toLowerCase().lastIndexOf('returning'));
+ expect(returning).not.toMatch(/over\s*\(/i);
+ expect(returning).not.toMatch(/count\s*\(/i);
+ });
+
it('reports zero, not null, when there was nothing unread', async () => {
const { body } = await call(readAllHandler, { method: 'POST' });
expect(body.marked_read).toBe(0);
diff --git a/tests/api/notifications-item-and-prefs.test.js b/tests/api/notifications-item-and-prefs.test.js
new file mode 100644
index 000000000..cb2d7f84d
--- /dev/null
+++ b/tests/api/notifications-item-and-prefs.test.js
@@ -0,0 +1,274 @@
+// Unit tests for the per-notification routes and the preference center:
+// POST /api/notifications/:id/read -> api/notifications/[id]/read.js
+// DELETE /api/notifications/:id -> api/notifications/[id]/index.js
+// GET|PUT /api/notifications/preferences -> api/notifications/preferences.js
+//
+// Pins three defects found by probing the live handlers (api audit, work order
+// api-notifications-01):
+// 1. `:id` is a uuid column, so a non-uuid id failed the cast inside Postgres
+// and the caller got a 500 where the sibling DELETE already returned 400.
+// 2. A PUT wrote the request body over the whole stored row, so the settings
+// panel (which saves the category matrix alone) wiped a connected Telegram
+// chat id on every save and silently stopped those alerts.
+// 3. A malformed body was parsed leniently into `{ categories: {} }` and then
+// stored, so a typo in a client 200'd and reset every preference to default.
+//
+// Mocks: sql (content-routed so each write is observable), auth, csrf,
+// rate-limit. All offline, no DATABASE_URL or Redis needed.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const dbState = { deleted: [], marked: [], stored: null, pushDevices: 0 };
+const sqlCalls = [];
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: Object.assign(
+ vi.fn((strings, ...values) => {
+ const text = strings.join(' ? ');
+ sqlCalls.push({ text, values });
+ if (/delete from user_notifications/.test(text)) return Promise.resolve(dbState.deleted);
+ if (/update user_notifications/.test(text)) return Promise.resolve(dbState.marked);
+ if (/from notification_preferences/.test(text)) {
+ return Promise.resolve(dbState.stored ? [{ prefs: dbState.stored }] : []);
+ }
+ if (/from push_subscriptions/.test(text)) {
+ return Promise.resolve([{ count: dbState.pushDevices }]);
+ }
+ return Promise.resolve([]);
+ }),
+ { transaction: vi.fn(async (fns) => { for (const f of fns) await f; }) },
+ ),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const authState = { user: null };
+vi.mock('../../api/_lib/auth.js', () => ({
+ getRequestUser: vi.fn(async () => authState.user),
+}));
+
+const csrfState = { ok: true };
+vi.mock('../../api/_lib/csrf.js', () => ({
+ requireCsrf: vi.fn(async (req, res) => {
+ if (csrfState.ok) return true;
+ res.statusCode = 403;
+ res.end(JSON.stringify({ error: 'forbidden' }));
+ return false;
+ }),
+}));
+
+const rlState = { success: true, limit: 30, remaining: 0, reset: 0 };
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { notifPrefsWrite: vi.fn(async () => rlState) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const { default: readHandler } = await import('../../api/notifications/[id]/read.js');
+const { default: deleteHandler } = await import('../../api/notifications/[id]/index.js');
+const { default: prefsHandler } = await import('../../api/notifications/preferences.js');
+
+const USER = { id: '00000000-0000-0000-0000-0000000000b1' };
+const ID = '46024db6-38f1-4a4e-99a3-b5a8e2ef4b80';
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this._body = body; },
+ };
+}
+async function call(handler, { method = 'POST', query = {}, body } = {}) {
+ const res = makeRes();
+ const req = {
+ method,
+ query,
+ url: '/api/notifications',
+ headers: body === undefined ? {} : { 'content-type': 'application/json' },
+ };
+ if (body !== undefined) req.body = body;
+ await handler(req, res);
+ let parsed = null;
+ try { parsed = JSON.parse(res._body); } catch {}
+ return { res, body: parsed };
+}
+
+const writes = () => sqlCalls.filter((c) => /insert into notification_preferences/.test(c.text));
+const storedWrite = () => JSON.parse(writes().at(-1).values[1]);
+
+beforeEach(() => {
+ sqlCalls.length = 0;
+ dbState.deleted = [];
+ dbState.marked = [];
+ dbState.stored = null;
+ dbState.pushDevices = 0;
+ authState.user = USER;
+ csrfState.ok = true;
+ rlState.success = true;
+});
+
+describe('POST /api/notifications/:id/read', () => {
+ it('401s for an anonymous caller without querying anything', async () => {
+ authState.user = null;
+ const { res, body } = await call(readHandler, { query: { id: ID } });
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ expect(sqlCalls).toHaveLength(0);
+ });
+
+ it('rejects a GET, because the route is state-changing', async () => {
+ const { res } = await call(readHandler, { method: 'GET', query: { id: ID } });
+ expect(res.statusCode).toBe(405);
+ });
+
+ it('marks the caller row read and scopes the update to them', async () => {
+ dbState.marked = [{ id: ID, read_at: '2026-08-14T02:08:54.547Z' }];
+ const { res, body } = await call(readHandler, { query: { id: ID } });
+ expect(res.statusCode).toBe(200);
+ expect(body).toEqual({ id: ID, read_at: '2026-08-14T02:08:54.547Z' });
+ const [update] = sqlCalls.filter((c) => /update user_notifications/.test(c.text));
+ expect(update.values).toContain(USER.id);
+ });
+
+ // A non-uuid used to reach Postgres and blow up as "invalid input syntax for
+ // type uuid", surfacing to the caller as an opaque 500.
+ it('400s a malformed id at the boundary instead of sending it to Postgres', async () => {
+ for (const id of ['not-a-uuid', '123', 'null', `${ID}x`]) {
+ sqlCalls.length = 0;
+ const { res, body } = await call(readHandler, { query: { id } });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ expect(sqlCalls.filter((c) => /update user_notifications/.test(c.text))).toHaveLength(0);
+ }
+ });
+
+ it('404s a well-formed id that is not the caller own row', async () => {
+ const { res, body } = await call(readHandler, { query: { id: ID } });
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+});
+
+describe('DELETE /api/notifications/:id', () => {
+ it('401s for an anonymous caller', async () => {
+ authState.user = null;
+ const { res } = await call(deleteHandler, { method: 'DELETE', query: { id: ID } });
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('refuses to delete when the CSRF check fails', async () => {
+ csrfState.ok = false;
+ const { res } = await call(deleteHandler, { method: 'DELETE', query: { id: ID } });
+ expect(res.statusCode).toBe(403);
+ expect(sqlCalls.filter((c) => /delete from user_notifications/.test(c.text))).toHaveLength(0);
+ });
+
+ it('deletes the caller own row and reports it', async () => {
+ dbState.deleted = [{ id: ID }];
+ const { res, body } = await call(deleteHandler, { method: 'DELETE', query: { id: ID } });
+ expect(res.statusCode).toBe(200);
+ expect(body).toEqual({ ok: true, id: ID, deleted: true });
+ const [del] = sqlCalls.filter((c) => /delete from user_notifications/.test(c.text));
+ expect(del.values).toContain(USER.id);
+ });
+
+ it('400s a malformed id and 404s one that is not the caller own', async () => {
+ const bad = await call(deleteHandler, { method: 'DELETE', query: { id: 'not-a-uuid' } });
+ expect(bad.res.statusCode).toBe(400);
+ const missing = await call(deleteHandler, { method: 'DELETE', query: { id: ID } });
+ expect(missing.res.statusCode).toBe(404);
+ });
+});
+
+describe('GET /api/notifications/preferences', () => {
+ it('401s for an anonymous caller', async () => {
+ authState.user = null;
+ const { res } = await call(prefsHandler, { method: 'GET' });
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('serves the full matrix, the channel list and the push device count', async () => {
+ dbState.pushDevices = 2;
+ const { res, body } = await call(prefsHandler, { method: 'GET' });
+ expect(res.statusCode).toBe(200);
+ expect(body.channels).toEqual(['in_app', 'push', 'email', 'telegram']);
+ expect(body.categories.map((c) => c.key)).toContain('social');
+ expect(body.prefs.categories.social).toBeTruthy();
+ expect(body.push).toEqual({ subscribed_devices: 2 });
+ });
+});
+
+describe('PUT /api/notifications/preferences', () => {
+ it('persists a sanitised sparse override', async () => {
+ const { res } = await call(prefsHandler, {
+ method: 'PUT',
+ body: { categories: { social: { push: false }, nonsense: { push: true } } },
+ });
+ expect(res.statusCode).toBe(200);
+ const written = storedWrite();
+ expect(written.categories.social).toEqual({ push: false });
+ expect(written.categories.nonsense).toBeUndefined();
+ });
+
+ it('429s when the per-user write limit is exhausted', async () => {
+ rlState.success = false;
+ const { res } = await call(prefsHandler, { method: 'PUT', body: { categories: {} } });
+ expect(res.statusCode).toBe(429);
+ expect(writes()).toHaveLength(0);
+ });
+
+ // The settings panel saves the category matrix and nothing else. Writing the
+ // body over the stored row therefore dropped the Telegram chat id, and the
+ // same panel reads that value to decide whether the telegram channel is even
+ // usable, so alerts stopped with no visible cause.
+ it('preserves a stored telegram chat id when the PUT sends categories only', async () => {
+ dbState.stored = { categories: { alerts: { email: true } }, telegram_chat_id: '123456789' };
+ await call(prefsHandler, { method: 'PUT', body: { categories: { social: { push: false } } } });
+ const written = storedWrite();
+ expect(written.telegram_chat_id).toBe('123456789');
+ expect(written.categories.alerts).toEqual({ email: true });
+ expect(written.categories.social).toEqual({ push: false });
+ });
+
+ it('merges into a category instead of replacing it', async () => {
+ dbState.stored = { categories: { social: { email: true, push: true } } };
+ await call(prefsHandler, { method: 'PUT', body: { categories: { social: { push: false } } } });
+ expect(storedWrite().categories.social).toEqual({ email: true, push: false });
+ });
+
+ it('clears the telegram chat id when the caller sends null, and when they send an empty string', async () => {
+ dbState.stored = { categories: {}, telegram_chat_id: '123456789' };
+ await call(prefsHandler, { method: 'PUT', body: { telegram_chat_id: null } });
+ expect(storedWrite().telegram_chat_id).toBeNull();
+
+ await call(prefsHandler, { method: 'PUT', body: { telegram_chat_id: '' } });
+ expect(storedWrite().telegram_chat_id).toBeNull();
+ });
+
+ // A lenient parse turned any malformed body into `{ categories: {} }` and
+ // stored it, so one bad client field silently reset every preference.
+ it('400s a malformed body and writes nothing', async () => {
+ const bodies = [
+ { categories: 'garbage' },
+ { categories: { social: { push: 'yes' } } },
+ { categories: { social: 'on' } },
+ { telegram_chat_id: 'not-numeric' },
+ { telegram_chat_id: 12345 },
+ ];
+ for (const body of bodies) {
+ sqlCalls.length = 0;
+ const { res, body: out } = await call(prefsHandler, { method: 'PUT', body });
+ expect(res.statusCode).toBe(400);
+ expect(out.error).toBe('validation_error');
+ expect(writes()).toHaveLength(0);
+ }
+ });
+
+ it('accepts a valid numeric telegram chat id, negative group ids included', async () => {
+ for (const id of ['123456789', '-1001234567890']) {
+ const { res } = await call(prefsHandler, { method: 'PUT', body: { telegram_chat_id: id } });
+ expect(res.statusCode).toBe(200);
+ expect(storedWrite().telegram_chat_id).toBe(id);
+ }
+ });
+});
diff --git a/tests/api/okx-identity-studio.test.js b/tests/api/okx-identity-studio.test.js
index f779ba9c7..afbe85582 100644
--- a/tests/api/okx-identity-studio.test.js
+++ b/tests/api/okx-identity-studio.test.js
@@ -21,6 +21,10 @@ process.env.X402_PAY_TO_XLAYER ||= '0x75d00a2713565171f33216e5aa2a375e076ecf69';
process.env.X402_XLAYER_RELAYER_KEY ||=
'0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d';
process.env.JWT_SECRET ||= 'okx-identity-test-secret';
+// /health memoizes its subsystem sweep in production; disable the memo by
+// default here so each case sees its own probes, and opt back in where the
+// cache itself is under test.
+process.env.OKX_HEALTH_TTL_MS = '0';
vi.mock('../../api/_lib/auth.js', () => ({
extractBearer: () => null,
@@ -85,6 +89,14 @@ const fetchRoutes = { chat: null, forgeSubmit: null, forgePoll: null, rig: null,
function jsonResponse(status, body) {
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
}
+// What GET /api/forge?catalog really answers with: the tier + backend matrix
+// the health probe requires before it calls the generation lane up.
+const FORGE_CATALOG = {
+ paths: ['image', 'geometry'],
+ tiers: [{ id: 'draft' }, { id: 'standard' }],
+ backends: [{ id: 'trellis' }, { id: 'hunyuan3d' }],
+};
+
const realFetch = globalThis.fetch;
beforeEach(() => {
r2Store.clear();
@@ -203,31 +215,7 @@ describe('free lanes over HTTP', () => {
});
it('GET /health runs real probes and reports per-subsystem status', async () => {
- fetchRoutes.forgeSubmit = () => jsonResponse(200, { tiers: [] });
- fetchRoutes.render = () => jsonResponse(200, { poses: [{ id: 'tpose' }] });
- // WO-03 probes: the retarget clip manifest, and the X Layer JSON-RPC
- // calls behind the payment-rail probe (block height + USD₮0 symbol read).
- fetchRoutes.ref = (u, init) => {
- if (String(u).includes('/animations/manifest.json')) {
- return jsonResponse(200, [{ name: 'idle', url: '/animations/idle.json' }]);
- }
- let rpc = {};
- try {
- rpc = JSON.parse(init?.body || '{}');
- } catch {
- /* not JSON-RPC */
- }
- const reply = (result) => jsonResponse(200, { jsonrpc: '2.0', id: rpc.id ?? 1, result });
- if (rpc.method === 'eth_blockNumber') return reply('0x10');
- if (rpc.method === 'eth_chainId') return reply('0xc4');
- if (rpc.method === 'eth_call') {
- // ABI-encoded string "USD₮0" — the on-chain symbol() return value.
- return reply(
- '0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000007555344e282ae3000000000000000000000000000000000000000000000000000',
- );
- }
- return jsonResponse(404, {});
- };
+ mountHealthyProbes();
const res = makeRes();
await handler(makeReq({ method: 'GET', service: 'health' }), res);
expect(res.statusCode).toBe(200);
@@ -246,13 +234,53 @@ describe('free lanes over HTTP', () => {
it('GET /health goes 503 when a subsystem is down — never a hardcoded ok', async () => {
fetchRoutes.render = () => new Response(null, { status: 500 });
- fetchRoutes.forgeSubmit = () => jsonResponse(200, { tiers: [] });
+ fetchRoutes.forgeSubmit = () => jsonResponse(200, FORGE_CATALOG);
const res = makeRes();
await handler(makeReq({ method: 'GET', service: 'health' }), res);
expect(res.statusCode).toBe(503);
expect(JSON.parse(res.body).ok).toBe(false);
});
+ // The generation probe used to GET /api/forge bare, which answers 400
+ // missing_job whether the lane is healthy or not — it only failed on a 5xx.
+ // It now reads ?catalog and requires a real tier + backend matrix.
+ it('GET /health fails generation on an empty forge catalog, not just on a 5xx', async () => {
+ fetchRoutes.forgeSubmit = (u) => {
+ expect(String(u)).toContain('/api/forge?catalog');
+ return jsonResponse(200, { tiers: [], backends: [] });
+ };
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', service: 'health' }), res);
+ expect(res.statusCode).toBe(503);
+ const generation = JSON.parse(res.body).subsystems.find((s) => s.name === 'generation');
+ expect(generation.ok).toBe(false);
+ expect(generation.error).toContain('empty');
+ });
+
+ // /health is free, unauthenticated, and fans out to five subsystems, so the
+ // report is memoized for OKX_HEALTH_TTL_MS: a poll loop costs one sweep per
+ // window, not one per request.
+ it('GET /health memoizes the sweep within the TTL window', async () => {
+ fetchRoutes.forgeSubmit = () => jsonResponse(200, FORGE_CATALOG);
+ // First call with the memo off, so this case sweeps for real and seeds a
+ // reading of its own instead of inheriting an earlier test's.
+ const first = makeRes();
+ await handler(makeReq({ method: 'GET', service: 'health' }), first);
+ const probesAfterFirst = globalThis.fetch.mock.calls.length;
+ expect(probesAfterFirst).toBeGreaterThan(0);
+
+ process.env.OKX_HEALTH_TTL_MS = '60000';
+ try {
+ const second = makeRes();
+ await handler(makeReq({ method: 'GET', service: 'health' }), second);
+ expect(globalThis.fetch.mock.calls.length).toBe(probesAfterFirst);
+ expect(JSON.parse(second.body).checkedAt).toBe(JSON.parse(first.body).checkedAt);
+ expect(second.headers['cache-control']).toBe('public, max-age=15, s-maxage=30');
+ } finally {
+ process.env.OKX_HEALTH_TTL_MS = '0';
+ }
+ });
+
it('unknown service 404s with the service index', async () => {
const res = makeRes();
await handler(makeReq({ method: 'GET', service: 'nope' }), res);
@@ -309,6 +337,60 @@ describe('402 challenge and pricing', () => {
expect(challenge.accepts.slice(1).some((a) => a.network !== 'eip155:196')).toBe(true);
});
+ // The 402 envelope is how a buying agent learns to call this server. It used
+ // to inherit build402Body's default bazaar entry, which describes the main
+ // /api/mcp server and told buyers to call validate_model — a tool this
+ // dispatcher does not have, so an agent that followed it paid $1.50 and then
+ // sent a call that could only be rejected.
+ it('the 402 bazaar extension describes THIS server: create_identity, never validate_model', async () => {
+ const res = makeRes();
+ await handler(
+ makeReq({
+ body: {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'create_identity', arguments: { agent_name: 'X', brief: 'a data agent' } },
+ },
+ }),
+ res,
+ );
+ expect(res.statusCode).toBe(402);
+ const challenge = JSON.parse(res.body);
+ const bazaar = challenge.extensions.bazaar;
+ expect(bazaar.discoverable).toBe(true);
+ expect(bazaar.info.input.method).toBe('POST');
+ expect(bazaar.info.input.body.params.name).toBe('create_identity');
+ // The advertised example arguments must satisfy the tool's real schema.
+ const validateArgs = tools.TOOLS.create_identity.validate;
+ expect(validateArgs(bazaar.info.input.body.params.arguments)).toBe(true);
+ expect(bazaar.info.output.example.result.structuredContent.poll_tool).toBe('identity_status');
+ const advertised = JSON.stringify(bazaar);
+ expect(advertised).not.toContain('validate_model');
+ for (const name of ['create_identity', 'identity_status', 'getting_started']) {
+ expect(advertised).toContain(name);
+ }
+ });
+
+ it('the 402 resource metadata keeps the okx tag inside the 5-tag Bazaar cap', async () => {
+ const res = makeRes();
+ await handler(
+ makeReq({
+ body: {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'create_identity', arguments: { agent_name: 'X', brief: 'a data agent' } },
+ },
+ }),
+ res,
+ );
+ const { resource } = JSON.parse(res.body);
+ expect(resource.serviceName).toBe('three.ws Agent Identity Studio');
+ expect(resource.tags.length).toBeLessThanOrEqual(5);
+ expect(resource.tags).toContain('okx');
+ });
+
it('identity_status is free — served anonymously, no 402', async () => {
const res = makeRes();
await handler(
diff --git a/tests/api/ops-endpoints.test.js b/tests/api/ops-endpoints.test.js
new file mode 100644
index 000000000..7e1544c8f
--- /dev/null
+++ b/tests/api/ops-endpoints.test.js
@@ -0,0 +1,208 @@
+// The three ops boards: /api/ops/health, /api/ops/money-health,
+// /api/ops/payment-outcomes.
+//
+// Three regression fences live here, one per defect these tests were written
+// against:
+//
+// 1. health's cron staleness windows were hand-set integers that drifted away
+// from the schedules in vercel.json. Three daily crons carried windows of 15
+// to 70 minutes, so they read as failing ~23 hours of every day and the board
+// could never answer ok:true. The windows are derived now, and the invariant
+// test below fails the moment a schedule changes without one.
+// 2. money-health ran its own auth gate accepting CRON_SECRET (the credential
+// the fund-moving crons carry) and a never-set ADMIN_TOKEN. It shares
+// authorizeOps with its neighbours now.
+// 3. money-health's activity probe swallowed every error, so a wrong column
+// name rendered as "no activity" forever. Only a missing table is silence.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+let authOk = true;
+vi.mock('../../api/_lib/ops-auth.js', () => ({
+ authorizeOps: vi.fn(async () => (authOk ? { ok: true, actor: 'ops-secret' } : { ok: false, actor: '' })),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+vi.mock('../../api/_lib/cache.js', () => ({
+ cacheGet: vi.fn(async () => null),
+ cacheSet: vi.fn(async () => {}),
+}));
+
+let sqlImpl = async () => [];
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (...args) => sqlImpl(...args),
+}));
+
+let settleHealthImpl = async () => ({ name: 'x402_settle', status: 'ok' });
+vi.mock('../../api/_lib/ops/x402-settle-health.js', () => ({
+ gatherX402SettleHealth: () => settleHealthImpl(),
+}));
+
+let ringWalletsImpl = async () => ({ wallets: [], sponsorRunway: null });
+vi.mock('../../api/_lib/x402/wallet-balance-monitor.js', () => ({
+ checkRingWallets: () => ringWalletsImpl(),
+}));
+
+const health = await import('../../api/ops/health.js');
+const { default: moneyHealthHandler, lastActivity } = await import('../../api/ops/money-health.js');
+const { default: paymentOutcomesHandler } = await import('../../api/ops/payment-outcomes.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this.writableEnded = true; this._body = body; },
+ };
+}
+
+async function call(handler, url, { method = 'GET', headers = {} } = {}) {
+ const res = makeRes();
+ await handler({ url, method, headers: { host: 'three.ws', ...headers }, query: {} }, res);
+ let body = null;
+ try { body = JSON.parse(res._body); } catch { /* non-JSON body */ }
+ return { res, body };
+}
+
+const MIN = 60 * 1000;
+
+beforeEach(() => {
+ authOk = true;
+ sqlImpl = async () => [];
+ settleHealthImpl = async () => ({ name: 'x402_settle', status: 'ok' });
+ ringWalletsImpl = async () => ({ wallets: [], sponsorRunway: null });
+});
+
+describe('cron staleness windows derived from vercel.json', () => {
+ it('measures a fixed-interval schedule at its interval', () => {
+ expect(health.cadenceMs('*/5 * * * *')).toBe(5 * MIN);
+ expect(health.deriveStaleAfterMs('*/5 * * * *')).toBe(5 * MIN * 1.5 + 30 * MIN);
+ });
+
+ it('measures an uneven schedule by its widest quiet stretch', () => {
+ // 09:00 and 17:00 daily: 8h apart one way, 16h the other. The window must
+ // clear the 16h gap or the cron reads as stale every single night.
+ expect(health.cadenceMs('0 9,17 * * *')).toBe(16 * 60 * MIN);
+ });
+
+ it('gives a daily cron a window longer than a day', () => {
+ // The exact defect: oracle-digest (0 8 * * *) and gmgn-seed (0 3 * * *)
+ // carried 70 minutes, dead-man-switch (0 5 * * *) carried 15.
+ const daily = health.deriveStaleAfterMs('0 8 * * *');
+ expect(daily).toBeGreaterThan(24 * 60 * MIN);
+ });
+
+ it('falls back to a documented default when a schedule cannot be parsed', () => {
+ expect(health.cadenceMs('every other tuesday')).toBeNull();
+ expect(health.deriveStaleAfterMs('every other tuesday')).toBe(70 * MIN);
+ expect(health.deriveStaleAfterMs(null)).toBe(70 * MIN);
+ });
+
+ it('resolves a real schedule and a window wider than the cadence for every cron watched', () => {
+ for (const cron of health.CRONS) {
+ // A null schedule means the cron was renamed or dropped from
+ // vercel.json and this board is now watching a heartbeat nobody writes.
+ expect(cron.schedule, `${cron.id} has no schedule in vercel.json`).toBeTruthy();
+ expect(
+ cron.stale_after_ms,
+ `${cron.id} would read stale before its next run`,
+ ).toBeGreaterThan(health.cadenceMs(cron.schedule));
+ }
+ });
+});
+
+describe('GET /api/ops/health', () => {
+ it('rejects a non-GET method with an Allow header', async () => {
+ const { res } = await call(health.default, '/api/ops/health', { method: 'POST' });
+ expect(res.statusCode).toBe(405);
+ expect(String(res.getHeader('allow'))).toContain('GET');
+ });
+
+ it('refuses an unauthorized caller before running any probe', async () => {
+ authOk = false;
+ const { res, body } = await call(health.default, '/api/ops/health');
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+});
+
+describe('GET /api/ops/money-health', () => {
+ it('refuses an unauthorized caller', async () => {
+ authOk = false;
+ const { res, body } = await call(moneyHealthHandler, '/api/ops/money-health');
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('reports per-subsystem verdicts and real last-activity', async () => {
+ const activityMs = Date.now() - 3 * MIN;
+ sqlImpl = async (first) => {
+ // Tagged-template call: the grouped verdict query.
+ if (Array.isArray(first)) {
+ return [{ source: 'ring_facilitator_settle', critical: 2, open_total: 5, last_checked: '2026-08-14T00:00:00.000Z' }];
+ }
+ // Plain-string call: an activity probe.
+ return [{ ms: activityMs }];
+ };
+ const { res, body } = await call(moneyHealthHandler, '/api/ops/money-health');
+ expect(res.statusCode).toBe(200);
+ expect(body.overall).toBe('critical');
+ const ring = body.subsystems.find((s) => s.key === 'x402_ring');
+ expect(ring.status).toBe('critical');
+ expect(ring.open_critical).toBe(2);
+ expect(ring.open_warn).toBe(3);
+ expect(ring.minutes_since_activity).toBe(3);
+ });
+
+ it('reads ok when nothing is open', async () => {
+ const { body } = await call(moneyHealthHandler, '/api/ops/money-health');
+ expect(body.overall).toBe('ok');
+ expect(body.subsystems.every((s) => s.status === 'ok')).toBe(true);
+ });
+});
+
+describe('money-health activity probe', () => {
+ it('returns the newest timestamp in the log', async () => {
+ sqlImpl = async () => [{ ms: 1786673438240 }];
+ expect(await lastActivity('x402_self_facilitator_log', 'ts')).toBe(1786673438240);
+ });
+
+ it('treats a table this deployment has not created as silence', async () => {
+ sqlImpl = async () => { throw new Error('relation "x402_self_facilitator_log" does not exist'); };
+ expect(await lastActivity('x402_self_facilitator_log', 'ts')).toBeNull();
+ });
+
+ it('rethrows a wrong column instead of reporting no activity', async () => {
+ // The defect: `created_at` on a table stamped `ts` threw, was swallowed,
+ // and a ring settling thousands of payments a day rendered as idle.
+ sqlImpl = async () => { throw new Error('column "created_at" does not exist'); };
+ await expect(lastActivity('x402_self_facilitator_log', 'created_at')).rejects.toThrow(/column "created_at"/);
+ });
+});
+
+describe('GET /api/ops/payment-outcomes', () => {
+ it('refuses an unauthorized caller', async () => {
+ authOk = false;
+ const { res, body } = await call(paymentOutcomesHandler, '/api/ops/payment-outcomes');
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('keeps the surviving panels when one panel fails', async () => {
+ // An RPC outage is exactly when the settle panels matter most, so a dead
+ // sponsor read must not blank the inbound ledger.
+ ringWalletsImpl = async () => { throw new Error('rpc unreachable'); };
+ sqlImpl = async () => [{ event_type: 'payment_settled', h1: 1, h3: 2, h24: 9 }];
+ const { res, body } = await call(paymentOutcomesHandler, '/api/ops/payment-outcomes');
+ expect(res.statusCode).toBe(200);
+ expect(body.sponsor.error).toBe('rpc unreachable');
+ expect(body.inbound.windows['24h'].settled).toBe(9);
+ expect(body.ring_settle.status).toBe('ok');
+ });
+});
diff --git a/tests/api/portfolio-action.test.js b/tests/api/portfolio-action.test.js
new file mode 100644
index 000000000..f65afb428
--- /dev/null
+++ b/tests/api/portfolio-action.test.js
@@ -0,0 +1,297 @@
+// api/portfolio/[action].js — the dispatcher behind /api/portfolio/{summary,
+// history,asset,send}.
+//
+// Pins the boundaries an August 2026 endpoint audit found unguarded:
+// * `?days=abc` reached Postgres as `NaN days` and surfaced as a 500 with a
+// support ref, and reached CoinGecko as `days=NaN` on /asset.
+// * an amount that truncates to zero base units signed and broadcast a
+// transfer that moved nothing and still burned a fee.
+// * /asset answered `symbol: "SOL"` for an unknown Solana mint.
+// * /asset went blank (`market: null`) whenever CoinGecko throttled our
+// egress IP, instead of falling through to the platform's price lanes.
+//
+// The upstreams (DB, RPC, CoinGecko, the price-fallback lanes) are stubbed at
+// their module boundary; everything else in the handler runs for real.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { makeReq, makeRes } from '../_helpers/monetization.js';
+
+const authState = { session: null };
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ isSameSiteOrigin: vi.fn(() => true),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+
+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ walletRead: vi.fn(async () => ({ success: true })),
+ strict: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const sqlState = { queries: [], agent: null, snapshots: [] };
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ const q = (typeof strings === 'string' ? strings : strings.join('?')).toLowerCase();
+ sqlState.queries.push({ q, values });
+ if (/from portfolio_snapshots/.test(q)) return sqlState.snapshots;
+ if (/from agent_identities/.test(q)) return sqlState.agent ? [sqlState.agent] : [];
+ return [];
+ }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: () => false,
+}));
+
+const balanceState = { byAddress: {} };
+vi.mock('../../api/_lib/balances.js', () => ({
+ getBalances: vi.fn(async ({ address }) => balanceState.byAddress[address] || { native: { symbol: 'SOL', amount: 0, usd: 0 }, tokens: [] }),
+ walletUsdTotal: vi.fn((bal) => Number(bal?.native?.usd || 0) + (bal?.tokens || []).reduce((s, t) => s + Number(t.usd || 0), 0)),
+ invalidateBalances: vi.fn(),
+}));
+
+vi.mock('../../src/solana/sns.js', () => ({
+ reverseLookupAddress: vi.fn(async () => null),
+ resolveSolanaRecipient: vi.fn(async (r) => ({ address: r, resolved_from: null })),
+}));
+
+// CoinGecko is the throttled upstream the fallback lanes exist for, so these
+// cases run with it failing unless a test opts in.
+const geckoState = { meta: null, chart: null, fail: true };
+vi.mock('../../api/_lib/coingecko.js', () => ({
+ geckoFetch: vi.fn(async (path) => {
+ if (geckoState.fail) throw Object.assign(new Error('CoinGecko 429'), { status: 429 });
+ return /market_chart/.test(path) ? geckoState.chart : geckoState.meta;
+ }),
+ htmlToText: (s) => String(s || ''),
+}));
+
+const priceState = { sol: 0, solChange: null, token: null, coin: null };
+vi.mock('../../api/_lib/sol-price.js', () => ({
+ solPriceUsd: vi.fn(async () => priceState.sol),
+ solChange24hPct: vi.fn(async () => priceState.solChange),
+}));
+vi.mock('../../api/_lib/market/token-market.js', () => ({
+ fetchTokenMarketData: vi.fn(async () => priceState.token),
+}));
+vi.mock('../../api/_lib/market-fallbacks.js', () => ({
+ fetchCoinPriceUsdOrNull: vi.fn(async () => priceState.coin),
+}));
+vi.mock('../../src/shared/failover-fetch.js', () => ({
+ fetchFirstOrNull: vi.fn(async () => priceState.coin),
+}));
+
+// The signing path must never reach a real RPC or a real key.
+const sendState = { signed: [], lamports: null, keyAudit: null };
+vi.mock('../../api/_lib/agent-wallet.js', () => ({
+ recoverAgentKey: vi.fn(async (_k, audit) => {
+ sendState.keyAudit = audit;
+ return '0x' + '11'.repeat(32);
+ }),
+ recoverSolanaAgentKeypair: vi.fn(async () => {
+ const { Keypair } = await import('@solana/web3.js');
+ return Keypair.generate();
+ }),
+}));
+vi.mock('../../api/_lib/solana/connection.js', () => ({
+ solanaConnection: vi.fn(() => ({
+ getLatestBlockhash: async () => ({ blockhash: '11111111111111111111111111111111' }),
+ getParsedAccountInfo: async () => ({ value: { data: { parsed: { info: { decimals: 6 } } } } }),
+ getAccountInfo: async () => ({ lamports: 1 }),
+ sendRawTransaction: async (raw) => {
+ sendState.signed.push(raw);
+ return 'sig-' + sendState.signed.length;
+ },
+ })),
+}));
+vi.mock('../../api/_lib/evm/rpc.js', () => ({ evmFallbackProvider: vi.fn(async () => ({})) }));
+vi.mock('../../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
+
+const { default: handler } = await import('../../api/portfolio/[action].js');
+
+const USER = { id: 'user-portfolio-1' };
+const AGENT_ID = '00000000-0000-4000-8000-00000000abcd';
+const SOL_WALLET = 'So11111111111111111111111111111111111111112';
+
+function res() {
+ return makeRes();
+}
+function body(r) {
+ return JSON.parse(r.body);
+}
+
+async function get(path, query) {
+ const r = res();
+ await handler(makeReq({ method: 'GET', url: path, query }), r);
+ return r;
+}
+
+async function send(payload) {
+ const r = res();
+ await handler(
+ makeReq({ method: 'POST', url: '/api/portfolio/send', query: { action: 'send' }, body: payload, headers: { origin: 'https://three.ws' } }),
+ r,
+ );
+ return r;
+}
+
+beforeEach(() => {
+ authState.session = USER;
+ sqlState.queries = [];
+ sqlState.agent = null;
+ sqlState.snapshots = [];
+ balanceState.byAddress = {};
+ geckoState.fail = true;
+ geckoState.meta = null;
+ geckoState.chart = null;
+ priceState.sol = 0;
+ priceState.solChange = null;
+ priceState.token = null;
+ priceState.coin = null;
+ sendState.signed = [];
+ sendState.keyAudit = null;
+});
+
+describe('dispatcher + auth', () => {
+ it('404s an unknown action', async () => {
+ const r = await get('/api/portfolio/nope', { action: 'nope' });
+ expect(r.statusCode).toBe(404);
+ expect(body(r).error).toBe('not_found');
+ });
+
+ it('401s every action without a session', async () => {
+ authState.session = null;
+ for (const action of ['summary', 'history', 'asset']) {
+ const r = await get(`/api/portfolio/${action}`, { action });
+ expect(r.statusCode).toBe(401);
+ expect(body(r).error).toBe('unauthorized');
+ }
+ const posted = await send({ agent_id: AGENT_ID, chain: 'solana', asset: 'native', recipient: SOL_WALLET, amount: '1' });
+ expect(posted.statusCode).toBe(401);
+ expect(body(posted).error).toBe('unauthorized');
+ });
+
+ it('405s a GET on the write action', async () => {
+ const r = await get('/api/portfolio/send', { action: 'send' });
+ expect(r.statusCode).toBe(405);
+ });
+});
+
+describe('days window', () => {
+ it('rejects a non-numeric window instead of handing Postgres NaN', async () => {
+ const r = await get('/api/portfolio/history?days=abc', { action: 'history' });
+ expect(r.statusCode).toBe(400);
+ expect(body(r).error).toBe('validation_error');
+ // The malformed value must never reach the database.
+ expect(sqlState.queries.some((c) => /portfolio_snapshots/.test(c.q))).toBe(false);
+ });
+
+ it('rejects a fractional window on /asset too', async () => {
+ const r = await get('/api/portfolio/asset?chain=solana&id=native&days=1.5', { action: 'asset' });
+ expect(r.statusCode).toBe(400);
+ expect(body(r).error).toBe('validation_error');
+ });
+
+ it('defaults when absent and clamps to 1..365', async () => {
+ expect(body(await get('/api/portfolio/history', { action: 'history' })).days).toBe(90);
+ expect(body(await get('/api/portfolio/history?days=0', { action: 'history' })).days).toBe(1);
+ expect(body(await get('/api/portfolio/history?days=9999', { action: 'history' })).days).toBe(365);
+ });
+});
+
+describe('asset pricing', () => {
+ it('prices native SOL from the SOL spot lane when CoinGecko is throttled', async () => {
+ priceState.sol = 42.5;
+ priceState.solChange = -1.25;
+ const r = await get('/api/portfolio/asset?chain=solana&id=native', { action: 'asset' });
+ expect(r.statusCode).toBe(200);
+ const b = body(r);
+ expect(b.market.price_usd).toBe(42.5);
+ expect(b.market.change_24h_pct).toBe(-1.25);
+ expect(b.symbol).toBe('SOL');
+ });
+
+ it('prices an SPL mint from the token-market cascade, and revalues holdings with it', async () => {
+ priceState.token = { price_usd: 2, price_change_24h: 10, market_cap: 1000, volume_24h: 50 };
+ balanceState.byAddress[SOL_WALLET] = {
+ native: { symbol: 'SOL', amount: 0, usd: 0 },
+ tokens: [{ mint: 'MINT111', symbol: 'THREE', decimals: 6, amount: 5, usd: 1 }],
+ };
+ sqlState.agent = { id: AGENT_ID, name: 'A', wallet_address: null, chain_id: null, meta: { solana_address: SOL_WALLET } };
+ const r = await get('/api/portfolio/asset?chain=solana&id=MINT111', { action: 'asset' });
+ const b = body(r);
+ expect(b.market.price_usd).toBe(2);
+ expect(b.market.market_cap_usd).toBe(1000);
+ // 5 tokens at $2 beats the $1 the balance provider guessed.
+ expect(b.total_usd).toBe(10);
+ expect(b.unit_price_usd).toBe(2);
+ });
+
+ it('labels an unpriceable mint with a short address, never the chain coin', async () => {
+ const r = await get('/api/portfolio/asset?chain=solana&id=THREEsynthetic1111111111111111111111111111', { action: 'asset' });
+ const b = body(r);
+ expect(b.market).toBeNull();
+ expect(b.symbol).not.toBe('SOL');
+ expect(b.symbol).toBe('THRE..1111');
+ });
+
+ it('validates chain and id before anything else', async () => {
+ expect((await get('/api/portfolio/asset?chain=bitcoin&id=native', { action: 'asset' })).statusCode).toBe(400);
+ expect((await get('/api/portfolio/asset?chain=solana', { action: 'asset' })).statusCode).toBe(400);
+ });
+});
+
+describe('send', () => {
+ const base = { agent_id: AGENT_ID, chain: 'solana', asset: 'native', recipient: SOL_WALLET };
+
+ it('rejects a malformed body with a 400 and never loads an agent', async () => {
+ const r = await send({ ...base, agent_id: 'not-a-uuid', amount: '1' });
+ expect(r.statusCode).toBe(400);
+ expect(body(r).error).toBe('validation_error');
+ expect(sqlState.queries.some((c) => /from agent_identities/.test(c.q))).toBe(false);
+ });
+
+ it('404s an agent the caller does not own', async () => {
+ sqlState.agent = null;
+ const r = await send({ ...base, amount: '1' });
+ expect(r.statusCode).toBe(404);
+ expect(body(r).error).toBe('not_found');
+ });
+
+ it('refuses an amount that truncates to zero lamports, without signing', async () => {
+ sqlState.agent = { id: AGENT_ID, name: 'A', wallet_address: null, chain_id: null, meta: { encrypted_solana_secret: 'enc' } };
+ const r = await send({ ...base, amount: '0.0000000001' });
+ expect(r.statusCode).toBe(400);
+ expect(body(r).error).toBe('validation_error');
+ expect(sendState.signed).toHaveLength(0);
+ });
+
+ it('signs and broadcasts a real amount', async () => {
+ sqlState.agent = { id: AGENT_ID, name: 'A', wallet_address: null, chain_id: null, meta: { encrypted_solana_secret: 'enc' } };
+ const r = await send({ ...base, amount: '0.25' });
+ expect(r.statusCode).toBe(200);
+ expect(body(r).tx_hash).toBe('sig-1');
+ expect(sendState.signed).toHaveLength(1);
+ });
+
+ it('409s an agent with no key for the requested chain', async () => {
+ sqlState.agent = { id: AGENT_ID, name: 'A', wallet_address: '0x' + '1'.repeat(40), chain_id: 8453, meta: {} };
+ const r = await send({ ...base, chain: 'evm', recipient: '0x' + '2'.repeat(40), amount: '1' });
+ expect(r.statusCode).toBe(409);
+ expect(body(r).error).toBe('no_key');
+ });
+
+ it('attributes the EVM key use to the signed-in owner', async () => {
+ sqlState.agent = { id: AGENT_ID, name: 'A', wallet_address: '0x' + '1'.repeat(40), chain_id: 8453, meta: { encrypted_wallet_key: 'enc' } };
+ // The ethers Wallet has no provider transport here, so the broadcast fails;
+ // the audit metadata is recorded before that, which is what this pins.
+ await send({ ...base, chain: 'evm', recipient: '0x' + '2'.repeat(40), amount: '1' });
+ expect(sendState.keyAudit?.userId).toBe(USER.id);
+ expect(sendState.keyAudit?.agentId).toBe(AGENT_ID);
+ });
+});
diff --git a/tests/ghost-copy.test.js b/tests/ghost-copy.test.js
index 4879d7657..05d23ad5a 100644
--- a/tests/ghost-copy.test.js
+++ b/tests/ghost-copy.test.js
@@ -66,6 +66,19 @@ describe('buildGhostSubscription', () => {
expect(buildGhostSubscription({}).ok).toBe(false);
});
+ it('rejects an unrecognized sizing rule instead of silently replaying a different one', () => {
+ // A caller asking for a rule we do not have used to get a `fixed` replay
+ // with no signal that the request was dropped, which makes the whole
+ // simulation answer a question nobody asked.
+ const bad = buildGhostSubscription({ budgetSol: 1, sizing_rule: 'martingale' });
+ expect(bad.ok).toBe(false);
+ expect(bad.error).toMatch(/fixed.*multiplier/);
+ // The two real rules, and the absent-means-default case, still pass.
+ expect(buildGhostSubscription({ budgetSol: 1, sizing_rule: 'fixed' }).value.sizing_rule).toBe('fixed');
+ expect(buildGhostSubscription({ budgetSol: 1, sizing_rule: 'multiplier' }).value.sizing_rule).toBe('multiplier');
+ expect(buildGhostSubscription({ budgetSol: 1, sizing_rule: undefined }).value.sizing_rule).toBe('fixed');
+ });
+
it('honors explicit overrides over the derived defaults', () => {
const { value } = buildGhostSubscription({ budgetSol: 2, fixed_sol: 0.05, max_open_copies: 2 });
expect(value.fixed_sol).toBe(0.05);
diff --git a/tests/launch-mark-enforcement.test.js b/tests/launch-mark-enforcement.test.js
index b4686afde..936028507 100644
--- a/tests/launch-mark-enforcement.test.js
+++ b/tests/launch-mark-enforcement.test.js
@@ -7,6 +7,8 @@
// 4. THREE_WS_MARK_ENFORCE=0 → legacy path (no mark required)
// 5. launch-agent, no mint supplied → server grinds a 3ws mint
// 6. launch-agent, unmarked pair → 400 unbranded_mint
+// 7. launch-agent, cross-site POST → 403, before any keypair or chain work
+// 8. launch-agent, no session → 401
//
// All network / Solana RPC calls are mocked. The vanity grinder is also mocked
// so tests are deterministic and fast (the real grind is covered by
@@ -17,11 +19,12 @@ import { Readable } from 'node:stream';
import { hasThreeWsMark } from '../src/solana/vanity/brand.js';
// ── Auth ─────────────────────────────────────────────────────────────────────
-const authState = { session: null };
+const authState = { session: null, sameSite: true };
vi.mock('../api/_lib/auth.js', () => ({
getSessionUser: vi.fn(async () => authState.session),
authenticateBearer: vi.fn(async () => null),
extractBearer: vi.fn(() => null),
+ isSameSiteOrigin: vi.fn(() => authState.sameSite),
}));
// ── SQL ──────────────────────────────────────────────────────────────────────
@@ -159,10 +162,13 @@ vi.mock('@pump-fun/pump-sdk', () => ({
}));
// ── agent-pumpfun — Solana connection + keypair loader ────────────────────────
-const agentPumpfunState = { connection: null, loadResult: null };
+const agentPumpfunState = { connection: null, loadResult: null, loadCalls: 0 };
vi.mock('../api/_lib/agent-pumpfun.js', () => ({
solanaConnection: vi.fn(() => agentPumpfunState.connection),
- loadAgentForSigning: vi.fn(async () => agentPumpfunState.loadResult),
+ loadAgentForSigning: vi.fn(async () => {
+ agentPumpfunState.loadCalls++;
+ return agentPumpfunState.loadResult;
+ }),
}));
// ── Request/response helpers (mirror tests/api/pump.test.js) ─────────────────
@@ -205,10 +211,12 @@ function pumpAction(action) {
function resetAll() {
authState.session = null;
+ authState.sameSite = true;
sqlState.queue = [];
sqlState.calls = [];
agentPumpfunState.connection = null;
agentPumpfunState.loadResult = null;
+ agentPumpfunState.loadCalls = 0;
}
// ── Shared fixtures ───────────────────────────────────────────────────────────
@@ -398,4 +406,35 @@ describe('POST /api/pump/launch-agent — brand-mark enforcement', () => {
expect(res.statusCode).toBe(400);
expect(json.error).toBe('unbranded_mint');
});
+
+ // launch-agent signs and broadcasts with the agent's CUSTODIAL keypair: the
+ // caller supplies no signature, so a session cookie alone was enough to mint a
+ // coin and spend the agent's SOL from any origin. The cookie path must prove
+ // same-site intent before it reaches any of that.
+ it('403s a cross-site POST before it touches the agent keypair or the chain', async () => {
+ authState.session = { id: 'user-1' };
+ authState.sameSite = false;
+ sqlState.queue = [[{ id: 'agent-1', name: 'Foo' }]];
+
+ const { res, json } = await invoke(pumpAction('launch-agent'), {
+ method: 'POST', url: '/api/pump/launch-agent',
+ body: baseAgentBody,
+ });
+
+ expect(res.statusCode).toBe(403);
+ expect(json.error).toBe('forbidden');
+ // Nothing was resolved, loaded, or queried on the caller's behalf.
+ expect(sqlState.calls).toHaveLength(0);
+ expect(agentPumpfunState.loadCalls).toBe(0);
+ });
+
+ it('still 401s an unauthenticated POST', async () => {
+ authState.session = null;
+ const { res, json } = await invoke(pumpAction('launch-agent'), {
+ method: 'POST', url: '/api/pump/launch-agent',
+ body: baseAgentBody,
+ });
+ expect(res.statusCode).toBe(401);
+ expect(json.error).toBe('unauthorized');
+ });
});
diff --git a/tests/monetization-service.test.js b/tests/monetization-service.test.js
index 0157d93d4..364f81a7d 100644
--- a/tests/monetization-service.test.js
+++ b/tests/monetization-service.test.js
@@ -1115,6 +1115,57 @@ describe('withdrawals endpoint', () => {
expect(body.error).toBe('insufficient_balance');
});
+ it('pays out on Solana even when an EVM wallet was saved more recently', async () => {
+ const { agent, session } = createTestAgent();
+ const EVM_ADDRESS = '0x1111111111111111111111111111111111111111';
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
+ // Ordered newest-first, so the EVM row leads. Taking it would price the
+ // withdrawal in Base USDC and strand the Solana balance at zero.
+ sqlState.queue.push([
+ { address: EVM_ADDRESS, chain: 'base', preferred_network: 'solana' },
+ { address: SOL_ADDRESS, chain: 'solana', preferred_network: 'solana' },
+ ]);
+ queueBalance({ earned: 5_000_000n });
+ sqlState.queue.push([]); // advisory lock
+ sqlState.queue.push([
+ {
+ id: 'wd-1', agent_id: agent.id, amount: 4_000_000n, currency_mint: USDC_MINT,
+ chain: 'solana', to_address: SOL_ADDRESS, status: 'pending', tx_signature: null,
+ created_at: '2026-06-18T00:00:00Z', updated_at: '2026-06-18T00:00:00Z',
+ },
+ ]);
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'POST',
+ url: '/api/monetization/withdrawals',
+ body: { agent_id: agent.id, amount_usdc: 4 },
+ });
+
+ expect(status).toBe(201);
+ expect(body.withdrawal.chain).toBe('solana');
+ expect(body.withdrawal.destination_address).toBe(SOL_ADDRESS);
+ expect(body.withdrawal.currency_mint).toBe(USDC_MINT);
+ });
+
+ it('refuses an explicit network the user has no wallet on, instead of paying out elsewhere', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
+ sqlState.queue.push([{ address: SOL_ADDRESS, chain: 'solana', preferred_network: 'solana' }]);
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'POST',
+ url: '/api/monetization/withdrawals',
+ body: { agent_id: agent.id, amount_usdc: 5, network: 'base' },
+ });
+
+ expect(status).toBe(422);
+ expect(body.error).toBe('no_payout_wallet');
+ });
+
it("returns 403 against someone else's agent", async () => {
const { agent } = createTestAgent();
authState.session = { id: 'user-1' };
diff --git a/tests/og-cards.test.js b/tests/og-cards.test.js
new file mode 100644
index 000000000..9639b62c9
--- /dev/null
+++ b/tests/og-cards.test.js
@@ -0,0 +1,296 @@
+// Coverage for the three dynamic Open Graph card renderers under api/og/.
+//
+// These endpoints are the face of every shared three.ws link, and they have one
+// hard contract in common: a crawler must ALWAYS get an image. Not one of a
+// missing id, an unknown id, a hostile id, or a dead upstream may produce a 5xx,
+// an HTML error page, or a broken-image box. The second contract is that nothing
+// secret and nothing private may reach the pixels.
+//
+// Each card exposes its pure renderer via __testInternals precisely so the SVG
+// can be asserted without a database, a chain read, or a CDN fetch; the handler
+// paths that need no network (validation, visibility, fallback) are driven end to
+// end against the real default export.
+
+import { describe, it, expect, beforeEach } from 'vitest';
+
+import sealedDropHandler, { __testInternals as sealedInternals } from '../api/og/sealed-drop.js';
+import agentHandler, { renderCard as renderAgentCard, __testInternals as agentInternals } from '../api/og/agent.js';
+import { __testInternals as badgeInternals } from '../api/og/three-token-badge.js';
+import { createDrop, __resetMemoryStore } from '../api/_lib/sealed-drop-store.js';
+
+// Minimal req/res pair that captures exactly what a crawler would see.
+async function invoke(handler, url) {
+ const chunks = [];
+ const headers = {};
+ let statusCode = 200;
+ const res = {
+ setHeader(k, v) { headers[k.toLowerCase()] = v; },
+ getHeader(k) { return headers[k.toLowerCase()]; },
+ end(buf) { if (buf) chunks.push(Buffer.from(buf)); },
+ get statusCode() { return statusCode; },
+ set statusCode(v) { statusCode = v; },
+ };
+ await handler({ method: 'GET', url, headers: { host: 'three.ws' } }, res);
+ return { body: Buffer.concat(chunks).toString('utf8'), headers, statusCode };
+}
+
+// An SVG a social crawler will actually rasterize: correct root element, the
+// 1200x630 unfurl box every platform crops to, and a closed document.
+function expectValidCard(svg) {
+ expect(svg.startsWith('<svg xmlns="http://www.w3.org/2000/svg"')).toBe(true);
+ expect(svg).toContain('width="1200"');
+ expect(svg).toContain('height="630"');
+ expect(svg.trimEnd().endsWith('</svg>')).toBe(true);
+ // Nothing executable ever belongs in an image served to a crawler.
+ expect(svg).not.toMatch(/<script|<foreignObject|javascript:/i);
+}
+
+describe('og/sealed-drop', () => {
+ beforeEach(() => { __resetMemoryStore(); });
+
+ // The record shape api/vanity/drops.js stores, secrets included, so the test
+ // proves the card reads the public projection rather than the raw record.
+ const SEALED_ENVELOPE = 'c2VhbGVkLWNpcGhlcnRleHQtbmV2ZXItcmVuZGVyZWQ';
+ const CLAIM_TOKEN_HASH = 'f'.repeat(64);
+ const DROP_ID = 'a1b2c3d4e5f607182930a1b2';
+
+ async function seedDrop(over = {}) {
+ return createDrop({
+ id: DROP_ID,
+ protocol: 'three-drop/v1',
+ address: 'THREEsynthetic1111111111111111111111111111',
+ asset: 'THREE',
+ amount: 250,
+ amountAtomics: '250000000',
+ network: 'solana',
+ sealMode: 'claim-time',
+ status: 'funded',
+ theme: 'birthday',
+ senderLabel: 'Ada',
+ vanity: { prefix: 'THREE' },
+ createdAt: 1_760_000_000_000,
+ expiresAt: 1_760_600_000_000,
+ fundingConfirmed: true,
+ // Secrets that must never reach the card:
+ sealedEnvelope: SEALED_ENVELOPE,
+ claimTokenHash: CLAIM_TOKEN_HASH,
+ ...over,
+ });
+ }
+
+ it('renders a real funded drop from its public projection, and never a secret', async () => {
+ await seedDrop();
+ const { statusCode, headers, body } = await invoke(sealedDropHandler, `/api/og/sealed-drop?id=${DROP_ID}`);
+
+ expect(statusCode).toBe(200);
+ expect(headers['content-type']).toBe('image/svg+xml; charset=utf-8');
+ expect(headers['cache-control']).toContain('s-maxage=');
+ expectValidCard(body);
+
+ // Real fields off the stored record.
+ expect(body).toContain('250 $THREE');
+ expect(body).toContain('from Ada');
+ expect(body).toContain('Happy birthday');
+ expect(body).toContain('SEALED · UNCLAIMED');
+ expect(body).toContain('vanity THREE…');
+
+ // The privacy boundary.
+ expect(body).not.toContain(SEALED_ENVELOPE);
+ expect(body).not.toContain(CLAIM_TOKEN_HASH);
+ expect(body).not.toContain('claimTokenHash');
+ });
+
+ it('reflects a claimed drop in the status line', async () => {
+ await seedDrop({ status: 'claimed', claimedAt: 1_760_100_000_000 });
+ const { body } = await invoke(sealedDropHandler, `/api/og/sealed-drop?id=${DROP_ID}`);
+ expect(body).toContain('CLAIMED');
+ expect(body).not.toContain('UNCLAIMED');
+ });
+
+ // Failure path: crawlers hitting a stale, mistyped, or hostile link.
+ it.each([
+ ['no id', '/api/og/sealed-drop'],
+ ['malformed id', '/api/og/sealed-drop?id=not-a-drop-id'],
+ ['unknown but well-formed id', '/api/og/sealed-drop?id=0123456789abcdef01234567'],
+ ['injection attempt', '/api/og/sealed-drop?id=%3Cscript%3Ealert(1)%3C%2Fscript%3E'],
+ ])('still serves a branded card for %s', async (_label, url) => {
+ const { statusCode, headers, body } = await invoke(sealedDropHandler, url);
+ expect(statusCode).toBe(200);
+ expect(headers['content-type']).toBe('image/svg+xml; charset=utf-8');
+ expectValidCard(body);
+ expect(body).toContain('A sealed gift');
+ });
+
+ it('escapes hostile record text instead of emitting markup', () => {
+ const svg = sealedInternals.buildCard({
+ status: 'funded',
+ amount: 1,
+ asset: 'SOL',
+ address: 'THREEsynthetic1111111111111111111111111111',
+ theme: 'default',
+ senderLabel: '"><script>alert(1)</script>',
+ vanity: null,
+ });
+ expectValidCard(svg);
+ expect(svg).toContain('&lt;script&gt;');
+ });
+
+ it('shortens a full base58 address and leaves a short one alone', () => {
+ const { shortAddr } = sealedInternals;
+ expect(shortAddr('THREEsynthetic1111111111111111111111111111')).toBe('THREEsyn…111111');
+ expect(shortAddr('short')).toBe('short');
+ expect(shortAddr(null)).toBe('');
+ });
+});
+
+describe('og/three-token-badge', () => {
+ const FULL = {
+ price: 0.001843, change24h: 13.61, marketCap: 1_843_105,
+ volume24h: 136_489.61, holders: 15_603, agents: 3140,
+ };
+
+ it('renders every live figure on the card', () => {
+ const svg = badgeInternals.renderCard(FULL);
+ expectValidCard(svg);
+ expect(svg).toContain('$THREE');
+ expect(svg).toContain('$0.001843');
+ expect(svg).toContain('+13.61%');
+ expect(svg).toContain('$1.84M'); // market cap
+ expect(svg).toContain('15,603'); // holders, the cell that used to be blank
+ expect(svg).toContain('$136.5K'); // 24h volume
+ expect(svg).toContain('3,140'); // on-chain agents
+ // The only coin this card may ever reference.
+ expect(svg).toContain('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump');
+ });
+
+ // Failure path: every upstream down. The card must degrade per-figure, never
+ // vanish, and never invent a number.
+ it('renders a complete branded card when every figure is unavailable', () => {
+ const svg = badgeInternals.renderCard({
+ price: null, change24h: null, marketCap: null,
+ volume24h: null, holders: null, agents: null,
+ });
+ expectValidCard(svg);
+ expect(svg).toContain('$THREE');
+ expect(svg).toContain('MARKET CAP');
+ expect(svg).toContain('HOLDERS');
+ // No change pill without a change datum, and no fabricated zeroes.
+ expect(svg).not.toMatch(/[▲▼]/);
+ expect(svg).not.toMatch(/<rect x="\d+" y="300"/);
+ expect(svg).not.toContain('$0.00');
+ });
+
+ it('formats a sub-cent price in plain decimal, never exponent notation', () => {
+ const { fmtPrice } = badgeInternals;
+ expect(fmtPrice(0.001843)).toBe('$0.001843');
+ expect(fmtPrice(0.00000001234)).not.toContain('e');
+ expect(fmtPrice(1234.5)).toBe('$1,234.50');
+ expect(fmtPrice(0.5)).toBe('$0.5000');
+ expect(fmtPrice(null)).toBe('-');
+ expect(fmtPrice(Number.NaN)).toBe('-');
+ });
+
+ it('keeps the 24h pill clear of the price at any magnitude', () => {
+ const { renderCard, heroTextWidth } = badgeInternals;
+ expect(heroTextWidth('$0.00000001234', 84)).toBeGreaterThan(heroTextWidth('$1.00', 84));
+ // A long price must not push the pill off the 1200px canvas.
+ const svg = renderCard({ ...FULL, price: 0.00000001234 });
+ const pillX = Number(/<rect x="(\d+)" y="300"/.exec(svg)?.[1]);
+ expect(pillX).toBeGreaterThan(0);
+ expect(pillX).toBeLessThan(1128);
+ });
+
+ it('compacts USD the way the token page does', () => {
+ const { fmtCompactUsd, fmtInt, fmtPct } = badgeInternals;
+ expect(fmtCompactUsd(1_843_105)).toBe('$1.84M');
+ expect(fmtCompactUsd(136_489.61)).toBe('$136.5K');
+ expect(fmtCompactUsd(2_400_000_000)).toBe('$2.40B');
+ expect(fmtCompactUsd(null)).toBe('-');
+ expect(fmtInt(15_603)).toBe('15,603');
+ expect(fmtInt(null)).toBe('-');
+ expect(fmtPct(-4.2)).toBe('-4.20%');
+ expect(fmtPct(null)).toBeNull();
+ });
+});
+
+describe('og/agent', () => {
+ const ROW = {
+ name: 'nova',
+ visibility: 'public',
+ thumbnail_key: null,
+ meta: { solana_address: '7bDyhXcwANT3FBKniiGbvgkc4divijBTRtS8oEBcnJdc' },
+ };
+ const ID = 'c080c68b-2aeb-4746-b739-41b30cbbf517';
+
+ it('renders a fully enriched wallet card', () => {
+ const svg = renderAgentCard({
+ id: ID,
+ row: { ...ROW, meta: { ...ROW.meta, solana_vanity_prefix: '7bDy' } },
+ solAddress: ROW.meta.solana_address,
+ balances: { tokens: [{ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', amount: 4200, usd: 7.7 }], usd: 7.7 },
+ rep: { tier: 'trusted', tierLabel: 'Trusted', score: 78.4, accent: '#a5b4fc' },
+ pnl: { sol: 1.25, wins: 3 },
+ tipsCount: 9,
+ achievements: { earned: [{ id: 'migrator', title: 'Serial Migrator', tier: 'gold' }], summary: { earnedCount: 4 } },
+ avatarData: null,
+ });
+
+ expectValidCard(svg);
+ expect(svg).toContain('nova');
+ expect(svg).toContain('✦ 7bDy…'); // vanity prefix highlighted
+ expect(svg).toContain('★ SERIAL MIGRATOR +3'); // headline badge + remainder
+ expect(svg).toContain('TRUSTED');
+ expect(svg).toContain('◆ $THREE'); // holder mark
+ expect(svg).toContain('+1.25 ◎'); // realized P&L
+ expect(svg).toContain(`three.ws/agent/${ID}`);
+ });
+
+ // Failure path: every enrichment timed out. The card still renders, and says
+ // "unknown" rather than "$0" for a balance it could not read.
+ it('renders with no enrichments at all', () => {
+ const svg = renderAgentCard({ id: ID, row: { ...ROW, meta: {} } });
+ expectValidCard(svg);
+ expect(svg).toContain('nova');
+ expect(svg).toContain('Wallet provisioning');
+ expect(svg).toContain('COMMON');
+ expect(svg).not.toContain('$THREE');
+ });
+
+ it('escapes a hostile agent name', () => {
+ const svg = renderAgentCard({ id: ID, row: { ...ROW, name: '<script>alert(1)</script>' } });
+ expectValidCard(svg);
+ expect(svg).toContain('&lt;script&gt;');
+ });
+
+ it('redirects a crawler to the static card for an unusable id, without touching the database', async () => {
+ for (const url of ['/api/og/agent', '/api/og/agent?id=not-a-uuid', "/api/og/agent?id=%27%20OR%201=1--"]) {
+ const { statusCode, headers } = await invoke(agentHandler, url);
+ expect(statusCode).toBe(302);
+ expect(headers.location).toMatch(/\/og-image\.png$/);
+ expect(headers['cache-control']).toBe('no-cache');
+ }
+ });
+
+ it('picks the migration badge over a higher tier, then the highest tier', () => {
+ const { headlineAchievement } = agentInternals;
+ expect(headlineAchievement([
+ { id: 'whale', title: 'Whale', tier: 'legendary' },
+ { id: 'graduate', title: 'Graduate', tier: 'bronze' },
+ ]).id).toBe('graduate');
+ expect(headlineAchievement([
+ { id: 'whale', title: 'Whale', tier: 'legendary' },
+ { id: 'starter', title: 'Starter', tier: 'bronze' },
+ ]).id).toBe('whale');
+ expect(headlineAchievement([])).toBeNull();
+ });
+
+ it('formats net worth the way the on-page wallet card does', () => {
+ const { fmtUsd } = agentInternals;
+ expect(fmtUsd(0)).toBe('$0');
+ expect(fmtUsd(0.004)).toBe('<$0.01');
+ expect(fmtUsd(7.7)).toBe('$7.70');
+ expect(fmtUsd(4200)).toBe('$4.2K');
+ expect(fmtUsd(2_400_000)).toBe('$2.4M');
+ expect(fmtUsd(null)).toBeNull();
+ });
+});
diff --git a/tests/onramp-link.test.js b/tests/onramp-link.test.js
new file mode 100644
index 000000000..c3b2305fd
--- /dev/null
+++ b/tests/onramp-link.test.js
@@ -0,0 +1,293 @@
+// GET /api/onramp/link: the fiat onramp checkout link handed to the "Add funds"
+// overlay (src/shared/add-funds.js), plus the CDP session-token module behind it.
+//
+// The two behaviours worth pinning are the contract with Coinbase (a hosted
+// checkout URL is only valid when it carries a freshly minted sessionToken) and
+// the promise that funding never hard-fails: if Coinbase is down or the CDP key
+// is rotated, the caller still gets a usable buy page instead of a 5xx.
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+let rlOk = true;
+let callerIp = '203.0.113.7';
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ clientIp: () => callerIp,
+ limits: {
+ onrampLinkIp: vi.fn(async () => ({
+ success: rlOk,
+ limit: 20,
+ remaining: rlOk ? 19 : 0,
+ reset: Date.now() + 300_000,
+ })),
+ },
+}));
+
+const generateJwtMock = vi.fn(async () => 'signed.jwt.value');
+vi.mock('@coinbase/cdp-sdk/auth', () => ({ generateJwt: (...a) => generateJwtMock(...a) }));
+
+const createTokenMock = vi.fn();
+vi.mock('../api/_lib/coinbase-onramp.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, createOnrampSessionToken: (...a) => createTokenMock(...a) };
+});
+
+const { default: handler } = await import('../api/onramp/link.js');
+const { isPublicIp, onrampClientIp, onrampConfigured, CoinbaseOnrampError } = await import(
+ '../api/_lib/coinbase-onramp.js'
+);
+const { createOnrampSessionToken } = await vi.importActual('../api/_lib/coinbase-onramp.js');
+
+const ADDRESS = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+function mkReq({ method = 'GET', query = '', headers = {} } = {}) {
+ return {
+ method,
+ url: `/api/onramp/link${query}`,
+ headers: { host: 'three.ws', ...headers },
+ socket: { remoteAddress: '203.0.113.7' },
+ };
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: undefined,
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(b) { this.body = b; this.writableEnded = true; },
+ };
+}
+
+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+beforeEach(() => {
+ rlOk = true;
+ callerIp = '203.0.113.7';
+ createTokenMock.mockReset();
+ generateJwtMock.mockClear();
+ vi.stubEnv('CDP_API_KEY_ID', '');
+ vi.stubEnv('CDP_API_KEY_SECRET', '');
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+});
+
+describe('GET /api/onramp/link', () => {
+ it('mints a session token and returns a hosted Coinbase checkout when CDP is configured', async () => {
+ vi.stubEnv('CDP_API_KEY_ID', 'key-id');
+ vi.stubEnv('CDP_API_KEY_SECRET', 'key-secret');
+ createTokenMock.mockResolvedValue('session-token-abc');
+
+ const res = mkRes();
+ await handler(mkReq({ query: `?address=${ADDRESS}&amount=50&asset=USDC` }), res);
+
+ expect(res.statusCode).toBe(200);
+ const body = parse(res);
+ expect(body.mode).toBe('coinbase-onramp');
+ expect(body.address).toBe(ADDRESS);
+ expect(body.amount).toBe(50);
+
+ const url = new URL(body.url);
+ expect(url.origin + url.pathname).toBe('https://pay.coinbase.com/buy/select-asset');
+ expect(url.searchParams.get('sessionToken')).toBe('session-token-abc');
+ expect(url.searchParams.get('defaultNetwork')).toBe('solana');
+ expect(url.searchParams.get('defaultAsset')).toBe('USDC');
+ expect(url.searchParams.get('presetFiatAmount')).toBe('50');
+ expect(url.searchParams.get('fiatCurrency')).toBe('USD');
+ // The deprecated pre-session-token parameters must never come back: Coinbase
+ // stopped honouring them, so a URL carrying them lands the buyer on an error.
+ expect(url.searchParams.get('appId')).toBeNull();
+ expect(url.searchParams.get('destinationWallets')).toBeNull();
+
+ // The destination wallet reaches Coinbase through the token call, not the URL.
+ expect(createTokenMock).toHaveBeenCalledWith({
+ address: ADDRESS,
+ blockchains: ['solana'],
+ assets: ['USDC'],
+ clientIp: '203.0.113.7',
+ });
+ });
+
+ it('binds the token to the SOL ticker when SOL is requested', async () => {
+ vi.stubEnv('CDP_API_KEY_ID', 'key-id');
+ vi.stubEnv('CDP_API_KEY_SECRET', 'key-secret');
+ createTokenMock.mockResolvedValue('session-token-sol');
+
+ const res = mkRes();
+ await handler(mkReq({ query: `?address=${ADDRESS}&asset=sol` }), res);
+
+ const body = parse(res);
+ expect(body.asset).toBe('SOL');
+ expect(createTokenMock.mock.calls[0][0].assets).toEqual(['SOL']);
+ expect(new URL(body.url).searchParams.get('defaultAsset')).toBe('SOL');
+ });
+
+ it('falls back to the Coinbase buy page (still 200) when the token call fails', async () => {
+ vi.stubEnv('CDP_API_KEY_ID', 'key-id');
+ vi.stubEnv('CDP_API_KEY_SECRET', 'key-secret');
+ createTokenMock.mockRejectedValue(
+ new CoinbaseOnrampError('onramp_rejected', 'CDP session token request returned 401'),
+ );
+
+ const res = mkRes();
+ await handler(mkReq({ query: `?address=${ADDRESS}` }), res);
+
+ expect(res.statusCode).toBe(200);
+ const body = parse(res);
+ expect(body.mode).toBe('coinbase-fallback');
+ expect(body.url).toBe('https://www.coinbase.com/price/usd-coin');
+ });
+
+ it('uses the fallback without calling CDP when no credentials are configured', async () => {
+ const res = mkRes();
+ await handler(mkReq({ query: `?address=${ADDRESS}&asset=SOL` }), res);
+
+ expect(parse(res)).toMatchObject({
+ mode: 'coinbase-fallback',
+ url: 'https://www.coinbase.com/price/solana',
+ asset: 'SOL',
+ });
+ expect(createTokenMock).not.toHaveBeenCalled();
+ });
+
+ it('clamps the preset amount and defaults an unparseable one', async () => {
+ const res = mkRes();
+ await handler(mkReq({ query: `?address=${ADDRESS}&amount=99999` }), res);
+ expect(parse(res).amount).toBe(500);
+
+ const res2 = mkRes();
+ await handler(mkReq({ query: `?address=${ADDRESS}&amount=abc` }), res2);
+ expect(parse(res2).amount).toBe(25);
+
+ const res3 = mkRes();
+ await handler(mkReq({ query: `?address=${ADDRESS}&amount=1` }), res3);
+ expect(parse(res3).amount).toBe(10);
+ });
+
+ it('rejects anything that is not a Solana public key', async () => {
+ for (const q of ['', `?address=`, '?address=nope', '?address=0x1234567890123456789012345678901234567890']) {
+ const res = mkRes();
+ await handler(mkReq({ query: q }), res);
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('invalid_address');
+ }
+ });
+
+ it('answers 405 to a non-GET method', async () => {
+ const res = mkRes();
+ await handler(mkReq({ method: 'POST', query: `?address=${ADDRESS}` }), res);
+ expect(res.statusCode).toBe(405);
+ expect(parse(res).error).toBe('method_not_allowed');
+ });
+
+ it('rate limits before it ever reaches Coinbase', async () => {
+ vi.stubEnv('CDP_API_KEY_ID', 'key-id');
+ vi.stubEnv('CDP_API_KEY_SECRET', 'key-secret');
+ rlOk = false;
+
+ const res = mkRes();
+ await handler(mkReq({ query: `?address=${ADDRESS}` }), res);
+
+ expect(res.statusCode).toBe(429);
+ expect(createTokenMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('createOnrampSessionToken', () => {
+ beforeEach(() => {
+ vi.stubEnv('CDP_API_KEY_ID', 'key-id');
+ vi.stubEnv('CDP_API_KEY_SECRET', 'key-secret');
+ });
+
+ it('posts the destination wallet to the CDP token API and returns the token', async () => {
+ const fetchMock = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ text: async () => JSON.stringify({ token: 'tok_live', channel_id: '' }),
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const token = await createOnrampSessionToken({
+ address: ADDRESS,
+ blockchains: ['solana'],
+ assets: ['USDC'],
+ clientIp: '203.0.113.7',
+ });
+
+ expect(token).toBe('tok_live');
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://api.developer.coinbase.com/onramp/v1/token');
+ expect(init.method).toBe('POST');
+ expect(init.headers.authorization).toBe('Bearer signed.jwt.value');
+ expect(JSON.parse(init.body)).toEqual({
+ addresses: [{ address: ADDRESS, blockchains: ['solana'] }],
+ assets: ['USDC'],
+ clientIp: '203.0.113.7',
+ });
+ // The JWT must be scoped to the exact method + host + path CDP verifies.
+ expect(generateJwtMock.mock.calls[0][0]).toMatchObject({
+ requestMethod: 'POST',
+ requestHost: 'api.developer.coinbase.com',
+ requestPath: '/onramp/v1/token',
+ });
+ });
+
+ it('throws a typed error when CDP rejects the request', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({
+ ok: false,
+ status: 401,
+ text: async () => 'Unauthorized',
+ })));
+
+ await expect(
+ createOnrampSessionToken({
+ address: ADDRESS,
+ blockchains: ['solana'],
+ clientIp: '203.0.113.7',
+ }),
+ ).rejects.toMatchObject({ code: 'onramp_rejected' });
+ });
+
+ it('refuses to call CDP at all when credentials are missing', async () => {
+ vi.stubEnv('CDP_API_KEY_ID', '');
+ vi.stubEnv('CDP_API_KEY_SECRET', '');
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(
+ createOnrampSessionToken({ address: ADDRESS, blockchains: ['solana'], clientIp: '203.0.113.7' }),
+ ).rejects.toMatchObject({ code: 'onramp_not_configured' });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('client IP handling', () => {
+ it('classifies routable and unroutable addresses', () => {
+ for (const ip of ['203.0.113.7', '8.8.8.8', '::ffff:8.8.8.8', '2606:4700::1111']) {
+ expect(isPublicIp(ip), ip).toBe(true);
+ }
+ for (const ip of ['10.1.2.3', '127.0.0.1', '192.168.1.9', '172.20.0.4', '169.254.1.1', '::1', 'fd00::1', '', 'not-an-ip']) {
+ expect(isPublicIp(ip), ip).toBe(false);
+ }
+ });
+
+ it('substitutes the documentation address when the caller IP is unroutable', () => {
+ callerIp = '127.0.0.1';
+ expect(onrampClientIp({ headers: {} })).toBe('192.0.2.1');
+ callerIp = '203.0.113.7';
+ expect(onrampClientIp({ headers: {} })).toBe('203.0.113.7');
+ });
+
+ it('reports configuration state from the CDP env pair', () => {
+ vi.stubEnv('CDP_API_KEY_ID', '');
+ vi.stubEnv('CDP_API_KEY_SECRET', '');
+ expect(onrampConfigured()).toBe(false);
+ vi.stubEnv('CDP_API_KEY_ID', 'key-id');
+ expect(onrampConfigured()).toBe(false);
+ vi.stubEnv('CDP_API_KEY_SECRET', 'key-secret');
+ expect(onrampConfigured()).toBe(true);
+ });
+});
diff --git a/tests/permissions-sdk-revocation.test.js b/tests/permissions-sdk-revocation.test.js
new file mode 100644
index 000000000..7af4815ea
--- /dev/null
+++ b/tests/permissions-sdk-revocation.test.js
@@ -0,0 +1,76 @@
+// The SDK's on-chain revocation check is the last gate before an agent honours a
+// delegation, and it was failing open twice over: it eth_call'd a selector
+// (0xa1a5bdd0) that matches no method on the DelegationManager, and it read a
+// missing `result` as "not disabled". A revoked delegation therefore came back
+// valid. These tests pin the real selector and that an unanswered check raises
+// instead of returning valid.
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { id as keccakId } from 'ethers';
+
+import { isDelegationValid, PermissionError } from '../sdk/src/permissions/toolkit.js';
+
+const CHAIN = 84532;
+const MANAGER = '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3';
+const HASH = '0x' + 'ab'.repeat(32);
+const DISABLED_SELECTOR = keccakId('disabledDelegations(bytes32)').slice(0, 10);
+
+const originalFetch = global.fetch;
+let lastBody = null;
+
+function mockRpc(response) {
+ global.fetch = async (_url, opts) => {
+ lastBody = JSON.parse(opts.body);
+ return { json: async () => response };
+ };
+}
+
+beforeEach(() => {
+ lastBody = null;
+ process.env[`THREE_WS_DELEGATION_MANAGER_${CHAIN}`] = MANAGER;
+});
+
+afterEach(() => {
+ global.fetch = originalFetch;
+ delete process.env[`THREE_WS_DELEGATION_MANAGER_${CHAIN}`];
+});
+
+describe('sdk isDelegationValid', () => {
+ it('calls disabledDelegations(bytes32) with the delegation hash', async () => {
+ mockRpc({ jsonrpc: '2.0', id: 1, result: '0x' + '0'.repeat(64) });
+ const out = await isDelegationValid({ hash: HASH, chainId: CHAIN, rpcUrl: 'http://rpc.test' });
+ expect(out).toEqual({ valid: true });
+ expect(lastBody.method).toBe('eth_call');
+ expect(lastBody.params[0].to).toBe(MANAGER);
+ expect(lastBody.params[0].data.slice(0, 10)).toBe(DISABLED_SELECTOR);
+ expect(lastBody.params[0].data.slice(10)).toBe(HASH.slice(2));
+ });
+
+ it('reports a disabled delegation as revoked', async () => {
+ mockRpc({ jsonrpc: '2.0', id: 1, result: '0x' + '0'.repeat(63) + '1' });
+ const out = await isDelegationValid({ hash: HASH, chainId: CHAIN, rpcUrl: 'http://rpc.test' });
+ expect(out).toEqual({ valid: false, reason: 'delegation_revoked' });
+ });
+
+ it('throws rather than failing open when the node returns an error', async () => {
+ mockRpc({ jsonrpc: '2.0', id: 1, error: { code: -32000, message: 'execution reverted' } });
+ await expect(
+ isDelegationValid({ hash: HASH, chainId: CHAIN, rpcUrl: 'http://rpc.test' }),
+ ).rejects.toThrow(PermissionError);
+ });
+
+ it('throws rather than failing open when the node returns no result', async () => {
+ mockRpc({ jsonrpc: '2.0', id: 1 });
+ await expect(
+ isDelegationValid({ hash: HASH, chainId: CHAIN, rpcUrl: 'http://rpc.test' }),
+ ).rejects.toMatchObject({ code: 'rpc_error' });
+ });
+
+ it('refuses to guess a manager address for a chain with no deployment', async () => {
+ delete process.env[`THREE_WS_DELEGATION_MANAGER_${CHAIN}`];
+ mockRpc({ jsonrpc: '2.0', id: 1, result: '0x' + '0'.repeat(64) });
+ await expect(
+ isDelegationValid({ hash: HASH, chainId: CHAIN, rpcUrl: 'http://rpc.test' }),
+ ).rejects.toMatchObject({ code: 'chain_not_supported' });
+ });
+});
diff --git a/tests/play-event-leaderboard-endpoint.test.js b/tests/play-event-leaderboard-endpoint.test.js
new file mode 100644
index 000000000..87ba9c2e6
--- /dev/null
+++ b/tests/play-event-leaderboard-endpoint.test.js
@@ -0,0 +1,148 @@
+// HTTP-level tests for GET /api/play/event-leaderboard, the read the in-world
+// jobs board and the web event page both render.
+//
+// The ranking math has its own suite (tests/event-leaderboard.test.js); this one
+// covers the handler around it: the no-event refusal, the wire shape of a live
+// board, the pinned `you` row, the limit clamp, and the deliberate decision that
+// an unparseable `account` degrades to an anonymous read rather than 400-ing a
+// public page over one bad query parameter.
+//
+// Only the event window is stubbed (it is read from public/event.json on disk,
+// which stays in its no-event state between events). The store and the ranking
+// are the real modules: with Redis unconfigured the store keeps its rows in
+// process, which is the same code path production takes during a Redis outage.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Readable } from 'node:stream';
+
+const EVENT = {
+ id: 'test-event-01',
+ name: 'Test Event',
+ startsAt: Date.now() - 60_000,
+ endsAt: Date.now() + 3_600_000,
+};
+
+let configuredEvent = EVENT;
+vi.mock('../api/_lib/event-config.js', () => ({
+ eventConfig: () => configuredEvent,
+ eventLiveNow: () => Boolean(configuredEvent),
+ eventId: () => configuredEvent?.id || null,
+}));
+
+const { recordEventRun, __resetEventBoards } = await import('../api/_lib/event-leaderboard-store.js');
+const { default: handler } = await import('../api/play/event-leaderboard.js');
+
+function mockRes() {
+ return {
+ statusCode: 200, _headers: {}, _body: '', _ended: false,
+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this._headers[k.toLowerCase()]; },
+ end(b) { this._body = b || ''; this._ended = true; },
+ get json() { try { return JSON.parse(this._body); } catch { return null; } },
+ };
+}
+
+function mockReq(query = '') {
+ const r = Readable.from([]);
+ r.method = 'GET';
+ r.url = '/api/play/event-leaderboard' + (query ? `?${query}` : '');
+ r.headers = { origin: 'http://localhost:3000' };
+ return r;
+}
+
+const read = async (query = '') => {
+ const res = mockRes();
+ await handler(mockReq(query), res);
+ return res;
+};
+
+// Three runners with a clear order: runs first, then cash.
+async function seed(count = 3) {
+ for (let i = 0; i < count; i += 1) {
+ const account = `wallet-${String(i).padStart(2, '0')}`;
+ for (let run = 0; run <= i; run += 1) {
+ await recordEventRun({
+ eventId: EVENT.id, account, name: `Runner ${i}`,
+ missionId: 'event-plaza-catch', gold: 100, at: 1_000 + run,
+ });
+ }
+ }
+}
+
+beforeEach(() => {
+ configuredEvent = EVENT;
+ __resetEventBoards();
+});
+
+describe('GET /api/play/event-leaderboard', () => {
+ it('refuses with 404 when no event is configured', async () => {
+ configuredEvent = null;
+ const res = await read();
+ expect(res.statusCode).toBe(404);
+ expect(res.json.error).toBe('no_event');
+ });
+
+ it('serves an event nobody has played as an empty board, not an error', async () => {
+ const res = await read();
+ expect(res.statusCode).toBe(200);
+ expect(res.json.top).toEqual([]);
+ expect(res.json.you).toBe(null);
+ expect(res.json.players).toBe(0);
+ expect(res.json.totalRuns).toBe(0);
+ });
+
+ it('returns the event window, the ranking and the manual-settlement notice', async () => {
+ await seed();
+ const res = await read();
+ expect(res.statusCode).toBe(200);
+ const body = res.json;
+ expect(body.event.id).toBe(EVENT.id);
+ expect(body.event.name).toBe(EVENT.name);
+ expect(body.event.startsAt).toBe(new Date(EVENT.startsAt).toISOString());
+ expect(body.event.live).toBe(true);
+ expect(body.top.map((r) => r.runs)).toEqual([3, 2, 1]);
+ expect(body.players).toBe(3);
+ expect(body.totalRuns).toBe(6);
+ // No prize is ever paid from this path.
+ expect(body.prizes.settlement).toBe('manual');
+ });
+
+ it('never puts an account key on the wire', async () => {
+ await seed();
+ const res = await read('account=wallet-00');
+ expect(res._body).not.toContain('wallet-00');
+ expect(res.json.you.rank).toBe(3);
+ expect(res.json.you.runs).toBe(1);
+ });
+
+ it('pins your own row even when you are outside the requested top', async () => {
+ await seed();
+ const res = await read('account=wallet-00&limit=1');
+ expect(res.json.top).toHaveLength(1);
+ expect(res.json.you.inTop).toBe(false);
+ expect(res.json.you.rank).toBe(3);
+ });
+
+ it('treats an unparseable account as an anonymous read rather than a 400', async () => {
+ await seed();
+ const res = await read('account=' + encodeURIComponent('not a valid key!!'));
+ expect(res.statusCode).toBe(200);
+ expect(res.json.you).toBe(null);
+ expect(res.json.top).toHaveLength(3);
+ });
+
+ it('clamps an absurd limit instead of dumping the whole board', async () => {
+ await seed(12);
+ const res = await read('limit=99999');
+ expect(res.json.top.length).toBeLessThanOrEqual(100);
+ expect(res.json.players).toBe(12);
+ });
+
+ it('refuses a non-GET verb', async () => {
+ const res = mockRes();
+ const req = mockReq();
+ req.method = 'POST';
+ await handler(req, res);
+ expect(res.statusCode).toBe(405);
+ });
+});
diff --git a/tests/plugins-marketplace-endpoint.test.js b/tests/plugins-marketplace-endpoint.test.js
new file mode 100644
index 000000000..70535bc8f
--- /dev/null
+++ b/tests/plugins-marketplace-endpoint.test.js
@@ -0,0 +1,442 @@
+/**
+ * api/plugins/[action].js, the plugin marketplace endpoint behind
+ * /api/plugins/{categories,list,import,publish}, /api/plugins/:id and
+ * /api/plugins/:id/install.
+ *
+ * Postgres, the rate limiter, auth, CSRF, and the SSRF-guarded outbound fetch
+ * are all mocked, so every branch runs deterministically with no Neon branch and
+ * no network: the visibility rules, the cursor guard, the install dedupe, and
+ * the import failure modes are each reachable from here.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: async () => ({ pressured: false }),
+}));
+
+const state = {
+ rateOk: true,
+ installDedupeOk: true,
+ session: null,
+ bearer: null,
+ csrfOk: true,
+ fetchImpl: null,
+};
+
+const ok = () => ({ success: true, limit: 60, remaining: 59, reset: Date.now() + 60_000 });
+const denied = () => ({ success: false, limit: 60, remaining: 0, reset: Date.now() + 60_000 });
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ widgetRead: vi.fn(async () => (state.rateOk ? ok() : denied())),
+ pluginImportIp: vi.fn(async () => (state.rateOk ? ok() : denied())),
+ pluginPublishUser: vi.fn(async () => (state.rateOk ? ok() : denied())),
+ pluginInstallDedupe: vi.fn(async () => (state.installDedupeOk ? ok() : denied())),
+ },
+ clientIp: () => '203.0.113.7',
+}));
+
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: async () => state.session,
+ authenticateBearer: async () => state.bearer,
+ extractBearer: (req) => {
+ const h = req.headers?.authorization || '';
+ return h.toLowerCase().startsWith('bearer ') ? h.slice(7).trim() : null;
+ },
+}));
+
+vi.mock('../api/_lib/csrf.js', () => ({
+ requireCsrf: async (_req, res) => {
+ if (state.csrfOk) return true;
+ res.statusCode = 403;
+ res.end(JSON.stringify({ error: 'csrf_missing' }));
+ return false;
+ },
+}));
+
+vi.mock('../api/_lib/ssrf-guard.js', async () => {
+ const actual = await vi.importActual('../api/_lib/ssrf-guard.js');
+ return {
+ ...actual,
+ fetchSafePublicUrlPinned: (...a) => state.fetchImpl(...a),
+ };
+});
+
+const { SsrfBlockedError, MaxBytesExceededError } = await import('../api/_lib/ssrf-guard.js');
+const { default: handler } = await import('../api/plugins/[action].js');
+
+const PUBLIC_ID = '11111111-2222-4333-8444-555555555555';
+const USER_ID = '99999999-8888-4777-8666-555555555555';
+
+function pluginRow(over = {}) {
+ return {
+ id: PUBLIC_ID,
+ identifier: 'web-search',
+ manifest_url: null,
+ manifest_json: { identifier: 'web-search' },
+ name: 'Web Search',
+ description: 'Search the web.',
+ category: 'web-search',
+ tags: ['search'],
+ install_count: 3,
+ avg_rating: '4.50',
+ author_id: null,
+ author_display_name: null,
+ created_at: '2026-05-02T07:43:09.276Z',
+ ...over,
+ };
+}
+
+function makeReq({ method = 'GET', path, body = null, headers = {} } = {}) {
+ const req = {
+ method,
+ url: path,
+ headers: { origin: 'https://three.ws', ...headers },
+ socket: { remoteAddress: '203.0.113.7' },
+ };
+ if (body !== null) {
+ req.headers['content-type'] = req.headers['content-type'] || 'application/json';
+ req.body = body;
+ }
+ return req;
+}
+
+function makeRes() {
+ const r = { statusCode: 200, _h: {}, _b: null, writableEnded: false, headersSent: false };
+ r.setHeader = (k, v) => { r._h[k.toLowerCase()] = v; };
+ r.getHeader = (k) => r._h[k.toLowerCase()];
+ r.end = (b) => { r._b = b ?? r._b; r.writableEnded = true; };
+ r.json = () => (r._b ? JSON.parse(r._b) : undefined);
+ return r;
+}
+
+async function call(opts) {
+ const res = makeRes();
+ await handler(makeReq(opts), res);
+ return res;
+}
+
+// The handler builds its queries with tagged templates, so the joined static
+// fragments are the only readable form of "what SQL did it actually run".
+function lastQueryText() {
+ const call = sqlMock.mock.calls.at(-1);
+ return call ? call[0].join(' ? ') : '';
+}
+function allQueryText() {
+ return sqlMock.mock.calls.map((c) => c[0].join(' ? ')).join('\n');
+}
+
+beforeEach(() => {
+ state.rateOk = true;
+ state.installDedupeOk = true;
+ state.session = null;
+ state.bearer = null;
+ state.csrfOk = true;
+ state.fetchImpl = async () => new Response('{}', { status: 200 });
+ sqlMock.mockReset().mockResolvedValue([]);
+});
+
+describe('GET /api/plugins/list', () => {
+ it('returns the page and a next_cursor when more rows exist', async () => {
+ sqlMock.mockResolvedValue([pluginRow(), pluginRow({ id: 'b' }), pluginRow({ id: 'c' })]);
+ const res = await call({ path: '/api/plugins/list?limit=2' });
+ expect(res.statusCode).toBe(200);
+ const { items, next_cursor } = res.json().data;
+ expect(items).toHaveLength(2);
+ expect(next_cursor).toBe('2');
+ expect(items[0].avg_rating).toBe(4.5);
+ });
+
+ it('rejects a cursor that is not a non-negative integer instead of 500ing', async () => {
+ // The cursor lands in OFFSET. Number('abc') is NaN, and NaN reaching
+ // Postgres raised a query error the wrapper surfaced as an opaque 500 for
+ // what is plainly a client fault.
+ for (const cursor of ['abc', '-1', '1.5', '1e3abc']) {
+ const res = await call({ path: `/api/plugins/list?cursor=${cursor}` });
+ expect(res.statusCode, cursor).toBe(400);
+ expect(res.json().error).toBe('validation_error');
+ }
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('serves the bare collection path as the list', async () => {
+ sqlMock.mockResolvedValue([pluginRow()]);
+ const res = await call({ path: '/api/plugins' });
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data.items).toHaveLength(1);
+ });
+
+ it('only ever lists public, undeleted rows', async () => {
+ await call({ path: '/api/plugins/list' });
+ expect(lastQueryText()).toContain('p.is_public = true');
+ expect(lastQueryText()).toContain('p.deleted_at IS NULL');
+ });
+
+ it('answers 429 when the browse bucket is spent', async () => {
+ state.rateOk = false;
+ const res = await call({ path: '/api/plugins/list' });
+ expect(res.statusCode).toBe(429);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('GET /api/plugins/:id', () => {
+ it('serves a public plugin', async () => {
+ sqlMock.mockResolvedValue([pluginRow()]);
+ const res = await call({ path: `/api/plugins/${PUBLIC_ID}` });
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data.plugin.identifier).toBe('web-search');
+ });
+
+ it('gates an unpublished plugin behind its author', async () => {
+ // is_public:false is a real publish option; reading by id alone used to
+ // hand an unpublished manifest to anyone holding the UUID.
+ await call({ path: `/api/plugins/${PUBLIC_ID}` });
+ expect(lastQueryText()).toContain('p.is_public = true OR p.author_id =');
+ const res = await call({ path: `/api/plugins/${PUBLIC_ID}` });
+ expect(res.statusCode).toBe(404);
+ expect(res.json().error).toBe('not_found');
+ });
+
+ it('passes the session user as the viewer so an author sees their own draft', async () => {
+ state.session = { id: USER_ID };
+ sqlMock.mockResolvedValue([pluginRow({ author_id: USER_ID, author_display_name: 'QA' })]);
+ const res = await call({ path: `/api/plugins/${PUBLIC_ID}` });
+ expect(res.statusCode).toBe(200);
+ expect(sqlMock.mock.calls.at(-1)).toContain(USER_ID);
+ expect(res.json().data.plugin.author).toEqual({ id: USER_ID, display_name: 'QA' });
+ });
+
+ it('404s a segment that is neither an action nor a UUID', async () => {
+ const res = await call({ path: '/api/plugins/not-a-uuid' });
+ expect(res.statusCode).toBe(404);
+ expect(res.json().error_description).toBe('unknown plugin action');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a write method with 405', async () => {
+ const res = await call({ path: `/api/plugins/${PUBLIC_ID}`, method: 'POST', body: {} });
+ expect(res.statusCode).toBe(405);
+ });
+});
+
+describe('POST /api/plugins/:id/install', () => {
+ it('404s a plugin that does not exist instead of reporting success', async () => {
+ // The counter UPDATE matched no row and the handler answered {ok:true}
+ // regardless, so a typo'd id looked exactly like a real install.
+ sqlMock.mockResolvedValue([]);
+ const res = await call({ path: `/api/plugins/${PUBLIC_ID}/install`, method: 'POST' });
+ expect(res.statusCode).toBe(404);
+ expect(allQueryText()).not.toContain('UPDATE plugins SET install_count');
+ });
+
+ it('counts the first install and reports the new total', async () => {
+ sqlMock
+ .mockResolvedValueOnce([{ id: PUBLIC_ID, install_count: 3 }])
+ .mockResolvedValueOnce([{ install_count: 4 }]);
+ const res = await call({ path: `/api/plugins/${PUBLIC_ID}/install`, method: 'POST' });
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data).toEqual({ ok: true, counted: true, install_count: 4 });
+ });
+
+ it('answers 200 counted:false on a repeat rather than a 429 the client must special-case', async () => {
+ state.installDedupeOk = false;
+ sqlMock.mockResolvedValueOnce([{ id: PUBLIC_ID, install_count: 4 }]);
+ const res = await call({ path: `/api/plugins/${PUBLIC_ID}/install`, method: 'POST' });
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data).toEqual({ ok: true, counted: false, install_count: 4 });
+ expect(allQueryText()).not.toContain('UPDATE plugins SET install_count');
+ });
+
+ it('applies the same visibility rule as detail', async () => {
+ await call({ path: `/api/plugins/${PUBLIC_ID}/install`, method: 'POST' });
+ expect(allQueryText()).toContain('is_public = true OR author_id =');
+ });
+});
+
+describe('POST /api/plugins/publish', () => {
+ const manifest = {
+ identifier: 'my-plugin',
+ meta: { title: 'My Plugin', description: 'Does a thing.' },
+ api: [{ name: 'do_thing', description: 'Does the thing' }],
+ };
+
+ it('requires authentication', async () => {
+ const res = await call({
+ path: '/api/plugins/publish',
+ method: 'POST',
+ body: { manifest_json: manifest },
+ });
+ expect(res.statusCode).toBe(401);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('requires a CSRF token on a cookie session', async () => {
+ // The session cookie rides along on any cross-site POST, so the
+ // double-submit token is the only thing separating a real publish from one
+ // a hostile page triggered in the victim's browser.
+ state.session = { id: USER_ID };
+ state.csrfOk = false;
+ const res = await call({
+ path: '/api/plugins/publish',
+ method: 'POST',
+ body: { manifest_json: manifest },
+ });
+ expect(res.statusCode).toBe(403);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('upserts and answers with a fully populated author', async () => {
+ state.session = { id: USER_ID };
+ sqlMock
+ .mockResolvedValueOnce([
+ pluginRow({ identifier: 'my-plugin', name: 'My Plugin', author_id: USER_ID }),
+ ])
+ .mockResolvedValueOnce([{ display_name: 'QA Audit' }]);
+ const res = await call({
+ path: '/api/plugins/publish',
+ method: 'POST',
+ body: { manifest_json: manifest },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data.plugin.author).toEqual({ id: USER_ID, display_name: 'QA Audit' });
+ expect(allQueryText()).toContain('ON CONFLICT (identifier, author_id) DO UPDATE');
+ });
+
+ it('rejects a manifest missing its required fields', async () => {
+ state.session = { id: USER_ID };
+ for (const [bad, expected] of [
+ [{ meta: { title: 'x' }, api: [{ name: 'a', description: 'b' }] }, 'Missing identifier'],
+ [{ identifier: 'ok', api: [{ name: 'a', description: 'b' }] }, 'Missing meta.title'],
+ [{ identifier: 'ok', meta: { title: 'x' }, api: [] }, 'non-empty array'],
+ [
+ { identifier: 'a'.repeat(200), meta: { title: 'x' }, api: [{ name: 'a', description: 'b' }] },
+ '128 characters or fewer',
+ ],
+ [
+ {
+ identifier: 'ok',
+ meta: { title: 'x' },
+ api: Array.from({ length: 101 }, (_, i) => ({ name: `t${i}`, description: 'd' })),
+ },
+ 'at most 100 tools',
+ ],
+ ]) {
+ const res = await call({
+ path: '/api/plugins/publish',
+ method: 'POST',
+ body: { manifest_json: bad },
+ });
+ expect(res.statusCode).toBe(422);
+ expect(res.json().error_description).toContain(expected);
+ }
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST /api/plugins/import', () => {
+ it('requires an http(s) manifest_url', async () => {
+ for (const [body, expected] of [
+ [{}, 'manifest_url is required'],
+ [{ manifest_url: 'notaurl' }, 'not a valid URL'],
+ [{ manifest_url: 'file:///etc/passwd' }, 'must be http or https'],
+ ]) {
+ const res = await call({ path: '/api/plugins/import', method: 'POST', body });
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error_description).toContain(expected);
+ }
+ });
+
+ it('reports an SSRF-blocked host as a client validation error', async () => {
+ state.fetchImpl = async () => {
+ throw new SsrfBlockedError('host 169.254.169.254 is a blocked address');
+ };
+ const res = await call({
+ path: '/api/plugins/import',
+ method: 'POST',
+ body: { manifest_url: 'http://169.254.169.254/latest/meta-data/' },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error_description).toContain('blocked address');
+ });
+
+ it('caps the transfer instead of buffering an oversized response', async () => {
+ // The old code read the whole body and measured it afterwards, so a
+ // hostile host could stream gigabytes into the instance before the check.
+ let opts;
+ state.fetchImpl = async (_url, _init, o) => {
+ opts = o;
+ throw new MaxBytesExceededError(9_000_000, 65_536);
+ };
+ const res = await call({
+ path: '/api/plugins/import',
+ method: 'POST',
+ body: { manifest_url: 'https://example.com/huge.json' },
+ });
+ expect(opts.maxBytes).toBe(65_536);
+ expect(res.statusCode).toBe(422);
+ expect(res.json().error_description).toContain('64KB limit');
+ });
+
+ it('surfaces a non-2xx upstream as fetch_failed', async () => {
+ state.fetchImpl = async () => new Response('nope', { status: 404 });
+ const res = await call({
+ path: '/api/plugins/import',
+ method: 'POST',
+ body: { manifest_url: 'https://example.com/missing.json' },
+ });
+ expect(res.statusCode).toBe(422);
+ expect(res.json().error).toBe('fetch_failed');
+ });
+
+ it('validates the fetched manifest and echoes back its source URL', async () => {
+ const manifest = {
+ identifier: 'remote-plugin',
+ meta: { title: 'Remote' },
+ api: [{ name: 'go', description: 'go' }],
+ };
+ state.fetchImpl = async () => new Response(JSON.stringify(manifest), { status: 200 });
+ const res = await call({
+ path: '/api/plugins/import',
+ method: 'POST',
+ body: { manifest_url: 'https://example.com/manifest.json' },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data.manifest._manifest_url).toBe('https://example.com/manifest.json');
+ // Import never writes: the client decides whether to install locally.
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects fetched JSON that is not a plugin manifest', async () => {
+ state.fetchImpl = async () => new Response('{"latest":"1.0.0"}', { status: 200 });
+ const res = await call({
+ path: '/api/plugins/import',
+ method: 'POST',
+ body: { manifest_url: 'https://example.com/dist-tags.json' },
+ });
+ expect(res.statusCode).toBe(422);
+ expect(res.json().error).toBe('invalid_manifest');
+ });
+});
+
+describe('GET /api/plugins/categories', () => {
+ it('counts only public, undeleted rows and lets the edge cache it', async () => {
+ sqlMock.mockResolvedValue([{ category: 'tools', count: 4 }]);
+ const res = await call({ path: '/api/plugins/categories' });
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data.categories).toEqual([{ slug: 'tools', count: 4 }]);
+ expect(res.getHeader('cache-control')).toBe('public, max-age=60');
+ expect(lastQueryText()).toContain('is_public = true AND deleted_at IS NULL');
+ });
+
+ it('answers a preflight without touching the database', async () => {
+ const res = await call({ path: '/api/plugins/categories', method: 'OPTIONS' });
+ expect(res.statusCode).toBe(204);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/pump-intel-api-boundaries.test.js b/tests/pump-intel-api-boundaries.test.js
new file mode 100644
index 000000000..612fcd4ee
--- /dev/null
+++ b/tests/pump-intel-api-boundaries.test.js
@@ -0,0 +1,247 @@
+// Input-boundary tests for the pump read endpoints that answer a caller mistake
+// with the wrong thing.
+//
+// GET /api/pump/intel a typo'd mint / view / minQuality used to come back
+// as `degraded: true` or as a silently-substituted
+// feed, i.e. the dashboard blamed the engine for the
+// caller's typo and the caller never learned.
+// GET /api/pump/dashboard a non-UUID agent_id reached a uuid-typed column and
+// Postgres 500'd on it.
+// GET /api/pump/helius-stats a probe against a non-Helius RPC was labelled
+// `endpoint: 'helius-rpc'`, and a failed probe was
+// reported as a bare `slot: null` with no reason.
+//
+// The DB and the RPC are the seams these handlers own, so those are stubbed. All
+// the validation, labelling, and error-boundary logic runs for real.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ sqlValues: () => '',
+ isDbUnavailableError: () => false,
+}));
+
+const getSessionUserMock = vi.fn();
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUserMock(...a),
+}));
+
+vi.mock('../api/_lib/pumpfun-ws-feed.js', () => ({ recentBuffered: () => [] }));
+vi.mock('../api/_lib/sol-price.js', () => ({
+ solPriceUsd: async () => 76,
+ solPriceInfo: () => ({ stale: false }),
+ solChange24hPct: async () => 0.5,
+}));
+
+const { default: intelHandler } = await import('../api/pump/intel.js');
+const { default: dashboardHandler } = await import('../api/pump/dashboard.js');
+const { default: heliusHandler, resolveProbeTarget, _resetHeliusCache } =
+ await import('../api/pump/helius-stats.js');
+
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+function mkReq({ method = 'GET', url = '/', headers = {} } = {}) {
+ return { method, url, headers: { host: 'three.ws', ...headers }, socket: {}, on() {}, destroy() {} };
+}
+function mkRes() {
+ return {
+ statusCode: 200, headers: {}, body: undefined, writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(b) { this.body = b; this.writableEnded = true; },
+ };
+}
+const read = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+async function callIntel(query) {
+ const res = mkRes();
+ await intelHandler(mkReq({ url: `/api/pump/intel${query}` }), res);
+ return { res, body: read(res) };
+}
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ getSessionUserMock.mockReset();
+ vi.unstubAllGlobals();
+});
+
+describe('GET /api/pump/intel input boundaries', () => {
+ it('400s a malformed mint instead of reporting "no such coin"', async () => {
+ const { res, body } = await callIntel('?mint=notbase58');
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('invalid_mint');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('400s a non-integer minQuality instead of blaming the engine', async () => {
+ // The old path forwarded NaN into `${minQuality}::int`, Postgres threw, and
+ // the catch-all answered 200 `degraded: true` — an outage report for a typo.
+ const { res, body } = await callIntel('?view=feed&minQuality=abc');
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('invalid_min_quality');
+ expect(body.degraded).toBeUndefined();
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('400s a minQuality outside the 0..100 score range', async () => {
+ expect((await callIntel('?view=feed&minQuality=-1')).res.statusCode).toBe(400);
+ expect((await callIntel('?view=feed&minQuality=101')).res.statusCode).toBe(400);
+ });
+
+ it('400s an unknown view rather than quietly serving the feed under its name', async () => {
+ const { res, body } = await callIntel('?view=bogusview');
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('invalid_view');
+ expect(body.view).toBeUndefined(); // the caller's string is not echoed back
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('still serves the default feed, a known view, and a valid minQuality', async () => {
+ sqlMock.mockResolvedValue([]);
+ for (const q of ['', '?view=feed', '?view=learning', '?view=traders', '?view=feed&minQuality=70']) {
+ const { res } = await callIntel(q);
+ expect(res.statusCode, `view query ${q || '(none)'}`).toBe(200);
+ }
+ });
+
+ it('still degrades to 200 when the engine tables are genuinely missing', async () => {
+ sqlMock.mockRejectedValue(new Error('relation "pump_coin_intel" does not exist'));
+ const { res, body } = await callIntel('?view=feed');
+ expect(res.statusCode).toBe(200);
+ expect(body.degraded).toBe(true);
+ expect(body.reason).toBe('engine_tables_pending');
+ });
+});
+
+describe('GET /api/pump/dashboard input boundaries', () => {
+ it('400s a non-UUID agent_id instead of 500ing on the uuid column', async () => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ const res = mkRes();
+ await dashboardHandler(mkReq({ url: '/api/pump/dashboard?agent_id=not-a-uuid' }), res);
+ expect(res.statusCode).toBe(400);
+ expect(read(res).error).toBe('invalid_agent_id');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('still 401s before it ever looks at the query', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ const res = mkRes();
+ await dashboardHandler(mkReq({ url: '/api/pump/dashboard?agent_id=not-a-uuid' }), res);
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('still 404s a well-formed id that is not the caller\'s agent', async () => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ sqlMock.mockResolvedValue([]);
+ const res = mkRes();
+ await dashboardHandler(
+ mkReq({ url: '/api/pump/dashboard?agent_id=00000000-0000-4000-8000-000000000000' }),
+ res,
+ );
+ expect(res.statusCode).toBe(404);
+ expect(read(res).error).toBe('not_found');
+ });
+});
+
+describe('helius-stats probe target', () => {
+ it('probes the configured RPC when it really is Helius', () => {
+ const t = resolveProbeTarget({ SOLANA_RPC_URL: 'https://mainnet.helius-rpc.com/?api-key=k' });
+ expect(t.url).toContain('helius-rpc.com');
+ expect(t.endpoint).toBe('helius-rpc');
+ });
+
+ it('probes Helius itself when the key is set but SOLANA_RPC_URL points elsewhere', () => {
+ // Production runs exactly this shape. Labelling the other provider
+ // "helius-rpc" is what made a third-party 403 read as a quiet chain.
+ const t = resolveProbeTarget({
+ HELIUS_API_KEY: 'abc',
+ SOLANA_RPC_URL: 'https://rpc.example-provider.app/mainnet',
+ });
+ expect(t.url).toBe('https://mainnet.helius-rpc.com/?api-key=abc');
+ expect(t.endpoint).toBe('helius-rpc');
+ });
+
+ it('claims no Helius endpoint when there is no key and no Helius URL', () => {
+ expect(resolveProbeTarget({ SOLANA_RPC_URL: 'https://rpc.example-provider.app/mainnet' }))
+ .toEqual({ url: '', endpoint: null });
+ expect(resolveProbeTarget({})).toEqual({ url: '', endpoint: null });
+ });
+});
+
+describe('GET /api/pump/helius-stats probe reporting', () => {
+ const call = async () => {
+ _resetHeliusCache(); // the 4s probe cache would otherwise answer the next case
+ const res = mkRes();
+ await heliusHandler(mkReq({ url: '/api/pump/helius-stats' }), res);
+ return read(res);
+ };
+
+ it('names the HTTP status when the RPC rejects the key', async () => {
+ // A rejected key answers with a plain-text body, so r.json() throws and the
+ // failure used to be filed as a generic "unreachable".
+ vi.stubEnv('HELIUS_API_KEY', 'dead-key');
+ vi.stubEnv('SOLANA_RPC_URL', '');
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('Unauthorized', { status: 401 })));
+ const body = await call();
+ expect(body.helius.error).toBe('http_401');
+ expect(body.helius.slot).toBeNull();
+ });
+
+ it('surfaces a JSON-RPC error body rather than a bare null slot', async () => {
+ vi.stubEnv('HELIUS_API_KEY', 'k2');
+ vi.stubEnv('SOLANA_RPC_URL', '');
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(
+ JSON.stringify({ jsonrpc: '2.0', id: 1, error: { code: 403, message: 'IP blocked' } }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ )));
+ const body = await call();
+ expect(body.helius.error).toBe('IP blocked');
+ expect(body.helius.slot).toBeNull();
+ });
+
+ it('reports the live slot with no error when the probe succeeds', async () => {
+ vi.stubEnv('HELIUS_API_KEY', 'k3');
+ vi.stubEnv('SOLANA_RPC_URL', '');
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(
+ JSON.stringify({ jsonrpc: '2.0', id: 1, result: 372_004_112 }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ )));
+ const body = await call();
+ expect(body.helius).toMatchObject({ enabled: true, slot: 372_004_112, endpoint: 'helius-rpc' });
+ expect(body.helius.error).toBeUndefined();
+ });
+
+ it('reports helius disabled, and never a stale slot, with nothing configured', async () => {
+ vi.stubEnv('HELIUS_API_KEY', '');
+ vi.stubEnv('SOLANA_RPC_URL', '');
+ const fetchSpy = vi.fn();
+ vi.stubGlobal('fetch', fetchSpy);
+ const body = await call();
+ expect(body.helius).toEqual({ enabled: false });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ expect(body.sol_price).toBe(76);
+ });
+});
+
+describe('/api/pump/intel still reads real intel rows', () => {
+ it('shapes a coin row into the documented record, verdict included', async () => {
+ sqlMock.mockImplementation((statics) => {
+ const text = Array.isArray(statics) ? statics.join(' ') : String(statics);
+ if (text.includes('pump_coin_intel')) {
+ return Promise.resolve([{
+ mint: MINT, network: 'mainnet', symbol: 'THREE', name: 'three.ws',
+ quality_score: 80, risk_flags: [], organic_score: 0.9, signals: {},
+ first_seen_at: '2026-08-01T00:00:00.000Z',
+ }]);
+ }
+ return Promise.resolve([]);
+ });
+ const { res, body } = await callIntel(`?mint=${MINT}`);
+ expect(res.statusCode).toBe(200);
+ expect(body.found).toBe(true);
+ expect(body.coin.symbol).toBe('THREE');
+ expect(body.coin.verdict.key).toBe('strong');
+ });
+});
diff --git a/tests/pump-telegram-delivery.test.js b/tests/pump-telegram-delivery.test.js
index d48fbbc40..86255393d 100644
--- a/tests/pump-telegram-delivery.test.js
+++ b/tests/pump-telegram-delivery.test.js
@@ -163,10 +163,14 @@ describe('POST /api/pump/deliver-telegram', () => {
expect(json.error).toBe('unauthorized');
});
- it('returns 500 when TELEGRAM_BOT_TOKEN is not set', async () => {
+ it('returns 503 not_configured when TELEGRAM_BOT_TOKEN is not set', async () => {
+ // An absent bot token is a deployment gap, not a server fault. 503 is what
+ // every sibling handler answers, and it tells a client to stop retrying
+ // instead of reporting a bug. The message names no env var to a caller who
+ // cannot set one.
const { res, json } = await callEndpoint({ chatId: '123', signal: SIGNAL });
- expect(res.statusCode).toBe(500);
- expect(json.error_description).toMatch(/TELEGRAM_BOT_TOKEN/);
+ expect(res.statusCode).toBe(503);
+ expect(json.error).toBe('not_configured');
});
it('returns 400 when chatId is missing', async () => {