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.

fix(api): harden the portfolio, holders and skill-purchase paths against bad input

nirholas5d2ff88bc583
diff --git a/api/_lib/coin/three-holders.js b/api/_lib/coin/three-holders.js
index 40a86e92e..f168fd6a6 100644
--- a/api/_lib/coin/three-holders.js
+++ b/api/_lib/coin/three-holders.js
@@ -18,7 +18,8 @@
import { sql } from '../db.js';
import { TOKEN_MINT as THREE_MINT } from '../token/config.js';
import { fetchHolderBalances } from './holders.js';
-import { acquireLock, releaseLock } from '../cache.js';
+import { jupiterTokenSearch } from '../token/jupiter.js';
+import { acquireLock, releaseLock, cacheGet, cacheSet } from '../cache.js';
const UPSERT_CHUNK = 2000; // rows per batched upsert — mirrors persistHolderSnapshot
// A snapshot older than this is treated as missing: the reader falls back to a
@@ -172,22 +173,59 @@ export async function readThreeHolderSnapshot({ allowStale = false } = {}) {
* Cheap holder *count* for the public stats panel. Reads only the snapshot meta
* row (one query, no balance rows) so the hot, edge-cached /api/three-token/stats
* path never triggers the multi-second DAS walk that threeHolderBalances() can.
- * Returns null when there's no fresh snapshot so the caller can fall back to a
- * market-data figure (Birdeye) or render "—" — the leaderboard read self-heals a
- * stale/cold snapshot on its own.
+ * Returns null only when neither our snapshot nor the keyless fallback answers,
+ * so the caller renders a blank figure rather than a wrong one.
*/
export async function threeHolderCount() {
try {
const [meta] = await sql`
select snapshot_at, holder_count from three_holder_snapshot_meta where id = 1
`;
- if (!meta?.snapshot_at) return null;
- const ageMs = Date.now() - new Date(meta.snapshot_at).getTime();
- if (ageMs > MAX_SNAPSHOT_AGE_MS) return null;
- const n = Number(meta.holder_count);
- return Number.isFinite(n) && n > 0 ? n : null;
+ if (meta?.snapshot_at) {
+ const ageMs = Date.now() - new Date(meta.snapshot_at).getTime();
+ const n = Number(meta.holder_count);
+ if (ageMs <= MAX_SNAPSHOT_AGE_MS && Number.isFinite(n) && n > 0) return n;
+ }
+ } catch {
+ // Table not migrated yet / DB blip: fall through to the keyless rung.
+ }
+ return jupiterThreeHolderCount();
+}
+
+// Keyless holder-count rung, used whenever our own snapshot is missing or stale.
+//
+// Why it exists: the snapshot is refreshed by a Helius DAS walk
+// (api/cron/three-holders-snapshot.js), so an exhausted Helius quota freezes it.
+// The staleness gate above then correctly refuses the frozen number, and every
+// public surface that shows holders went blank indefinitely rather than for a
+// tick or two. Jupiter's token search carries a holderCount for any mint and
+// needs no key, so it keeps the figure real through a DAS outage instead of
+// blanking it. Deliberately NOT a substitute for the snapshot: it is a single
+// count with no per-wallet balances, so ranking and %-of-supply still come from
+// the snapshot alone.
+const JUP_HOLDERS_KEY = 'three:holders:jup-count';
+const JUP_HOLDERS_TTL_S = 300;
+const JUP_HOLDERS_TIMEOUT_MS = 4000;
+
+async function jupiterThreeHolderCount() {
+ try {
+ const cached = await cacheGet(JUP_HOLDERS_KEY);
+ if (Number.isFinite(cached?.count) && cached.count > 0) return cached.count;
+ } catch {
+ // Cache miss/outage just means we ask Jupiter directly.
+ }
+ try {
+ const rows = await jupiterTokenSearch(THREE_MINT, {
+ limit: 1,
+ signal: AbortSignal.timeout(JUP_HOLDERS_TIMEOUT_MS),
+ });
+ const row = rows.find((r) => r?.id === THREE_MINT) || rows[0];
+ const count = Number(row?.holderCount);
+ if (!Number.isFinite(count) || count <= 0) return null;
+ await cacheSet(JUP_HOLDERS_KEY, { count }, JUP_HOLDERS_TTL_S).catch(() => {});
+ return count;
} catch {
- // Table not migrated yet / DB blip — signal "unknown" rather than erroring.
+ // Upstream down or throttled: unknown beats a fabricated number.
return null;
}
}
diff --git a/api/_lib/ghost-copy.js b/api/_lib/ghost-copy.js
index 245f2128c..8612210d8 100644
--- a/api/_lib/ghost-copy.js
+++ b/api/_lib/ghost-copy.js
@@ -64,11 +64,18 @@ export function buildGhostSubscription({
} = {}) {
const budget = num(budgetSol);
if (budget == null || budget <= 0) return { ok: false, error: 'budget must be a positive number of SOL' };
+ // An unrecognized rule used to fall through to 'fixed', so a caller asking for
+ // a multiplier-sized replay got a fixed-sized one and no hint that the request
+ // was ignored. A replay that silently simulates something else is worse than
+ // no replay: reject it and let the endpoint's invalid_sizing 400 fire.
+ if (!['fixed', 'multiplier'].includes(sizing_rule)) {
+ return { ok: false, error: 'sizing must be "fixed" or "multiplier"' };
+ }
// Deploy the budget in roughly ten slices, never more than a quarter of it in
// one trade, and recycle the whole budget at most once per UTC day.
const draft = {
- sizing_rule: ['fixed', 'multiplier'].includes(sizing_rule) ? sizing_rule : 'fixed',
+ sizing_rule,
fixed_sol: num(fixed_sol) ?? round4(budget / 10),
multiplier: num(multiplier) ?? 0.1,
per_trade_cap_sol: num(per_trade_cap_sol) ?? round4(budget / 4),
diff --git a/api/_lib/token/jupiter.js b/api/_lib/token/jupiter.js
index b0d1a6c2e..4aa9cbd78 100644
--- a/api/_lib/token/jupiter.js
+++ b/api/_lib/token/jupiter.js
@@ -100,17 +100,19 @@ export async function jupiterSwapTx({
* token's full record: usdPrice, mcap, liquidity, holderCount, launchpad,
* audit flags, and per-window stats.
* @param {string} query symbol, name, or mint address
- * @param {{ limit?: number }} [opts] upstream caps at 100
+ * @param {{ limit?: number, signal?: AbortSignal }} [opts] upstream caps at 100;
+ * pass a signal to bound the call from a latency-sensitive path (an OG card,
+ * a request handler), which otherwise waits on the platform default.
* @returns {Promise<Array<object>>} raw Jupiter token records
*/
-export async function jupiterTokenSearch(query, { limit } = {}) {
+export async function jupiterTokenSearch(query, { limit, signal } = {}) {
if (!query) {
throw Object.assign(new Error('jupiterTokenSearch requires a query'), { code: 'bad_query' });
}
const u = new URL(`${JUP_TOKENS_URL}/search`);
u.searchParams.set('query', String(query));
if (limit) u.searchParams.set('limit', String(limit));
- const data = await fetchJson(u.toString(), { headers: { accept: 'application/json' } });
+ const data = await fetchJson(u.toString(), { headers: { accept: 'application/json' }, signal });
return Array.isArray(data) ? data : [];
}
diff --git a/api/plugins/[action].js b/api/plugins/[action].js
index 0e4fef26b..c7632de03 100644
--- a/api/plugins/[action].js
+++ b/api/plugins/[action].js
@@ -383,7 +383,10 @@ async function handlePublish(req, res) {
RETURNING *
`;
- return json(res, 200, { data: { plugin: toPlugin(row) } });
+ const [author] = await sql`SELECT display_name FROM users WHERE id = ${auth.userId}`;
+ return json(res, 200, {
+ data: { plugin: toPlugin({ ...row, author_display_name: author?.display_name ?? null }) },
+ });
}
// ── Install (counter) ─────────────────────────────────────────────────────────
@@ -392,11 +395,37 @@ async function handleInstall(req, res, id) {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
- const rl = await limits.widgetRead(clientIp(req));
+ const ip = clientIp(req);
+ const rl = await limits.widgetRead(ip);
if (!rl.success) return rateLimited(res, rl);
- await sql`
- UPDATE plugins SET install_count = install_count + 1 WHERE id = ${id} AND deleted_at IS NULL
+ // Same visibility rule as detail: a private plugin's counter is its author's
+ // business. Without this the endpoint confirmed a private plugin's existence
+ // and let anyone holding the UUID drive its install_count.
+ const auth = await resolveAuth(req);
+ const viewerId = auth?.userId ?? null;
+ const [target] = await sql`
+ SELECT id, install_count FROM plugins
+ WHERE id = ${id}
+ AND deleted_at IS NULL
+ AND (is_public = true OR author_id = ${viewerId}::uuid)
+ `;
+ if (!target) return error(res, 404, 'not_found', 'plugin not found');
+
+ // One counted install per (IP, plugin) per 30 minutes. A repeat inside the
+ // window is not an error the client should surface (the marketplace fires this
+ // as fire-and-forget), so it answers 200 with counted:false and the unchanged
+ // total rather than a 429 the caller would have to special-case.
+ const dedupe = await limits.pluginInstallDedupe(`${ip}:${id}`);
+ if (!dedupe.success)
+ return json(res, 200, { data: { ok: true, counted: false, install_count: target.install_count } });
+
+ const [row] = await sql`
+ UPDATE plugins SET install_count = install_count + 1
+ WHERE id = ${id} AND deleted_at IS NULL
+ RETURNING install_count
`;
- return json(res, 200, { data: { ok: true } });
+ return json(res, 200, {
+ data: { ok: true, counted: true, install_count: row?.install_count ?? target.install_count + 1 },
+ });
}
diff --git a/api/portfolio/[action].js b/api/portfolio/[action].js
index 1f96c2be8..5a4982e8b 100644
--- a/api/portfolio/[action].js
+++ b/api/portfolio/[action].js
@@ -12,7 +12,7 @@
import { cors, json, method, readJson, wrap, error, validationError, rateLimited } from '../_lib/http.js';
import { solanaConnection } from '../_lib/solana/connection.js';
import { evmFallbackProvider } from '../_lib/evm/rpc.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
+import { limits } from '../_lib/rate-limit.js';
import { getSessionUser, isSameSiteOrigin } from '../_lib/auth.js';
import { requireCsrf } from '../_lib/csrf.js';
import { logAudit } from '../_lib/audit.js';
@@ -20,6 +20,7 @@ import { sql } from '../_lib/db.js';
import { getBalances, walletUsdTotal, invalidateBalances } from '../_lib/balances.js';
import { recoverAgentKey, recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
import { reverseLookupAddress, resolveSolanaRecipient } from '../../src/solana/sns.js';
+import { geckoFetch, htmlToText } from '../_lib/coingecko.js';
import { env } from '../_lib/env.js';
import { z } from 'zod';
@@ -45,6 +46,20 @@ async function lookupSnsCached(address) {
const ETH_ADDR_RE = /^0x[a-fA-F0-9]{40}$/;
const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+// Window length for /history and /asset, clamped to 1..365. Returns null on a
+// value that is not a whole number, which the caller answers with a 400.
+// `parseInt` used to swallow those: `?days=abc` became NaN and survived both
+// Math clamps, so /history handed Postgres `NaN days` (a 500 with a support ref)
+// and /asset silently shipped `chart.days: null` plus a `days=NaN` upstream URL
+// that could never return points.
+function parseDays(url, fallback) {
+ const raw = url.searchParams.get('days');
+ if (raw === null || raw.trim() === '') return fallback;
+ const n = Number(raw);
+ if (!Number.isInteger(n)) return null;
+ return Math.min(365, Math.max(1, n));
+}
+
function parse(schema, raw) {
const r = schema.safeParse(raw);
if (!r.success) {
@@ -188,7 +203,8 @@ async function handleHistory(req, res) {
if (!rl.success) return rateLimited(res, rl);
const url = new URL(req.url, 'http://localhost');
- const days = Math.min(365, Math.max(1, parseInt(url.searchParams.get('days') || '90', 10)));
+ const days = parseDays(url, 90);
+ if (days === null) return error(res, 400, 'validation_error', 'days must be a whole number');
const rows = await sql`
select captured_at, total_usd
@@ -224,7 +240,17 @@ function parseAmountToBaseUnits(amountStr, decimals) {
const [whole, frac = ''] = amountStr.split('.');
const fracPadded = (frac + '0'.repeat(decimals)).slice(0, decimals);
const combined = (whole + fracPadded).replace(/^0+/, '') || '0';
- return BigInt(combined);
+ const units = BigInt(combined);
+ // The schema accepts "0", and any amount below one base unit truncates to the
+ // same place. Both would sign and broadcast a transfer that moves nothing and
+ // still burns a fee, so refuse before we touch a key.
+ if (units === 0n) {
+ const e = new Error(`amount is zero at ${decimals} decimals`);
+ e.code = 'validation_error';
+ e.status = 400;
+ throw e;
+ }
+ return units;
}
async function loadOwnedAgent(userId, agentId) {
@@ -237,7 +263,7 @@ async function loadOwnedAgent(userId, agentId) {
return row || null;
}
-async function sendEvm({ agent, asset, recipient, amount, memo }) {
+async function sendEvm({ agent, asset, recipient, amount, memo, userId }) {
if (!ETH_ADDR_RE.test(recipient)) {
const e = new Error('invalid EVM recipient');
e.code = 'validation_error';
@@ -253,17 +279,21 @@ async function sendEvm({ agent, asset, recipient, amount, memo }) {
}
const chainId = agent.chain_id || 8453;
+ // loadOwnedAgent already proved this user owns the agent; pass the id through
+ // so the key-use and custody rows name the human who authorized the transfer.
+ // `agent.user_id` was always undefined here (the query does not select it), so
+ // every EVM send landed in the audit trail attributed to nobody.
const pkHex = await recoverAgentKey(encryptedKey, {
agentId: agent.id,
- userId: agent.user_id ?? null,
+ userId: userId ?? null,
reason: `portfolio_send_${asset}`,
});
- const { Wallet, parseEther, Contract } = await import('ethers');
+ const { Wallet, Contract } = await import('ethers');
const provider = await evmFallbackProvider(chainId);
const signer = new Wallet(pkHex, provider);
if (asset === 'native') {
- const value = parseEther(amount);
+ const value = parseAmountToBaseUnits(amount, 18);
const tx = await signer.sendTransaction({ to: recipient, value, data: memo ? '0x' + Buffer.from(memo, 'utf8').toString('hex') : undefined });
return { tx_hash: tx.hash, chain_id: chainId };
}
@@ -285,7 +315,7 @@ async function sendEvm({ agent, asset, recipient, amount, memo }) {
async function sendSolana({ agent, asset, recipient, amount, userId }) {
const { address: resolvedRecipient, resolved_from } = await resolveSolanaRecipient(recipient);
if (!resolvedRecipient) {
- const e = new Error('invalid Solana recipient — must be a base58 address or a registered .sol name');
+ const e = new Error('invalid Solana recipient: must be a base58 address or a registered .sol name');
e.code = 'validation_error';
e.status = 400;
throw e;
@@ -299,9 +329,8 @@ async function sendSolana({ agent, asset, recipient, amount, userId }) {
throw e;
}
- const { Connection, PublicKey, Transaction, SystemProgram, LAMPORTS_PER_SOL } = await import('@solana/web3.js');
- const rpcUrl = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
- const conn = solanaConnection({ url: rpcUrl, commitment: 'confirmed' });
+ const { PublicKey, Transaction, SystemProgram } = await import('@solana/web3.js');
+ const conn = solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
const kp = await recoverSolanaAgentKeypair(encryptedSecret, {
userId,
@@ -313,7 +342,10 @@ async function sendSolana({ agent, asset, recipient, amount, userId }) {
const tx = new Transaction();
if (asset === 'native') {
- const lamports = BigInt(Math.round(Number(amount) * LAMPORTS_PER_SOL));
+ // Decimal string to lamports as integers. `Number(amount) * LAMPORTS_PER_SOL`
+ // loses precision above ~9M SOL and can round a value up past the balance,
+ // which the RPC then rejects in preflight for no reason the user can see.
+ const lamports = parseAmountToBaseUnits(amount, 9);
tx.add(SystemProgram.transfer({ fromPubkey: kp.publicKey, toPubkey: recipientPk, lamports }));
} else {
if (!SOL_ADDR_RE.test(asset)) {
@@ -344,7 +376,7 @@ async function sendSolana({ agent, asset, recipient, amount, userId }) {
tx.sign(kp);
// Preflight runs on the RPC and throws synchronously if the tx would fail
- // (insufficient lamports, missing ATA rent, etc.) — that gives us instant
+ // (insufficient lamports, missing ATA rent, etc.), which gives us instant
// validation feedback. We deliberately don't await confirmTransaction here:
// 'confirmed' commitment takes 10-30s under load and the function would
// time out (Vercel default 10s). The signature is the receipt.
@@ -381,7 +413,7 @@ async function handleSend(req, res) {
const out =
body.chain === 'solana'
? await sendSolana({ agent, asset: body.asset, recipient: body.recipient, amount: body.amount, userId: user.id })
- : await sendEvm({ agent, asset: body.asset, recipient: body.recipient, amount: body.amount, memo: body.memo });
+ : await sendEvm({ agent, asset: body.asset, recipient: body.recipient, amount: body.amount, memo: body.memo, userId: user.id });
logAudit({
userId: user.id,
@@ -425,13 +457,44 @@ async function handleSend(req, res) {
// Native maps to SOL on Solana and ETH on EVM (mainnet coin IDs are used for
// the price chart; the holding is read directly from the live balances).
-async function cgFetch(url) {
- const r = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) });
- if (!r.ok) {
- const text = await r.text().catch(() => '');
- throw Object.assign(new Error(`coingecko ${r.status}: ${text.slice(0, 200)}`), { status: 502 });
- }
- return r.json();
+// Market metadata + price history for one asset. Both the native-coin and the
+// contract-addressed lookups return the same CoinGecko shape, so only the two
+// paths differ. Goes through the shared geckoFetch (demo API key, memory cache,
+// stale + durable last-good fallbacks) rather than a bare fetch: the keyless
+// public tier throttles our egress IP within minutes, and a raw fetch turned
+// that into a permanently empty market panel instead of recent data.
+async function loadMarket({ metaPath, chartPath, coingeckoId, days }) {
+ const [meta, chart] = await Promise.all([
+ geckoFetch(metaPath).catch(() => null),
+ geckoFetch(chartPath, { ttlMs: 5 * 60_000 }).catch(() => null),
+ ]);
+
+ const market = meta
+ ? {
+ name: meta.name,
+ price_usd: meta.market_data?.current_price?.usd ?? null,
+ change_24h_pct: meta.market_data?.price_change_percentage_24h ?? null,
+ change_7d_pct: meta.market_data?.price_change_percentage_7d ?? null,
+ change_30d_pct: meta.market_data?.price_change_percentage_30d ?? null,
+ market_cap_usd: meta.market_data?.market_cap?.usd ?? null,
+ total_volume_usd: meta.market_data?.total_volume?.usd ?? null,
+ high_24h_usd: meta.market_data?.high_24h?.usd ?? null,
+ low_24h_usd: meta.market_data?.low_24h?.usd ?? null,
+ ath_usd: meta.market_data?.ath?.usd ?? null,
+ ath_change_pct: meta.market_data?.ath_change_percentage?.usd ?? null,
+ description: htmlToText(meta.description?.en || '').split('. ').slice(0, 2).join('. '),
+ homepage: meta.links?.homepage?.[0] || null,
+ coingecko_id: meta.id || coingeckoId,
+ }
+ : null;
+
+ return {
+ market,
+ symbol: meta?.symbol ? String(meta.symbol).toUpperCase() : null,
+ logo: meta?.image?.small || meta?.image?.thumb || null,
+ points: (chart?.prices || []).map(([t, p]) => ({ t: new Date(t).toISOString(), price: p })),
+ days,
+ };
}
async function handleAsset(req, res) {
@@ -447,12 +510,13 @@ async function handleAsset(req, res) {
const url = new URL(req.url, 'http://localhost');
const chain = String(url.searchParams.get('chain') || '').toLowerCase();
const idRaw = String(url.searchParams.get('id') || '').trim();
- const days = Math.min(365, Math.max(1, parseInt(url.searchParams.get('days') || '30', 10)));
+ const days = parseDays(url, 30);
if (chain !== 'solana' && chain !== 'evm') {
return error(res, 400, 'validation_error', 'chain must be solana or evm');
}
if (!idRaw) return error(res, 400, 'validation_error', 'id required');
+ if (days === null) return error(res, 400, 'validation_error', 'days must be a whole number');
const isNative = idRaw === 'native';
const id = isNative ? 'native' : idRaw;
@@ -525,79 +589,18 @@ async function handleAsset(req, res) {
// 2) Pull market data + price history from CoinGecko.
// For native: use coin id ("solana" or "ethereum").
// For tokens: use /coins/{platform}/contract/{address}.
- let market = null;
- let chartPoints = [];
- try {
- if (isNative) {
- const coinId = chain === 'solana' ? 'solana' : 'ethereum';
- const [meta, chart] = await Promise.all([
- cgFetch(
- `https://api.coingecko.com/api/v3/coins/${coinId}?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false`,
- ).catch(() => null),
- cgFetch(
- `https://api.coingecko.com/api/v3/coins/${coinId}/market_chart?vs_currency=usd&days=${days}`,
- ).catch(() => null),
- ]);
- if (meta) {
- symbol = (meta.symbol || symbol || '').toUpperCase();
- logo = logo || meta.image?.small || meta.image?.thumb || null;
- market = {
- name: meta.name,
- price_usd: meta.market_data?.current_price?.usd ?? null,
- change_24h_pct: meta.market_data?.price_change_percentage_24h ?? null,
- change_7d_pct: meta.market_data?.price_change_percentage_7d ?? null,
- change_30d_pct: meta.market_data?.price_change_percentage_30d ?? null,
- market_cap_usd: meta.market_data?.market_cap?.usd ?? null,
- total_volume_usd: meta.market_data?.total_volume?.usd ?? null,
- high_24h_usd: meta.market_data?.high_24h?.usd ?? null,
- low_24h_usd: meta.market_data?.low_24h?.usd ?? null,
- ath_usd: meta.market_data?.ath?.usd ?? null,
- ath_change_pct: meta.market_data?.ath_change_percentage?.usd ?? null,
- description: (meta.description?.en || '').split('. ').slice(0, 2).join('. '),
- homepage: meta.links?.homepage?.[0] || null,
- coingecko_id: coinId,
- };
- }
- if (chart?.prices?.length) {
- chartPoints = chart.prices.map(([t, p]) => ({ t: new Date(t).toISOString(), price: p }));
- }
- } else {
- const platform = chain === 'solana' ? 'solana' : 'ethereum';
- const [meta, chart] = await Promise.all([
- cgFetch(
- `https://api.coingecko.com/api/v3/coins/${platform}/contract/${encodeURIComponent(id)}`,
- ).catch(() => null),
- cgFetch(
- `https://api.coingecko.com/api/v3/coins/${platform}/contract/${encodeURIComponent(id)}/market_chart?vs_currency=usd&days=${days}`,
- ).catch(() => null),
- ]);
- if (meta) {
- symbol = (meta.symbol || symbol || '').toUpperCase();
- logo = logo || meta.image?.small || meta.image?.thumb || null;
- market = {
- name: meta.name,
- price_usd: meta.market_data?.current_price?.usd ?? null,
- change_24h_pct: meta.market_data?.price_change_percentage_24h ?? null,
- change_7d_pct: meta.market_data?.price_change_percentage_7d ?? null,
- change_30d_pct: meta.market_data?.price_change_percentage_30d ?? null,
- market_cap_usd: meta.market_data?.market_cap?.usd ?? null,
- total_volume_usd: meta.market_data?.total_volume?.usd ?? null,
- high_24h_usd: meta.market_data?.high_24h?.usd ?? null,
- low_24h_usd: meta.market_data?.low_24h?.usd ?? null,
- ath_usd: meta.market_data?.ath?.usd ?? null,
- ath_change_pct: meta.market_data?.ath_change_percentage?.usd ?? null,
- description: (meta.description?.en || '').split('. ').slice(0, 2).join('. '),
- homepage: meta.links?.homepage?.[0] || null,
- coingecko_id: meta.id,
- };
- }
- if (chart?.prices?.length) {
- chartPoints = chart.prices.map(([t, p]) => ({ t: new Date(t).toISOString(), price: p }));
- }
- }
- } catch (e) {
- console.error('[portfolio/asset] coingecko fetch failed', e?.message);
- }
+ 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({
+ metaPath: isNative
+ ? `${base}?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false`
+ : base,
+ chartPath: `${base}/market_chart?vs_currency=usd&days=${days}`,
+ coingeckoId: isNative ? platform : id,
+ days,
+ });
+ symbol = cgSymbol || symbol;
+ logo = logo || cgLogo;
// If CoinGecko gave us a more reliable spot price, use it for the holding
// USD calculation as well so the page is internally consistent.
diff --git a/api/pump/[action].js b/api/pump/[action].js
index d43a67fc6..7f1084ebe 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -157,6 +157,30 @@ async function resolveAuth(req) {
return null;
}
+/**
+ * Session lookup for the handlers that sign and BROADCAST with an agent's
+ * custodial keypair server-side (launch-agent, the *-agent fee cranks). Those
+ * need nothing from the caller but a cookie, so a cross-site POST alone was
+ * enough to mint a coin or sweep fees — the exact threat resolveAuth() guards
+ * against, which these paths were not routed through. Same rule as resolveAuth:
+ * the cookie path must prove same-site intent, reads stay open.
+ *
+ * Returns the session user, or null after writing the 401/403 response.
+ */
+async function requireSessionUser(req, res) {
+ const user = await getSessionUser(req);
+ if (!user) {
+ error(res, 401, 'unauthorized', 'sign in required');
+ return null;
+ }
+ const isRead = ['GET', 'HEAD', 'OPTIONS'].includes(String(req.method || '').toUpperCase());
+ if (!isRead && !isSameSiteOrigin(req)) {
+ error(res, 403, 'forbidden', 'cross-site request blocked');
+ return null;
+ }
+ return user;
+}
+
const wrapped = wrap(async (req, res) => {
const action = req.query?.action;
switch (action) {
@@ -1665,8 +1689,8 @@ async function handleLaunchAgent(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ const user = await requireSessionUser(req, res);
+ if (!user) return;
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
@@ -3790,15 +3814,14 @@ async function handleSearch(req, res) {
// ── deliver-telegram ──────────────────────────────────────────────────────────
-import { z as _z } from 'zod';
-const _deliverSchema = _z.object({
- chatId: _z.union([_z.string(), _z.number()]),
- signal: _z.object({
- kind: _z.enum(['mint', 'whale', 'claim', 'graduation']),
- mint: _z.string(),
- summary: _z.string(),
- refs: _z.array(_z.string()).optional(),
- ts: _z.number().optional(),
+const _deliverSchema = z.object({
+ chatId: z.union([z.string(), z.number()]),
+ signal: z.object({
+ kind: z.enum(['mint', 'whale', 'claim', 'graduation']),
+ mint: z.string(),
+ summary: z.string(),
+ refs: z.array(z.string()).optional(),
+ ts: z.number().optional(),
}),
});
@@ -3813,7 +3836,11 @@ async function handleDeliverTelegram(req, res) {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl, 'too many delivery requests');
const botToken = process.env.TELEGRAM_BOT_TOKEN;
- if (!botToken) return error(res, 500, 'misconfigured', 'TELEGRAM_BOT_TOKEN is not set');
+ // An absent bot token is a deployment gap, not a server fault: 503 +
+ // not_configured is what every sibling handler answers, and it tells a client
+ // to stop retrying rather than to report a bug.
+ if (!botToken)
+ return error(res, 503, 'not_configured', 'Telegram delivery is not configured');
const raw = await readJson(req);
const { chatId, signal } = parse(_deliverSchema, raw);
const { sendTelegramSignal } = await import('../../src/pump/telegram-delivery.js');
@@ -4602,11 +4629,8 @@ async function signSendWithAgent({ network, agentKeypair, instructions, extraSig
// wallet is the on-chain creator (agent_authority) of the coin. Returns
// { agent, mintRow, loaded, creator } or sends an error and returns null.
async function resolveAgentFeeContext(req, res, body) {
- const user = await getSessionUser(req);
- if (!user) {
- error(res, 401, 'unauthorized', 'sign in required');
- return null;
- }
+ const user = await requireSessionUser(req, res);
+ if (!user) return null;
const agent = await resolveLaunchAgentId({
userId: user.id,
diff --git a/api/pump/coin-intel.js b/api/pump/coin-intel.js
index efb16338d..b4b72c892 100644
--- a/api/pump/coin-intel.js
+++ b/api/pump/coin-intel.js
@@ -13,7 +13,7 @@
* IP rate-limited; every number traces to an on-chain trade we observed.
*/
-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';
@@ -113,10 +113,15 @@ export default wrap(async (req, res) => {
// ── single coin ───────────────────────────────────────────────────────────
if (mint) {
- if (mint.length < 32 || mint.length > 64) return json(res, 400, { error: 'invalid mint' });
+ // Same envelope every other handler answers with ({error, error_description});
+ // a bare {error} left every client that reads error_description with undefined.
+ if (mint.length < 32 || mint.length > 64) {
+ return error(res, 400, 'invalid_mint', 'mint must be 32 to 64 characters');
+ }
const [row] = await sql`select * from pump_coin_intel where mint = ${mint} limit 1`;
if (!row) {
- return json(res, 404, { error: 'not_found', mint, hint: 'coin not observed (too old, or launched before the intel engine, or still mid-observation)' });
+ const hint = 'coin not observed (too old, or launched before the intel engine, or still mid-observation)';
+ return json(res, 404, { error: 'not_found', error_description: hint, mint, hint });
}
const out = shapeRow(row);
out.smart_money_notable = Array.isArray(row.smart_money_notable) ? row.smart_money_notable : [];
diff --git a/src/agent-detail.css b/src/agent-detail.css
index 33959d227..2865b3484 100644
--- a/src/agent-detail.css
+++ b/src/agent-detail.css
@@ -2377,6 +2377,29 @@ div.ad-hero-avatar canvas {
color: var(--ad-dim);
text-align: center;
}
+.payment-qr-swap {
+ border: 0;
+ background: none;
+ padding: 4px 6px;
+ border-radius: 6px;
+ font: inherit;
+ font-size: 11px;
+ color: var(--ad-muted);
+ text-decoration: underline;
+ cursor: pointer;
+ transition: color 0.15s ease, background 0.15s ease;
+}
+.payment-qr-swap:hover {
+ color: var(--ad-text);
+ background: rgba(255, 255, 255, 0.06);
+}
+.payment-qr-swap:active {
+ background: rgba(255, 255, 255, 0.1);
+}
+.payment-qr-swap:focus-visible {
+ outline: 2px solid var(--ad-text);
+ outline-offset: 2px;
+}
.payment-status {
font-size: 13px;
margin-top: 12px;
diff --git a/src/monitor.js b/src/monitor.js
index e4aca9101..b2e27a880 100644
--- a/src/monitor.js
+++ b/src/monitor.js
@@ -71,7 +71,7 @@ async function loadHomeStats() {
$('t-widgets').textContent = nf.format(s.widgets);
$('t-chains').textContent = nf.format(s.chains);
}
- if (platform.status === 'fulfilled') {
+ if (platform.status === 'fulfilled' && platform.value.available) {
$('t-avatars').textContent = nf.format(platform.value.avatars);
$('t-countries').textContent = nf.format(platform.value.countries);
}
diff --git a/src/shared/skill-purchase.js b/src/shared/skill-purchase.js
index 4c57f7007..b21ad5a9b 100644
--- a/src/shared/skill-purchase.js
+++ b/src/shared/skill-purchase.js
@@ -1433,12 +1433,48 @@ async function startQrPurchase() {
url.searchParams.set('label', purchase.label || `Skill: ${skill}`);
url.searchParams.set('message', purchase.message || `Unlock '${skill}'`);
+ // Solana Pay TRANSACTION request for the same pending purchase. The server
+ // builds the transfer (api/purchase/skill.js), which is what lets the platform
+ // sponsor the network fee for a buyer holding only USDC, create a missing
+ // creator token account, and settle the treasury fee leg in one signature.
+ // The transfer-request link above stays as the fallback rail for wallets that
+ // do not implement transaction requests.
+ const txRequestUrl = `solana:${encodeURIComponent(
+ `${window.location.origin}/api/purchase/skill?reference=${encodeURIComponent(purchase.reference)}`,
+ )}`;
+
const qrEl = $('payment-qr');
if (qrEl) {
- qrEl.innerHTML = `<canvas id="payment-qr-canvas" width="240" height="240"></canvas>
- <p class="muted small">Scan with a Solana Pay wallet (Phantom mobile, Solflare mobile, etc.)</p>`;
const QRCode = await import('qrcode');
- await (QRCode.default ?? QRCode).toCanvas(document.getElementById('payment-qr-canvas'), url.toString(), { width: 240 });
+ const rails = {
+ sponsored: {
+ url: txRequestUrl,
+ note: 'Scan with a Solana Pay wallet (Phantom mobile, Solflare mobile, etc.). No SOL needed: we cover the network fee.',
+ swap: 'Wallet rejected the code? Use a direct transfer',
+ },
+ direct: {
+ url: url.toString(),
+ note: `Scan to send ${human} directly from your wallet. You pay the Solana network fee.`,
+ swap: 'Back to the fee-free code',
+ },
+ };
+ const drawRail = async (name) => {
+ const rail = rails[name];
+ qrEl.innerHTML = `<canvas id="payment-qr-canvas" width="240" height="240"></canvas>
+ <p class="muted small">${escapeHtml(rail.note)}</p>
+ <button type="button" class="payment-qr-swap" data-qr-swap>${escapeHtml(rail.swap)}</button>`;
+ await (QRCode.default ?? QRCode).toCanvas(
+ document.getElementById('payment-qr-canvas'),
+ rail.url,
+ { width: 240 },
+ );
+ qrEl.querySelector('[data-qr-swap]')?.addEventListener('click', () => {
+ drawRail(name === 'sponsored' ? 'direct' : 'sponsored').catch((e) =>
+ log.error('[skill-purchase] qr swap failed', e),
+ );
+ });
+ };
+ await drawRail('sponsored');
}
const qrSuccess = async () => {