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.

feat: per-asset portfolio detail endpoint, balances 24h change, skill price extras, csrf_tokens

nirholase4d3cf515b15
diff --git a/api/_lib/balances.js b/api/_lib/balances.js
index b8a5e60dd..069b6a36c 100644
--- a/api/_lib/balances.js
+++ b/api/_lib/balances.js
@@ -72,38 +72,38 @@ async function getSolanaBalances(address) {
return { mint, amount: tokenAmount.uiAmount, decimals: tokenAmount.decimals };
})
.filter(Boolean)
- .sort((a, b) => b.amount - a.amount)
- .slice(0, 50);
+ .sort((a, b) => b.amount - a.amount);
- const mintList = fungible.map((t) => t.mint).join(',');
- let cgTokenPrices = {};
- if (mintList) {
+ // 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 {
- cgTokenPrices = await fetchJson(
- `https://api.coingecko.com/api/v3/simple/token_price/solana?contract_addresses=${mintList}&vs_currencies=usd`,
+ 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
}
}
let solUsdPrice = 0;
+ let solChange24h = 0;
try {
const cgSol = await fetchJson(
- 'https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd',
+ '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 tokens = [];
- for (const t of fungible) {
- const price = cgTokenPrices[t.mint.toLowerCase()]?.usd ?? 0;
- let symbol = t.mint.slice(0, 6);
- let logo = null;
- try {
- const das = await fetchJson(rpcUrl, {
+ // DAS metadata is one RPC per mint; run them concurrently.
+ const metaResults = await Promise.all(
+ fungible.map((t) =>
+ fetchJson(rpcUrl, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
@@ -112,20 +112,43 @@ async function getSolanaBalances(address) {
method: 'getAsset',
params: { id: t.mint },
}),
- });
- symbol = das.result?.content?.metadata?.symbol || symbol;
- logo = das.result?.content?.links?.image || null;
- } catch {
- // metadata is best-effort
- }
- tokens.push({ symbol, mint: t.mint, decimals: t.decimals, amount: t.amount, usd: t.amount * price, logo });
- }
+ }).catch(() => 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,
+ };
+ });
tokens.sort((a, b) => (b.usd || 0) - (a.usd || 0));
return {
chain: 'solana',
address,
- native: { symbol: 'SOL', amount: solAmount, usd: solAmount * solUsdPrice },
+ native: {
+ symbol: 'SOL',
+ name: 'Solana',
+ amount: solAmount,
+ price: solUsdPrice,
+ change24h: solChange24h,
+ usd: solAmount * solUsdPrice,
+ },
tokens,
};
}
@@ -167,8 +190,7 @@ async function getEvmBalances(address) {
});
const rawTokens = (tokenBalResp.result?.tokenBalances ?? [])
- .filter((t) => t.tokenBalance && t.tokenBalance !== '0x0' && t.tokenBalance !== '0x')
- .slice(0, 50);
+ .filter((t) => t.tokenBalance && t.tokenBalance !== '0x0' && t.tokenBalance !== '0x');
const metadataResults = await Promise.allSettled(
rawTokens.map((t) =>
@@ -185,24 +207,27 @@ async function getEvmBalances(address) {
),
);
- const contractList = rawTokens.map((t) => t.contractAddress).join(',');
- let cgTokenPrices = {};
- if (contractList) {
+ const cgTokenPrices = {};
+ for (let i = 0; i < rawTokens.length; i += 80) {
+ const chunk = rawTokens.slice(i, i + 80).map((t) => t.contractAddress).join(',');
try {
- cgTokenPrices = await fetchJson(
- `https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses=${contractList}&vs_currencies=usd`,
+ const part = await fetchJson(
+ `https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses=${chunk}&vs_currencies=usd&include_24hr_change=true`,
);
+ Object.assign(cgTokenPrices, part);
} catch {
// best-effort
}
}
let ethUsdPrice = 0;
+ let ethChange24h = 0;
try {
const cgEth = await fetchJson(
- 'https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd',
+ 'https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd&include_24hr_change=true',
);
ethUsdPrice = cgEth?.ethereum?.usd ?? 0;
+ ethChange24h = cgEth?.ethereum?.usd_24h_change ?? 0;
} catch {
// best-effort
}
@@ -212,12 +237,17 @@ async function getEvmBalances(address) {
const decimals = meta?.decimals ?? 18;
const rawBal = BigInt(t.tokenBalance || '0x0');
const amount = Number(rawBal) / Math.pow(10, decimals);
- const price = cgTokenPrices[t.contractAddress.toLowerCase()]?.usd ?? 0;
+ const priceInfo = cgTokenPrices[t.contractAddress.toLowerCase()] || {};
+ const price = priceInfo.usd ?? 0;
+ const change24h = priceInfo.usd_24h_change ?? null;
return {
symbol: meta?.symbol || t.contractAddress.slice(0, 8),
+ name: meta?.name || meta?.symbol || t.contractAddress.slice(0, 8),
contract: t.contractAddress,
decimals,
amount,
+ price,
+ change24h,
usd: amount * price,
logo: meta?.logo || null,
};
@@ -227,7 +257,14 @@ async function getEvmBalances(address) {
return {
chain: 'evm',
address,
- native: { symbol: 'ETH', amount: ethAmount, usd: ethAmount * ethUsdPrice },
+ native: {
+ symbol: 'ETH',
+ name: 'Ethereum',
+ amount: ethAmount,
+ price: ethUsdPrice,
+ change24h: ethChange24h,
+ usd: ethAmount * ethUsdPrice,
+ },
tokens,
};
}
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 80a319814..88daccec8 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -997,15 +997,19 @@ create index if not exists pumpfun_graduations_creator on pumpfun_graduations(cr
-- Per-skill price set by the agent owner. Authoritative source of truth for
-- "is this skill paid, and how much?". See migration 2026-04-30-agent-monetization.sql.
CREATE TABLE IF NOT EXISTS agent_skill_prices (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
- skill TEXT NOT NULL,
- currency_mint TEXT NOT NULL,
- chain TEXT NOT NULL DEFAULT 'solana',
- amount BIGINT NOT NULL,
- is_active BOOLEAN NOT NULL DEFAULT true,
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ skill TEXT NOT NULL,
+ currency_mint TEXT NOT NULL,
+ chain TEXT NOT NULL DEFAULT 'solana',
+ amount BIGINT NOT NULL,
+ is_active BOOLEAN NOT NULL DEFAULT true,
+ mint_decimals SMALLINT NOT NULL DEFAULT 6, -- A2 cached mint decimals
+ trial_uses INTEGER NOT NULL DEFAULT 0, -- C2 trial allowance per buyer
+ time_pass_hours INTEGER, -- C3 time-pass duration
+ time_pass_amount BIGINT, -- C3 time-pass price
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (agent_id, skill)
);
@@ -1083,6 +1087,22 @@ CREATE INDEX IF NOT EXISTS purchase_events_purchase
CREATE INDEX IF NOT EXISTS purchase_events_event_time
ON purchase_events (event, created_at DESC);
+-- ── csrf_tokens ──────────────────────────────────────────────────────────────
+-- Lightweight double-submit cookie tokens (A5). See api/_lib/csrf.js. Expired
+-- rows are pruned by the cron job in api/cron/[name].js.
+CREATE TABLE IF NOT EXISTS csrf_tokens (
+ token TEXT PRIMARY KEY,
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ expires_at TIMESTAMPTZ NOT NULL
+);
+
+CREATE INDEX IF NOT EXISTS csrf_tokens_user
+ ON csrf_tokens (user_id, expires_at DESC);
+
+CREATE INDEX IF NOT EXISTS csrf_tokens_expires
+ ON csrf_tokens (expires_at);
+
-- ── agent_payment_intents ────────────────────────────────────────────────────
-- Generic payment intent (subscriptions, one-shot, x402 invocations). Skill
-- purchases get a synthetic intent with id 'sp_<skill_purchase_id>' on confirm
diff --git a/api/portfolio/[action].js b/api/portfolio/[action].js
index 6937ce3f9..1d710346d 100644
--- a/api/portfolio/[action].js
+++ b/api/portfolio/[action].js
@@ -381,6 +381,217 @@ async function handleSend(req, res) {
}
}
+// ── GET /api/portfolio/asset ───────────────────────────────────────────────
+//
+// Returns combined data for a single token across all of the user's agent
+// wallets: which wallets hold it, total amount, USD value, plus current market
+// data (price, 24h change, market cap) and a price history chart pulled from
+// CoinGecko. Params:
+// chain = "solana" | "evm"
+// id = "native" | <mint or 0x contract>
+// days = optional, defaults to 30
+//
+// 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' } });
+ 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();
+}
+
+async function handleAsset(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.walletRead(user.id);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ 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)));
+
+ 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');
+
+ const isNative = idRaw === 'native';
+ const id = isNative ? 'native' : idRaw;
+
+ // 1) Walk this user's wallets, fetch live balances, and pick out matching holdings.
+ const wallets = await listUserAgentWallets(user.id);
+ const chainWallets = wallets.filter((w) => w.chain === chain);
+ const balResults = await Promise.allSettled(
+ chainWallets.map((w) => getBalances({ chain: w.chain, address: w.address })),
+ );
+
+ const holdings = [];
+ let totalAmount = 0;
+ let totalUsd = 0;
+ let symbol = isNative ? (chain === 'solana' ? 'SOL' : 'ETH') : null;
+ let logo = null;
+ let decimals = isNative ? (chain === 'solana' ? 9 : 18) : null;
+ let unitPrice = 0;
+
+ for (let i = 0; i < chainWallets.length; i++) {
+ const w = chainWallets[i];
+ const r = balResults[i];
+ if (r.status !== 'fulfilled') continue;
+ const bal = r.value;
+ if (isNative) {
+ const a = Number(bal.native?.amount || 0);
+ const u = Number(bal.native?.usd || 0);
+ if (a > 0 || u > 0) {
+ holdings.push({
+ agent_id: w.agent_id,
+ agent_name: w.agent_name,
+ chain: w.chain,
+ chain_id: w.chain_id,
+ address: w.address,
+ amount: a,
+ usd: u,
+ });
+ totalAmount += a;
+ totalUsd += u;
+ if (!unitPrice && a > 0) unitPrice = u / a;
+ }
+ } else {
+ const tokens = bal.tokens || [];
+ const idLower = id.toLowerCase();
+ const match = tokens.find((t) => {
+ const tid = (t.mint || t.contract || '').toLowerCase();
+ return tid === idLower;
+ });
+ if (!match) continue;
+ symbol = symbol || match.symbol;
+ logo = logo || match.logo;
+ decimals = decimals ?? match.decimals;
+ const a = Number(match.amount || 0);
+ const u = Number(match.usd || 0);
+ holdings.push({
+ agent_id: w.agent_id,
+ agent_name: w.agent_name,
+ chain: w.chain,
+ chain_id: w.chain_id,
+ address: w.address,
+ amount: a,
+ usd: u,
+ });
+ totalAmount += a;
+ totalUsd += u;
+ if (!unitPrice && a > 0) unitPrice = u / a;
+ }
+ }
+
+ // 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);
+ }
+
+ // If CoinGecko 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;
+ for (const h of holdings) h.usd = h.amount * market.price_usd;
+ unitPrice = market.price_usd;
+ }
+
+ return json(res, 200, {
+ chain,
+ id,
+ is_native: isNative,
+ symbol: symbol || (chain === 'solana' ? 'SOL' : 'ETH'),
+ logo,
+ decimals,
+ unit_price_usd: unitPrice,
+ total_amount: totalAmount,
+ total_usd: totalUsd,
+ holdings,
+ market,
+ chart: { days, points: chartPoints },
+ });
+}
+
// ── Dispatcher ─────────────────────────────────────────────────────────────
export default wrap(async (req, res) => {
@@ -390,6 +601,8 @@ export default wrap(async (req, res) => {
return handleSummary(req, res);
case 'history':
return handleHistory(req, res);
+ case 'asset':
+ return handleAsset(req, res);
case 'send':
return handleSend(req, res);
default: