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.

production fixes: error handling, Helius DAS, bonfida CJS, registry safety

nirholas35d9ab29cf9e
diff --git a/api/_lib/balances.js b/api/_lib/balances.js
index 2026230a7..1a76dccd3 100644
--- a/api/_lib/balances.js
+++ b/api/_lib/balances.js
@@ -1,21 +1,28 @@
// Live on-chain balance + USD-price helpers, shared by /api/wallet/balances and
-// /api/portfolio. Server-side memoizes results per (chain, address) for 60s to
-// shield upstream RPCs and CoinGecko from per-page-load fan-out.
-
-const RPC_CACHE_TTL_MS = 60_000;
-const _cache = new Map(); // key: `${chain}:${address}` → { at, value }
-
-function cacheGet(key) {
- const hit = _cache.get(key);
- if (!hit) return null;
- if (Date.now() - hit.at > RPC_CACHE_TTL_MS) {
- _cache.delete(key);
- return null;
- }
- return hit.value;
-}
-function cacheSet(key, value) {
- _cache.set(key, { at: Date.now(), value });
+// /api/portfolio.
+//
+// Optimization strategy (2026-05-25):
+// - Solana: single Helius `getAssetsByOwner` (DAS) call returns native SOL +
+// all fungible token balances *with metadata*. Eliminates the previous
+// N+1 (getTokenAccountsByOwner + N×getAsset) burn (~200 Helius credits
+// per portfolio → ~10).
+// - Falls back to public RPC + token_metadata cache when Helius is missing
+// or rate-limited. DAS isn't available on public RPC, so metadata then
+// comes from our Postgres `token_metadata` cache.
+// - Jupiter Lite Price API replaces CoinGecko for Solana token prices —
+// faster, no rate limits, knows pump.fun bondings.
+// - Cache layer uses Upstash Redis if configured (shared across function
+// instances), in-memory otherwise.
+
+import { cacheGet, cacheSet, cacheDel } from './cache.js';
+import { getMetadataForMints } from './token-metadata.js';
+
+const BALANCES_TTL_S = 60;
+
+const PUBLIC_SOL_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+function heliusRpc() {
+ const key = process.env.HELIUS_API_KEY;
+ return key ? `https://mainnet.helius-rpc.com/?api-key=${key}` : null;
}
async function fetchJson(url, opts = {}) {
@@ -27,16 +34,6 @@ async function fetchJson(url, opts = {}) {
return r.json();
}
-// Helius primary, public mainnet-beta fallback. Helius is required for `getAsset`
-// (DAS) — token metadata silently degrades when we fall back, but balances still
-// resolve, which is better than 503ing the whole portfolio when Helius is rate-
-// limited or out of credits.
-const PUBLIC_SOL_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
-function heliusRpc() {
- const key = process.env.HELIUS_API_KEY;
- return key ? `https://mainnet.helius-rpc.com/?api-key=${key}` : null;
-}
-
async function solRpc(body, { allowFallback = true } = {}) {
const helius = heliusRpc();
if (helius) {
@@ -58,7 +55,184 @@ async function solRpc(body, { allowFallback = true } = {}) {
});
}
-async function getSolanaBalances(address) {
+// -- Solana price helpers --
+
+async function jupiterPrices(mints) {
+ if (mints.length === 0) return {};
+ const out = {};
+ // Jupiter caps each request at ~100 ids
+ for (let i = 0; i < mints.length; i += 100) {
+ const chunk = mints.slice(i, i + 100).join(',');
+ try {
+ const data = await fetchJson(`https://lite-api.jup.ag/price/v3?ids=${chunk}`);
+ if (data && typeof data === 'object') Object.assign(out, data);
+ } catch (err) {
+ console.warn('[balances] jupiter price chunk failed:', err?.message);
+ }
+ }
+ return out;
+}
+
+const SOL_MINT = 'So11111111111111111111111111111111111111112';
+
+async function solNativePrice() {
+ try {
+ const data = await fetchJson(`https://lite-api.jup.ag/price/v3?ids=${SOL_MINT}`);
+ const usd = data?.[SOL_MINT]?.usdPrice ?? data?.[SOL_MINT]?.price ?? 0;
+ return Number(usd) || 0;
+ } catch {
+ try {
+ const cg = await fetchJson(
+ 'https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd&include_24hr_change=true',
+ );
+ return cg?.solana?.usd ?? 0;
+ } catch {
+ return 0;
+ }
+ }
+}
+
+// -- Solana balance path: Helius DAS getAssetsByOwner --
+
+async function getSolanaBalancesViaDas(address) {
+ const helius = heliusRpc();
+ if (!helius) return null; // signal caller to take fallback path
+
+ let allItems = [];
+ let nativeLamports = 0;
+ let page = 1;
+ // Helius paginates at 1000/page; loop until empty.
+ while (page < 6) {
+ const resp = await fetchJson(helius, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 'getAssetsByOwner',
+ method: 'getAssetsByOwner',
+ params: {
+ ownerAddress: address,
+ page,
+ limit: 1000,
+ displayOptions: { showFungible: true, showNativeBalance: true },
+ },
+ }),
+ });
+ const result = resp?.result;
+ if (!result) break;
+ if (page === 1 && result.nativeBalance) {
+ nativeLamports = Number(result.nativeBalance.lamports || 0);
+ }
+ const items = Array.isArray(result.items) ? result.items : [];
+ allItems = allItems.concat(items);
+ if (items.length < 1000) break;
+ page += 1;
+ }
+
+ const fungible = allItems
+ .filter((a) => a?.interface === 'FungibleToken' || a?.interface === 'FungibleAsset' || a?.token_info)
+ .map((a) => {
+ const ti = a.token_info || {};
+ const decimals = ti.decimals ?? 0;
+ const rawBalance = Number(ti.balance || 0);
+ if (!rawBalance) return null;
+ const amount = rawBalance / Math.pow(10, decimals);
+ const md = a?.content?.metadata || {};
+ const symbol = ti.symbol || md.symbol || a.id.slice(0, 6);
+ const name = md.name || symbol;
+ const logo = a?.content?.links?.image || a?.content?.files?.[0]?.uri || null;
+ const priceFromHelius = ti.price_info?.price_per_token ?? null;
+ return { mint: a.id, decimals, amount, symbol, name, logo, priceFromHelius };
+ })
+ .filter(Boolean)
+ .filter((t) => t.amount > 0);
+
+ // Persist metadata for everything we just resolved so other callers
+ // (which may not use DAS) can hit cache instead of re-fetching.
+ const metaPayload = fungible.map((t) => ({
+ mint: t.mint,
+ symbol: t.symbol,
+ name: t.name,
+ logo: t.logo,
+ decimals: t.decimals,
+ }));
+ if (metaPayload.length > 0) {
+ // Fire-and-forget — never block balance response on cache write.
+ import('./token-metadata.js')
+ .then((mod) => mod.getMetadataForMints([])) // ensure module loaded
+ .catch(() => {});
+ // Direct write (cheaper than going through getMetadataForMints):
+ try {
+ const { sql } = await import('./db.js');
+ await sql`
+ INSERT INTO token_metadata (mint, chain, symbol, name, logo, decimals, source, refreshed_at)
+ SELECT * FROM ${sql(
+ metaPayload.map((m) => [
+ m.mint,
+ 'solana',
+ m.symbol,
+ m.name,
+ m.logo,
+ m.decimals,
+ 'helius-das',
+ new Date(),
+ ]),
+ )}
+ ON CONFLICT (mint) DO UPDATE SET
+ symbol = EXCLUDED.symbol,
+ name = EXCLUDED.name,
+ logo = EXCLUDED.logo,
+ decimals = EXCLUDED.decimals,
+ refreshed_at = EXCLUDED.refreshed_at
+ `;
+ } catch (err) {
+ console.warn('[balances] token_metadata persist failed:', err?.message);
+ }
+ }
+
+ // Prices: trust Helius price_info first, fall back to Jupiter for any gaps.
+ const missingPrice = fungible.filter((t) => !t.priceFromHelius).map((t) => t.mint);
+ const jupPrices = missingPrice.length > 0 ? await jupiterPrices(missingPrice) : {};
+ const solUsd = await solNativePrice();
+
+ const tokens = fungible
+ .map((t) => {
+ const price =
+ t.priceFromHelius ??
+ Number(jupPrices?.[t.mint]?.usdPrice ?? jupPrices?.[t.mint]?.price ?? 0) ??
+ 0;
+ return {
+ symbol: t.symbol,
+ name: t.name,
+ mint: t.mint,
+ decimals: t.decimals,
+ amount: t.amount,
+ price,
+ change24h: null,
+ usd: t.amount * price,
+ logo: t.logo,
+ };
+ })
+ .sort((a, b) => (b.usd || 0) - (a.usd || 0));
+
+ return {
+ chain: 'solana',
+ address,
+ native: {
+ symbol: 'SOL',
+ name: 'Solana',
+ amount: nativeLamports / 1e9,
+ price: solUsd,
+ change24h: null,
+ usd: (nativeLamports / 1e9) * solUsd,
+ },
+ tokens,
+ };
+}
+
+// -- Solana balance fallback: plain RPC + DB metadata cache --
+
+async function getSolanaBalancesFallback(address) {
const solResp = await solRpc({ jsonrpc: '2.0', id: 1, method: 'getBalance', params: [address] });
const lamports = solResp.result?.value ?? 0;
const solAmount = lamports / 1e9;
@@ -83,77 +257,34 @@ async function getSolanaBalances(address) {
if (!tokenAmount || !tokenAmount.uiAmount || tokenAmount.uiAmount === 0) return null;
return { mint, amount: tokenAmount.uiAmount, decimals: tokenAmount.decimals };
})
- .filter(Boolean)
- .sort((a, b) => b.amount - a.amount);
-
- // CoinGecko caps each request at ~100 contract addresses; chunk to stay safe.
- const cgTokenPrices = {};
- for (let i = 0; i < fungible.length; i += 80) {
- const chunk = fungible.slice(i, i + 80).map((t) => t.mint).join(',');
- try {
- const part = await fetchJson(
- `https://api.coingecko.com/api/v3/simple/token_price/solana?contract_addresses=${chunk}&vs_currencies=usd&include_24hr_change=true`,
- );
- Object.assign(cgTokenPrices, part);
- } catch {
- // best-effort
- }
- }
+ .filter(Boolean);
- let solUsdPrice = 0;
- let solChange24h = 0;
- try {
- const cgSol = await fetchJson(
- 'https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd&include_24hr_change=true',
- );
- solUsdPrice = cgSol?.solana?.usd ?? 0;
- solChange24h = cgSol?.solana?.usd_24h_change ?? 0;
- } catch {
- // best-effort
- }
+ const mints = fungible.map((t) => t.mint);
+ const [metadata, jupPrices, solUsd] = await Promise.all([
+ getMetadataForMints(mints),
+ jupiterPrices(mints),
+ solNativePrice(),
+ ]);
- // DAS metadata (getAsset) is Helius-only — skip entirely if no key, since
- // public mainnet-beta returns "method not found" for every mint.
- const helius = heliusRpc();
- const metaResults = helius
- ? await Promise.all(
- fungible.map((t) =>
- fetchJson(helius, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- jsonrpc: '2.0',
- id: 'meta',
- method: 'getAsset',
- params: { id: t.mint },
- }),
- }).catch(() => null),
- ),
- )
- : fungible.map(() => null);
-
- const tokens = fungible.map((t, i) => {
- const priceInfo = cgTokenPrices[t.mint.toLowerCase()] || cgTokenPrices[t.mint] || {};
- const price = priceInfo.usd ?? 0;
- const change24h = priceInfo.usd_24h_change ?? null;
- const das = metaResults[i];
- const symbol = das?.result?.content?.metadata?.symbol || t.mint.slice(0, 6);
- const name = das?.result?.content?.metadata?.name || symbol;
- const logo = das?.result?.content?.links?.image || null;
- return {
- symbol,
- name,
- mint: t.mint,
- decimals: t.decimals,
- amount: t.amount,
- price,
- change24h,
- usd: t.amount * price,
- logo,
- };
- });
+ const tokens = fungible
+ .map((t) => {
+ const md = metadata.get(t.mint) || {};
+ const priceInfo = jupPrices?.[t.mint] || {};
+ const price = Number(priceInfo.usdPrice ?? priceInfo.price ?? 0);
+ return {
+ symbol: md.symbol || t.mint.slice(0, 6),
+ name: md.name || md.symbol || t.mint.slice(0, 6),
+ mint: t.mint,
+ decimals: t.decimals,
+ amount: t.amount,
+ price,
+ change24h: null,
+ usd: t.amount * price,
+ logo: md.logo || null,
+ };
+ })
+ .sort((a, b) => (b.usd || 0) - (a.usd || 0));
- tokens.sort((a, b) => (b.usd || 0) - (a.usd || 0));
return {
chain: 'solana',
address,
@@ -161,14 +292,26 @@ async function getSolanaBalances(address) {
symbol: 'SOL',
name: 'Solana',
amount: solAmount,
- price: solUsdPrice,
- change24h: solChange24h,
- usd: solAmount * solUsdPrice,
+ price: solUsd,
+ change24h: null,
+ usd: solAmount * solUsd,
},
tokens,
};
}
+async function getSolanaBalances(address) {
+ try {
+ const viaDas = await getSolanaBalancesViaDas(address);
+ if (viaDas) return viaDas;
+ } catch (err) {
+ console.warn('[balances] DAS path failed, using fallback:', err?.message);
+ }
+ return getSolanaBalancesFallback(address);
+}
+
+// -- EVM (Alchemy) — unchanged behavior, kept on CoinGecko since Jupiter is Solana-only --
+
async function getEvmBalances(address) {
const alchemyKey = process.env.ALCHEMY_API_KEY;
if (!alchemyKey) {
@@ -205,8 +348,9 @@ async function getEvmBalances(address) {
}),
});
- const rawTokens = (tokenBalResp.result?.tokenBalances ?? [])
- .filter((t) => t.tokenBalance && t.tokenBalance !== '0x0' && t.tokenBalance !== '0x');
+ const rawTokens = (tokenBalResp.result?.tokenBalances ?? []).filter(
+ (t) => t.tokenBalance && t.tokenBalance !== '0x0' && t.tokenBalance !== '0x',
+ );
const metadataResults = await Promise.allSettled(
rawTokens.map((t) =>
@@ -286,16 +430,16 @@ async function getEvmBalances(address) {
}
export async function getBalances({ chain, address }) {
- const key = `${chain}:${address}`;
- const cached = cacheGet(key);
+ const key = `bal:${chain}:${address}`;
+ const cached = await cacheGet(key);
if (cached) return cached;
const value = chain === 'solana' ? await getSolanaBalances(address) : await getEvmBalances(address);
- cacheSet(key, value);
+ await cacheSet(key, value, BALANCES_TTL_S);
return value;
}
-export function invalidateBalances({ chain, address }) {
- _cache.delete(`${chain}:${address}`);
+export async function invalidateBalances({ chain, address }) {
+ await cacheDel(`bal:${chain}:${address}`);
}
export function walletUsdTotal(balances) {
diff --git a/api/_lib/cache.js b/api/_lib/cache.js
new file mode 100644
index 000000000..3f592702c
--- /dev/null
+++ b/api/_lib/cache.js
@@ -0,0 +1,88 @@
+// Shared cache adapter — Upstash Redis (REST) primary, in-memory fallback.
+//
+// Why: Vercel serverless functions are stateless per-instance. Our previous
+// in-memory Map cache was wiped on every cold start, which is *most* requests
+// under low traffic. Upstash REST works on edge + node, no socket pooling,
+// and the free tier (10k cmd/day) easily covers our portfolio/balances volume.
+//
+// Falls back to in-memory transparently when UPSTASH_REDIS_REST_URL is unset,
+// so dev + tests need no extra config.
+//
+// Env:
+// UPSTASH_REDIS_REST_URL — https://<region>.upstash.io
+// UPSTASH_REDIS_REST_TOKEN — REST API token (read+write)
+
+const memCache = new Map();
+const MEM_DEFAULT_TTL_MS = 60_000;
+
+function memSet(key, value, ttlSeconds) {
+ const ttlMs = (ttlSeconds && ttlSeconds * 1000) || MEM_DEFAULT_TTL_MS;
+ memCache.set(key, { value, expiresAt: Date.now() + ttlMs });
+}
+function memGet(key) {
+ const hit = memCache.get(key);
+ if (!hit) return null;
+ if (Date.now() > hit.expiresAt) {
+ memCache.delete(key);
+ return null;
+ }
+ return hit.value;
+}
+function memDel(key) {
+ memCache.delete(key);
+}
+
+function redisConfigured() {
+ return Boolean(process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN);
+}
+
+async function redisCmd(args) {
+ const r = await fetch(process.env.UPSTASH_REDIS_REST_URL, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${process.env.UPSTASH_REDIS_REST_TOKEN}`,
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify(args),
+ });
+ if (!r.ok) throw new Error(`upstash ${r.status}: ${await r.text().catch(() => '')}`);
+ const json = await r.json();
+ if (json.error) throw new Error(`upstash error: ${json.error}`);
+ return json.result;
+}
+
+export async function cacheGet(key) {
+ if (!redisConfigured()) return memGet(key);
+ try {
+ const raw = await redisCmd(['GET', key]);
+ if (raw == null) return null;
+ return JSON.parse(raw);
+ } catch (err) {
+ console.warn('[cache] redis GET failed, using memory fallback:', err?.message);
+ return memGet(key);
+ }
+}
+
+export async function cacheSet(key, value, ttlSeconds = 60) {
+ if (!redisConfigured()) return memSet(key, value, ttlSeconds);
+ try {
+ const payload = JSON.stringify(value);
+ await redisCmd(['SET', key, payload, 'EX', String(ttlSeconds)]);
+ } catch (err) {
+ console.warn('[cache] redis SET failed, using memory fallback:', err?.message);
+ memSet(key, value, ttlSeconds);
+ }
+}
+
+export async function cacheDel(key) {
+ if (!redisConfigured()) return memDel(key);
+ try {
+ await redisCmd(['DEL', key]);
+ } catch {
+ memDel(key);
+ }
+}
+
+export function cacheBackend() {
+ return redisConfigured() ? 'upstash' : 'memory';
+}
diff --git a/api/_lib/migrations/2026-05-25-marketplace-social-rollforward.sql b/api/_lib/migrations/2026-05-25-marketplace-social-rollforward.sql
new file mode 100644
index 000000000..f62a8a9a0
--- /dev/null
+++ b/api/_lib/migrations/2026-05-25-marketplace-social-rollforward.sql
@@ -0,0 +1,71 @@
+-- Roll-forward for drifted 2026-05-25-marketplace-and-social-tables.sql
+-- Idempotent: all CREATE IF NOT EXISTS / ADD COLUMN IF NOT EXISTS.
+
+BEGIN;
+
+CREATE TABLE IF NOT EXISTS agent_reviews (
+ id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ rating int NOT NULL CHECK (rating BETWEEN 1 AND 5),
+ review text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (agent_id, user_id)
+);
+ALTER TABLE agent_reviews ADD COLUMN IF NOT EXISTS rating int;
+ALTER TABLE agent_reviews ADD COLUMN IF NOT EXISTS review text;
+ALTER TABLE agent_reviews ADD COLUMN IF NOT EXISTS updated_at timestamptz NOT NULL DEFAULT now();
+CREATE INDEX IF NOT EXISTS agent_reviews_agent_id ON agent_reviews(agent_id);
+CREATE INDEX IF NOT EXISTS agent_reviews_user_id ON agent_reviews(user_id);
+
+CREATE TABLE IF NOT EXISTS x_triggers (
+ id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ agent_id uuid REFERENCES agent_identities(id) ON DELETE SET NULL,
+ kind text NOT NULL,
+ config jsonb NOT NULL DEFAULT '{}',
+ auto_publish boolean NOT NULL DEFAULT false,
+ enabled boolean NOT NULL DEFAULT true,
+ last_fired_at timestamptz,
+ last_state jsonb,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+ALTER TABLE x_triggers ADD COLUMN IF NOT EXISTS auto_publish boolean NOT NULL DEFAULT false;
+ALTER TABLE x_triggers ADD COLUMN IF NOT EXISTS last_state jsonb;
+CREATE INDEX IF NOT EXISTS x_triggers_user_id ON x_triggers(user_id) WHERE enabled;
+CREATE INDEX IF NOT EXISTS x_triggers_agent_id ON x_triggers(agent_id) WHERE enabled;
+
+CREATE TABLE IF NOT EXISTS x_scheduled_posts (
+ id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ agent_id uuid REFERENCES agent_identities(id) ON DELETE SET NULL,
+ text text NOT NULL,
+ scheduled_at timestamptz NOT NULL,
+ published_at timestamptz,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+ALTER TABLE x_scheduled_posts ADD COLUMN IF NOT EXISTS published_at timestamptz;
+CREATE INDEX IF NOT EXISTS x_scheduled_posts_pending
+ ON x_scheduled_posts(scheduled_at) WHERE published_at IS NULL;
+
+CREATE TABLE IF NOT EXISTS x_pending_reviews (
+ id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ trigger_id uuid REFERENCES x_triggers(id) ON DELETE SET NULL,
+ agent_id uuid REFERENCES agent_identities(id) ON DELETE SET NULL,
+ text text NOT NULL,
+ reviewed_at timestamptz,
+ approved boolean,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+ALTER TABLE x_pending_reviews ADD COLUMN IF NOT EXISTS trigger_id uuid REFERENCES x_triggers(id) ON DELETE SET NULL;
+ALTER TABLE x_pending_reviews ADD COLUMN IF NOT EXISTS reviewed_at timestamptz;
+ALTER TABLE x_pending_reviews ADD COLUMN IF NOT EXISTS approved boolean;
+CREATE INDEX IF NOT EXISTS x_pending_reviews_user_pending
+ ON x_pending_reviews(user_id) WHERE reviewed_at IS NULL;
+
+ALTER TABLE club_tips ADD COLUMN IF NOT EXISTS amount_atomics numeric;
+ALTER TABLE club_tips ADD COLUMN IF NOT EXISTS paid_at timestamptz;
+
+COMMIT;
diff --git a/api/_lib/migrations/2026-05-25-token-metadata-cache.sql b/api/_lib/migrations/2026-05-25-token-metadata-cache.sql
new file mode 100644
index 000000000..9aa7a67c1
--- /dev/null
+++ b/api/_lib/migrations/2026-05-25-token-metadata-cache.sql
@@ -0,0 +1,29 @@
+-- Migration: token_metadata — server-side cache of Solana token metadata
+-- (symbol/name/logo/decimals) keyed by mint. Resolved via Helius DAS once,
+-- then served from Postgres on every subsequent portfolio load. This is the
+-- single biggest Helius-credit saver: getAsset is ~10 credits per call, and
+-- mint metadata is effectively immutable.
+--
+-- refreshed_at lets us TTL stale rows (e.g. logo URL went 404).
+--
+-- Apply: npm run db:migrate -- --apply --file 2026-05-25-token-metadata-cache.sql
+-- Idempotent.
+
+begin;
+
+create table if not exists token_metadata (
+ mint text primary key,
+ chain text not null default 'solana',
+ symbol text,
+ name text,
+ logo text,
+ decimals smallint,
+ source text, -- 'helius-das' | 'jupiter' | 'manual'
+ refreshed_at timestamptz not null default now(),
+ created_at timestamptz not null default now()
+);
+
+create index if not exists token_metadata_chain on token_metadata(chain);
+create index if not exists token_metadata_refreshed on token_metadata(refreshed_at);
+
+commit;
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 06e33dadb..6bfa25149 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -48,6 +48,23 @@ create unique index if not exists user_subdomains_label_parent
create index if not exists user_subdomains_user
on user_subdomains(user_id, created_at desc);
+-- ── token_metadata — server cache of Solana token info (symbol/name/logo) ──
+-- Resolved once via Helius DAS, then served from Postgres on every subsequent
+-- portfolio load. Biggest Helius-credit saver in the system.
+create table if not exists token_metadata (
+ mint text primary key,
+ chain text not null default 'solana',
+ symbol text,
+ name text,
+ logo text,
+ decimals smallint,
+ source text,
+ refreshed_at timestamptz not null default now(),
+ created_at timestamptz not null default now()
+);
+create index if not exists token_metadata_chain on token_metadata(chain);
+create index if not exists token_metadata_refreshed on token_metadata(refreshed_at);
+
-- ── avatars (GLBs stored in R2) ─────────────────────────────────────────────
create table if not exists avatars (
id uuid primary key default gen_random_uuid(),
diff --git a/api/_lib/token-metadata.js b/api/_lib/token-metadata.js
new file mode 100644
index 000000000..2af0d694c
--- /dev/null
+++ b/api/_lib/token-metadata.js
@@ -0,0 +1,148 @@
+// Solana token metadata resolver — Postgres cache primary, Helius DAS on miss.
+//
+// Why: getAsset/searchAssets are the most expensive Helius calls (~10 credits
+// each). Mint metadata (symbol, name, logo, decimals) is effectively immutable,
+// so we resolve a mint *once* and serve from `token_metadata` forever after.
+//
+// Cache flow for getMetadataForMints(mints[]):
+// 1. SELECT cached rows from token_metadata
+// 2. Resolve cache misses via Helius getAssetBatch (single RPC, up to 1000 mints)
+// 3. INSERT new rows (ON CONFLICT DO UPDATE — refresh stale logos)
+//
+// Falls back gracefully:
+// - no Helius key → returns only cached + bare {mint, symbol: mint.slice(0,6)}
+// - DB unreachable → in-memory map for the request lifetime
+
+import { sql } from './db.js';
+
+const REFRESH_AFTER_MS = 1000 * 60 * 60 * 24 * 30; // 30 days
+
+function heliusRpcUrl() {
+ const key = process.env.HELIUS_API_KEY;
+ return key ? `https://mainnet.helius-rpc.com/?api-key=${key}` : null;
+}
+
+function bareEntry(mint) {
+ return { mint, symbol: mint.slice(0, 6), name: mint.slice(0, 6), logo: null, decimals: null };
+}
+
+async function fetchFromCache(mints) {
+ if (mints.length === 0) return new Map();
+ try {
+ const rows = await sql`
+ SELECT mint, symbol, name, logo, decimals, refreshed_at
+ FROM token_metadata
+ WHERE mint = ANY(${mints}) AND chain = 'solana'
+ `;
+ const out = new Map();
+ const now = Date.now();
+ for (const r of rows) {
+ const age = now - new Date(r.refreshed_at).getTime();
+ if (age > REFRESH_AFTER_MS) continue; // stale — re-resolve
+ out.set(r.mint, {
+ mint: r.mint,
+ symbol: r.symbol,
+ name: r.name,
+ logo: r.logo,
+ decimals: r.decimals,
+ });
+ }
+ return out;
+ } catch (err) {
+ console.warn('[token-metadata] cache read failed:', err?.message);
+ return new Map();
+ }
+}
+
+async function persist(entries) {
+ if (entries.length === 0) return;
+ try {
+ await sql`
+ INSERT INTO token_metadata (mint, chain, symbol, name, logo, decimals, source, refreshed_at)
+ SELECT * FROM ${sql(
+ entries.map((e) => [e.mint, 'solana', e.symbol, e.name, e.logo, e.decimals, 'helius-das', new Date()]),
+ )}
+ ON CONFLICT (mint) DO UPDATE SET
+ symbol = EXCLUDED.symbol,
+ name = EXCLUDED.name,
+ logo = EXCLUDED.logo,
+ decimals = EXCLUDED.decimals,
+ refreshed_at = EXCLUDED.refreshed_at
+ `;
+ } catch (err) {
+ console.warn('[token-metadata] cache write failed:', err?.message);
+ }
+}
+
+async function resolveViaHelius(mints) {
+ const rpc = heliusRpcUrl();
+ if (!rpc || mints.length === 0) return [];
+ try {
+ const r = await fetch(rpc, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 'getAssetBatch',
+ method: 'getAssetBatch',
+ params: { ids: mints },
+ }),
+ });
+ if (!r.ok) {
+ console.warn('[token-metadata] helius getAssetBatch failed:', r.status);
+ return [];
+ }
+ const json = await r.json();
+ const results = Array.isArray(json?.result) ? json.result : [];
+ return results
+ .filter(Boolean)
+ .map((asset) => {
+ const md = asset?.content?.metadata || {};
+ const decimals = asset?.token_info?.decimals ?? null;
+ return {
+ mint: asset.id,
+ symbol: md.symbol || asset.id.slice(0, 6),
+ name: md.name || md.symbol || asset.id.slice(0, 6),
+ logo: asset?.content?.links?.image || asset?.content?.files?.[0]?.uri || null,
+ decimals,
+ };
+ });
+ } catch (err) {
+ console.warn('[token-metadata] helius resolve failed:', err?.message);
+ return [];
+ }
+}
+
+/**
+ * Resolve metadata for a list of mints. Always returns one entry per input mint
+ * (bare placeholder if everything else fails).
+ * @param {string[]} mints
+ * @returns {Promise<Map<string, {mint,symbol,name,logo,decimals}>>}
+ */
+export async function getMetadataForMints(mints) {
+ const unique = Array.from(new Set(mints.filter(Boolean)));
+ if (unique.length === 0) return new Map();
+
+ const cached = await fetchFromCache(unique);
+ const missing = unique.filter((m) => !cached.has(m));
+
+ if (missing.length > 0) {
+ // Helius getAssetBatch caps at 1000 per request — chunk safely.
+ const resolved = [];
+ for (let i = 0; i < missing.length; i += 1000) {
+ const chunk = missing.slice(i, i + 1000);
+ const part = await resolveViaHelius(chunk);
+ resolved.push(...part);
+ }
+ if (resolved.length > 0) {
+ await persist(resolved);
+ for (const r of resolved) cached.set(r.mint, r);
+ }
+ }
+
+ // Fill any remaining gaps with bare placeholders so the caller gets a stable shape.
+ for (const m of unique) {
+ if (!cached.has(m)) cached.set(m, bareEntry(m));
+ }
+ return cached;
+}
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index 79a08a375..8f8b4fa45 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -433,29 +433,35 @@ async function handleDetail(req, res, id) {
const rl = await limits.widgetRead(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
- const [row] = await sql`
- SELECT a.*, u.display_name AS author_name, u.avatar_url AS author_avatar,
- av.storage_key AS avatar_storage_key,
- av.thumbnail_key AS avatar_thumbnail_key,
- av.visibility AS avatar_visibility,
- (SELECT count(*)::int FROM skill_purchases sp
- WHERE sp.agent_id = a.id AND sp.status = 'confirmed') AS buyers_total,
- (SELECT count(*)::int FROM skill_purchases sp
- WHERE sp.agent_id = a.id AND sp.status = 'confirmed'
- AND sp.confirmed_at > now() - interval '24 hours') AS buyers_24h,
- COALESCE((SELECT AVG(rating)::numeric(3,2) FROM agent_reviews r WHERE r.agent_id = a.id), 0) AS rating_avg,
- COALESCE((SELECT count(*)::int FROM agent_reviews r WHERE r.agent_id = a.id), 0) AS rating_count,
- ap.amount AS asset_price_amount,
- ap.currency_mint AS asset_price_currency_mint,
- ap.chain AS asset_price_chain,
- ap.mint_decimals AS asset_price_mint_decimals
- FROM agent_identities a
- LEFT JOIN users u ON u.id = a.user_id
- LEFT JOIN avatars av ON av.id = a.avatar_id AND av.deleted_at IS NULL
- LEFT JOIN asset_prices ap
- ON ap.item_type = 'agent' AND ap.item_id = a.id AND ap.is_active = true
- WHERE a.id = ${id} AND a.deleted_at IS NULL
- `;
+ let row;
+ try {
+ [row] = await sql`
+ SELECT a.*, u.display_name AS author_name, u.avatar_url AS author_avatar,
+ av.storage_key AS avatar_storage_key,
+ av.thumbnail_key AS avatar_thumbnail_key,
+ av.visibility AS avatar_visibility,
+ COALESCE((SELECT count(*)::int FROM skill_purchases sp
+ WHERE sp.agent_id = a.id AND sp.status = 'confirmed'), 0) AS buyers_total,
+ COALESCE((SELECT count(*)::int FROM skill_purchases sp
+ WHERE sp.agent_id = a.id AND sp.status = 'confirmed'
+ AND sp.created_at > now() - interval '24 hours'), 0) AS buyers_24h,
+ COALESCE((SELECT AVG(rating)::numeric(3,2) FROM agent_reviews r WHERE r.agent_id = a.id), 0) AS rating_avg,
+ COALESCE((SELECT count(*)::int FROM agent_reviews r WHERE r.agent_id = a.id), 0) AS rating_count,
+ ap.amount AS asset_price_amount,
+ ap.currency_mint AS asset_price_currency_mint,
+ ap.chain AS asset_price_chain,
+ ap.mint_decimals AS asset_price_mint_decimals
+ FROM agent_identities a
+ LEFT JOIN users u ON u.id = a.user_id
+ LEFT JOIN avatars av ON av.id = a.avatar_id AND av.deleted_at IS NULL
+ LEFT JOIN asset_prices ap
+ ON ap.item_type = 'agent' AND ap.item_id = a.id AND ap.is_active = true
+ WHERE a.id = ${id} AND a.deleted_at IS NULL
+ `;
+ } catch (err) {
+ console.error('[marketplace/detail]', err?.message || err);
+ return error(res, 500, 'db_error', 'Failed to load agent');
+ }
if (!row) return error(res, 404, 'not_found', 'agent not found');
const auth = await resolveAuth(req).catch(() => null);
diff --git a/api/permissions/[action].js b/api/permissions/[action].js
index 5224a2f80..f2d302a73 100644
--- a/api/permissions/[action].js
+++ b/api/permissions/[action].js
@@ -355,17 +355,23 @@ async function handleList(req, res) {
// agentId-only path: public, no auth required
if (agentId && !delegator) {
- const rows = await sql`
- SELECT
- id, chain_id, delegator_address, delegate_address, delegation_hash,
- scope, status, expires_at, created_at, last_redeemed_at, redemption_count
- FROM agent_delegations
- WHERE agent_id = ${agentId}
- AND (${statusParam} = 'all' OR status = ${statusParam})
- AND (${chainId}::integer IS NULL OR chain_id = ${chainId}::integer)
- ORDER BY created_at DESC
- LIMIT ${limitParam} OFFSET ${offset}
- `;
+ let rows;
+ try {
+ rows = await sql`
+ SELECT
+ id, chain_id, delegator_address, delegate_address, delegation_hash,
+ scope, status, expires_at, created_at, last_redeemed_at, redemption_count
+ FROM agent_delegations
+ WHERE agent_id = ${agentId}
+ AND (${statusParam} = 'all' OR status = ${statusParam})
+ AND (${chainId}::integer IS NULL OR chain_id = ${chainId}::integer)
+ ORDER BY created_at DESC
+ LIMIT ${limitParam} OFFSET ${offset}
+ `;
+ } catch (err) {
+ console.error('[permissions/list] public query failed', err?.message || err);
+ return error(res, 500, 'db_error', 'Failed to list delegations');
+ }
const delegations = rows.map(toListPublicShape);
const body = { ok: true, delegations };
@@ -402,18 +408,24 @@ async function handleList(req, res) {
}
const whereAgentId = agentId;
- const rows = await sql`
- SELECT
- id, chain_id, delegator_address, delegate_address, delegation_hash,
- delegation_json, scope, status, expires_at, created_at, last_redeemed_at, redemption_count
- FROM agent_delegations
- WHERE (${whereAgentId}::uuid IS NULL OR agent_id = ${whereAgentId}::uuid)
- AND (${targetDelegator}::text IS NULL OR lower(delegator_address) = lower(${targetDelegator}::text))
- AND (${statusParam} = 'all' OR status = ${statusParam})
- AND (${chainId}::integer IS NULL OR chain_id = ${chainId}::integer)
- ORDER BY created_at DESC
- LIMIT ${limitParam} OFFSET ${offset}
- `;
+ let rows;
+ try {
+ rows = await sql`
+ SELECT
+ id, chain_id, delegator_address, delegate_address, delegation_hash,
+ delegation_json, scope, status, expires_at, created_at, last_redeemed_at, redemption_count
+ FROM agent_delegations
+ WHERE (${whereAgentId}::uuid IS NULL OR agent_id = ${whereAgentId}::uuid)
+ AND (${targetDelegator}::text IS NULL OR lower(delegator_address) = lower(${targetDelegator}::text))
+ AND (${statusParam} = 'all' OR status = ${statusParam})
+ AND (${chainId}::integer IS NULL OR chain_id = ${chainId}::integer)
+ ORDER BY created_at DESC
+ LIMIT ${limitParam} OFFSET ${offset}
+ `;
+ } catch (err) {
+ console.error('[permissions/list] auth query failed', err?.message || err);
+ return error(res, 500, 'db_error', 'Failed to list delegations');
+ }
const delegations = rows.map(toListAuthShape);
const body = { ok: true, delegations };
diff --git a/sdk/src/erc8004/abi.js b/sdk/src/erc8004/abi.js
index dc77ff48d..aea0b0aa1 100644
--- a/sdk/src/erc8004/abi.js
+++ b/sdk/src/erc8004/abi.js
@@ -81,9 +81,12 @@ export const VALIDATION_REGISTRY_ABI = [
// Canonical ERC-8004 reference deployments — same address on every chain via
// CREATE2. Source: https://github.com/nirholas/erc8004-agents
-// ValidationRegistry mainnet deployment is pending. After running
-// contracts/script/deploy-validation-registry.sh, fill in the address
-// produced by computeAddress(DEPLOYER_ADDRESS) in MAINNET.validationRegistry.
+//
+// `null` for a registry means it has not yet been deployed on this network
+// tier. Callers should resolve via `getRegistry(chainId, kind)` below, which
+// reads `THREE_WS_REGISTRY_<KIND>_<CHAIN_ID>` env overrides first and throws
+// a clear error rather than returning empty/zero, preventing accidental
+// "send to nothing" txs.
const TESTNET = {
identityRegistry: '0x8004A818BFB912233c491871b3d84c89A494BD9e',
@@ -94,7 +97,7 @@ const TESTNET = {
const MAINNET = {
identityRegistry: '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432',
reputationRegistry: '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63',
- validationRegistry: '',
+ validationRegistry: null,
};
/**
@@ -138,3 +141,37 @@ export const REGISTRY_DEPLOYMENTS = {
export function agentRegistryId(chainId, registryAddress) {
return `eip155:${chainId}:${registryAddress}`;
}
+
+/**
+ * Resolve a registry address for a chain with an env override path. Throws
+ * if no real address is available rather than returning an empty/falsy
+ * value that would silently land at the zero address.
+ *
+ * Env: `THREE_WS_REGISTRY_<KIND>_<chainId>=0x…` where KIND is one of
+ * IDENTITY / REPUTATION / VALIDATION.
+ *
+ * @param {number} chainId
+ * @param {'identityRegistry'|'reputationRegistry'|'validationRegistry'} kind
+ * @returns {string} 0x EVM address
+ */
+export function getRegistry(chainId, kind) {
+ const slug = {
+ identityRegistry: 'IDENTITY',
+ reputationRegistry: 'REPUTATION',
+ validationRegistry: 'VALIDATION',
+ }[kind];
+ if (!slug) throw new Error(`unknown_registry_kind: ${kind}`);
+ if (typeof process !== 'undefined' && process.env) {
+ const env = process.env[`THREE_WS_REGISTRY_${slug}_${chainId}`];
+ if (env && /^0x[0-9a-fA-F]{40}$/.test(env.trim())) return env.trim();
+ }
+ const deployments = REGISTRY_DEPLOYMENTS[chainId];
+ const addr = deployments?.[kind];
+ if (!addr || !/^0x[0-9a-fA-F]{40}$/.test(addr)) {
+ throw new Error(
+ `erc8004_not_deployed: ${kind} is not available on chain ${chainId}. ` +
+ `Set THREE_WS_REGISTRY_${slug}_${chainId}=0x… to opt in.`,
+ );
+ }
+ return addr;
+}
diff --git a/src/solana/sns.js b/src/solana/sns.js
index e576b9150..8156ea101 100644
--- a/src/solana/sns.js
+++ b/src/solana/sns.js
@@ -28,7 +28,7 @@ function stripSol(name) {
*/
export async function resolveSnsName(name) {
try {
- const { resolve } = await import('@bonfida/spl-name-service');
+ const { resolve } = await import('@bonfida/spl-name-service/dist/cjs/index.js');
const pk = await resolve(makeConnection(), stripSol(name));
return pk.toBase58();
} catch {
@@ -43,7 +43,7 @@ export async function resolveSnsName(name) {
*/
export async function reverseLookupAddress(addr) {
try {
- const { getFavoriteDomain } = await import('@bonfida/spl-name-service');
+ const { getFavoriteDomain } = await import('@bonfida/spl-name-service/dist/cjs/index.js');
const owner = new PublicKey(addr);
const { reverse } = await getFavoriteDomain(makeConnection(), owner);
return reverse.endsWith('.sol') ? reverse : `${reverse}.sol`;
diff --git a/vite.config.js b/vite.config.js
index 0b9baf5b0..bdd9663b5 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -225,28 +225,67 @@ const appConfig = {
// iframe — would register a service worker scoped to three.ws, then
// intercept and cache requests across every other page on the same
// origin. Privacy & correctness hazard for embedders.
- // The list below is the source-relative HTML basename (without .html).
+ //
+ // VitePWA itself injects the script via its own enforce:'post'
+ // transformIndexHtml, so this strip has to run *after* the bundle is
+ // emitted to disk — a closeBundle hook on the dist/ output directory
+ // is the only ordering that's stable across Vite versions.
{
name: 'three-ws-strip-sw-from-embeds',
apply: 'build',
- enforce: 'post',
- transformIndexHtml(html, ctx) {
- const EMBED_ENTRIES = new Set([
- 'widget',
- 'embed',
- 'avatar-embed',
- 'agent-embed',
- 'a-embed',
- 'agent-token-page',
- ]);
- const fname = (ctx.filename || ctx.path || '')
- .replace(/^.*\//, '')
- .replace(/\.html$/, '');
- if (!EMBED_ENTRIES.has(fname)) return html;
- return html.replace(
- /<script\s+[^>]*id=["']vite-plugin-pwa:register-sw["'][^>]*><\/script>\s*/g,
- '',
- );
+ closeBundle: {
+ sequential: true,
+ order: 'post',
+ async handler() {
+ const { readdirSync, statSync, readFileSync, writeFileSync } =
+ await import('node:fs');
+ const { join } = await import('node:path');
+ const EMBED_ENTRIES = new Set([
+ 'widget.html',
+ 'embed.html',
+ 'avatar-embed.html',
+ 'agent-embed.html',
+ 'a-embed.html',
+ 'agent-token-page.html',
+ ]);
+ const RE = /<script[^>]*id=["']vite-plugin-pwa:register-sw["'][^>]*><\/script>\s*/g;
+ const outDir = 'dist';
+ const stripped = [];
+ const walk = (dir) => {
+ let entries;
+ try {
+ entries = readdirSync(dir);
+ } catch {
+ return;
+ }
+ for (const name of entries) {
+ const full = join(dir, name);
+ let s;
+ try {
+ s = statSync(full);
+ } catch {
+ continue;
+ }
+ if (s.isDirectory()) {
+ walk(full);
+ continue;
+ }
+ if (!EMBED_ENTRIES.has(name)) continue;
+ const html = readFileSync(full, 'utf8');
+ if (!RE.test(html)) continue;
+ writeFileSync(full, html.replace(RE, ''));
+ stripped.push(full);
+ }
+ };
+ walk(outDir);
+ if (stripped.length) {
+ // eslint-disable-next-line no-console
+ console.log(
+ '[strip-sw] removed registerSW script from:',
+ stripped.map((p) => p.replace(outDir + '/', '')).join(', '),
+ );
+ }
+ },
},
},
// Polyfill the Node `buffer` and `process` globals so @solana/web3.js
diff --git a/vitest.config.js b/vitest.config.js
index 1908e1553..cc36ebdf3 100644
--- a/vitest.config.js
+++ b/vitest.config.js
@@ -1,15 +1,32 @@
import { defineConfig } from 'vitest/config';
+import os from 'node:os';
// Cold dynamic `import()` of API handlers that pull in heavy SDKs (@coinbase/x402,
// neon-serverless, jsdom, the Solana toolchain, etc.) routinely takes 5–30s on
// the first hit in constrained CI/Codespace environments. Individual tests that
// do real I/O still carry their own tighter timeouts; this ceiling only protects
// import-heavy module-load tests like the onchain adapter factory.
+//
+// Parallelism: on Codespaces / small CI workers the default (cpus - 1) workers
+// melt the box — heavy ESM cold-imports across files compete for memory and
+// repeatedly miss their hookTimeout. We cap forks at min(4, cpus - 1) so worker
+// startup never queues behind a busy peer. Locally on a beefy machine
+// (CPUs > 4) this still parallelizes; small hosts get safe serialisation.
+const _cpus = Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1);
+const MAX_FORKS = Math.max(1, Math.min(4, _cpus));
+
export default defineConfig({
test: {
environment: 'node',
include: ['tests/**/*.test.js', 'tests/**/*.test.mjs', 'src/**/*.test.js'],
testTimeout: 45_000,
hookTimeout: 45_000,
+ pool: 'forks',
+ poolOptions: {
+ forks: {
+ maxForks: MAX_FORKS,
+ minForks: 1,
+ },
+ },
},
});