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.

30.0 KB
Raw Blame
// Portfolio dispatcher for the user's agent custodial wallets.
//
//   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
// the caller (agent_identities.user_id = session.user_id). Balances are
// memoized for 60s in-process to shield Helius/Alchemy/CoinGecko from
// per-page-load fan-out.

import { cors, json, method, readJson, wrap, error, validationError, rateLimited } from '../_lib/http.js';
import { solanaConnection } from '../_lib/solana/connection.js';
import { ataExists, blockhashKey, getRecentBlockhashInfo } from '../_lib/solana/read-guards.js';
import { evmFallbackProvider } from '../_lib/evm/rpc.js';
import { limits } from '../_lib/rate-limit.js';
import { getSessionUser, isSameSiteOrigin } from '../_lib/auth.js';
import { requireCsrf } from '../_lib/csrf.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { logAudit } from '../_lib/audit.js';
import { enforceDestinationAllowlist, SpendLimitError } from '../_lib/agent-trade-guards.js';
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 { 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 { evmChainMarket, DEFAULT_EVM_CHAIN_ID } from '../_lib/evm/chain-market.js';
import { env } from '../_lib/env.js';
import { z } from 'zod';

// `send` does a Solana submit + EVM RPC roundtrips; default 10s is not enough.
export const maxDuration = 60;

const SNS_CACHE_TTL_MS = 10 * 60_000;
const _snsCache = new Map();

async function lookupSnsCached(address) {
	const hit = _snsCache.get(address);
	if (hit && Date.now() - hit.at < SNS_CACHE_TTL_MS) return hit.value;
	let value = null;
	try {
		value = await reverseLookupAddress(address);
	} catch {
		value = null;
	}
	_snsCache.set(address, { at: Date.now(), value });
	return value;
}

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) {
		const err = new Error(r.error.issues[0]?.message || 'invalid input');
		err.status = 400;
		err.code = 'validation_error';
		err.issues = r.error.issues;
		throw err;
	}
	return r.data;
}

async function listUserAgentWallets(userId) {
	const rows = await sql`
		select id, name, wallet_address, chain_id, meta
		  from agent_identities
		 where user_id = ${userId} and deleted_at is null
		 order by created_at asc
	`;
	const wallets = [];
	for (const row of rows) {
		const meta = row.meta || {};
		if (row.wallet_address) {
			wallets.push({
				agent_id: row.id,
				agent_name: row.name || 'Agent',
				kind: 'evm',
				chain: 'evm',
				chain_id: row.chain_id || 8453,
				address: row.wallet_address,
			});
		}
		const solAddr = meta.solana_address;
		if (solAddr) {
			wallets.push({
				agent_id: row.id,
				agent_name: row.name || 'Agent',
				kind: 'solana',
				chain: 'solana',
				address: solAddr,
			});
		}
	}
	return wallets;
}

// ── GET /api/portfolio/summary ─────────────────────────────────────────────

async function handleSummary(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 rateLimited(res, rl);

	const url = new URL(req.url, 'http://localhost');
	const wantSnapshot = url.searchParams.get('snapshot') === '1';

	const wallets = await listUserAgentWallets(user.id);

	const [balanceResults, snsResults] = await Promise.all([
		Promise.allSettled(wallets.map((w) => getBalances({ chain: w.chain, address: w.address }))),
		Promise.all(
			wallets.map((w) => (w.chain === 'solana' ? lookupSnsCached(w.address) : Promise.resolve(null))),
		),
	]);

	const byWallet = wallets.map((w, i) => {
		const r = balanceResults[i];
		const sns = snsResults[i];
		if (r.status === 'fulfilled') {
			const bal = r.value;
			return {
				agent_id: w.agent_id,
				agent_name: w.agent_name,
				chain: w.chain,
				chain_id: w.chain_id,
				address: w.address,
				sns,
				native: bal.native,
				tokens: bal.tokens,
				usd: walletUsdTotal(bal),
				ok: true,
			};
		}
		const err = r.reason;
		return {
			agent_id: w.agent_id,
			agent_name: w.agent_name,
			chain: w.chain,
			chain_id: w.chain_id,
			address: w.address,
			sns,
			native: { symbol: w.chain === 'solana' ? 'SOL' : 'ETH', amount: 0, usd: 0 },
			tokens: [],
			usd: 0,
			ok: false,
			error: err?.code === 'not_configured' ? `missing env: ${err.missing}` : err?.message || 'fetch failed',
		};
	});

	const totalUsd = byWallet.reduce((s, w) => s + (w.usd || 0), 0);

	if (wantSnapshot) {
		const breakdown = byWallet.map((w) => ({
			agent_id: w.agent_id,
			chain: w.chain,
			address: w.address,
			usd: w.usd,
		}));
		try {
			await sql`
				insert into portfolio_snapshots (user_id, total_usd, breakdown)
				values (${user.id}, ${totalUsd}, ${JSON.stringify(breakdown)}::jsonb)
			`;
		} catch (e) {
			console.error('[portfolio] snapshot insert failed', e?.message);
		}
	}

	return json(res, 200, {
		captured_at: new Date().toISOString(),
		total_usd: totalUsd,
		wallets: byWallet,
	});
}

// ── GET /api/portfolio/history ─────────────────────────────────────────────

async function handleHistory(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 rateLimited(res, rl);

	const url = new URL(req.url, 'http://localhost');
	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
		  from portfolio_snapshots
		 where user_id = ${user.id}
		   and captured_at > now() - (${days} || ' days')::interval
		 order by captured_at asc
	`;

	return json(res, 200, {
		days,
		points: rows.map((r) => ({
			t: new Date(r.captured_at).toISOString(),
			usd: Number(r.total_usd),
		})),
	});
}

// ── POST /api/portfolio/send ───────────────────────────────────────────────

const sendSchema = z.object({
	agent_id: z.string().uuid(),
	chain: z.enum(['solana', 'evm']),
	// 'native' for SOL/ETH, otherwise a mint (Solana) or 0x contract (EVM).
	asset: z.string().min(1),
	recipient: z.string().min(1),
	// Decimal string, in human units (e.g. "1.5" SOL, ".5" SOL, "100" USDC).
	amount: z.string().regex(/^(\d+(\.\d*)?|\.\d+)$/, 'invalid amount'),
	memo: z.string().max(120).optional(),
});

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';
	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) {
	const [row] = await sql`
		select id, name, wallet_address, chain_id, meta
		  from agent_identities
		 where id = ${agentId} and user_id = ${userId} and deleted_at is null
		 limit 1
	`;
	return row || null;
}

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';
		e.status = 400;
		throw e;
	}
	const encryptedKey = agent.meta?.encrypted_wallet_key;
	if (!encryptedKey) {
		const e = new Error('agent has no EVM key');
		e.code = 'no_key';
		e.status = 409;
		throw e;
	}
	const chainId = agent.chain_id || 8453;
	await enforceDestinationAllowlist({ agentId: agent.id, meta: agent.meta, category: 'withdraw', destination: recipient, usdValue: null });

	// 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: userId ?? null,
		reason: `portfolio_send_${asset}`,
	});
	const { Wallet, Contract } = await import('ethers');
	const provider = await evmFallbackProvider(chainId);
	const signer = new Wallet(pkHex, provider);

	if (asset === 'native') {
		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 };
	}

	if (!ETH_ADDR_RE.test(asset)) {
		const e = new Error('asset must be 0x contract or "native"');
		e.code = 'validation_error';
		e.status = 400;
		throw e;
	}
	const ERC20 = ['function decimals() view returns (uint8)', 'function transfer(address,uint256) returns (bool)'];
	const token = new Contract(asset, ERC20, signer);
	const decimals = Number(await token.decimals());
	const amountUnits = parseAmountToBaseUnits(amount, decimals);
	const tx = await token.transfer(recipient, amountUnits);
	return { tx_hash: tx.hash, chain_id: chainId };
}

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');
		e.code = 'validation_error';
		e.status = 400;
		throw e;
	}
	recipient = resolvedRecipient;
	await enforceDestinationAllowlist({ agentId: agent.id, meta: agent.meta, category: 'withdraw', destination: recipient, usdValue: null });
	const encryptedSecret = agent.meta?.encrypted_solana_secret;
	if (!encryptedSecret) {
		const e = new Error('agent has no Solana key');
		e.code = 'no_key';
		e.status = 409;
		throw e;
	}

	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,
		agentId: agent.id,
		reason: 'portfolio_send',
	});

	const recipientPk = new PublicKey(recipient);
	const tx = new Transaction();

	if (asset === 'native') {
		// 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)) {
			const e = new Error('asset must be SPL mint or "native"');
			e.code = 'validation_error';
			e.status = 400;
			throw e;
		}
		const { getAssociatedTokenAddress, createAssociatedTokenAccountIdempotentInstruction, createTransferInstruction } = await import('@solana/spl-token');
		const mintPk = new PublicKey(asset);

		const mintInfo = await conn.getParsedAccountInfo(mintPk);
		const decimals = mintInfo.value?.data?.parsed?.info?.decimals ?? 6;

		const senderAta = await getAssociatedTokenAddress(mintPk, kp.publicKey);
		const recipientAta = await getAssociatedTokenAddress(mintPk, recipientPk);
		// Fails open to "missing" when the chain cannot be read: the worst case is
		// an extra create instruction for an account that already exists, which the
		// runtime treats as a no-op, whereas throwing here loses the whole transfer.
		const recipientAccountExists = await ataExists(conn, recipientAta);
		if (!recipientAccountExists) {
			tx.add(createAssociatedTokenAccountIdempotentInstruction(kp.publicKey, recipientAta, recipientPk, mintPk));
		}
		const amountUnits = parseAmountToBaseUnits(amount, decimals);
		tx.add(createTransferInstruction(senderAta, recipientAta, kp.publicKey, amountUnits));
	}

	const { blockhash } = await getRecentBlockhashInfo(conn, blockhashKey({ url: env.SOLANA_RPC_URL }), { commitment: 'finalized' });
	tx.feePayer = kp.publicKey;
	tx.recentBlockhash = blockhash;
	tx.sign(kp);

	// Preflight runs on the RPC and throws synchronously if the tx would fail
	// (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.
	const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
	return { tx_hash: sig, recipient, resolved_from };
}

async function handleSend(req, res) {
	if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
	if (!method(req, res, ['POST'])) return;

	const user = await getSessionUser(req, res);
	if (!user) return error(res, 401, 'unauthorized', 'sign in required');

	if (!isSameSiteOrigin(req)) {
		return error(res, 403, 'forbidden', 'cross-site request denied');
	}
	if (!(await requireRealFundsAgreement(req, res, { userId: user.id, context: 'portfolio-send' }))) return;
	if (!(await requireCsrf(req, res, user.id))) return;

	const rl = await limits.strict(`portfolio:send:${user.id}`);
	if (!rl.success) return rateLimited(res, rl, 'too many sends');

	let body;
	try {
		body = parse(sendSchema, await readJson(req));
	} catch (e) {
		return validationError(res, e);
	}

	const agent = await loadOwnedAgent(user.id, body.agent_id);
	if (!agent) return error(res, 404, 'not_found', 'agent not found');

	try {
		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, userId: user.id });

		logAudit({
			userId: user.id,
			action: 'portfolio_send',
			resourceId: agent.id,
			meta: {
				chain: body.chain,
				asset: body.asset,
				recipient: out.recipient || body.recipient,
				recipient_typed: body.recipient,
				resolved_from: out.resolved_from || null,
				amount: body.amount,
				tx_hash: out.tx_hash,
			},
		});

		// Invalidate cache so the next /summary reflects the new balance.
		const addr = body.chain === 'solana' ? agent.meta?.solana_address : agent.wallet_address;
		if (addr) invalidateBalances({ chain: body.chain, address: addr });

		return json(res, 200, { ok: true, ...out });
	} catch (e) {
		if (e instanceof SpendLimitError) return error(res, e.status, e.code, e.message, { detail: e.detail });
		if (e.code === 'validation_error') return error(res, 400, 'validation_error', e.message);
		if (e.code === 'no_key') return error(res, 409, 'no_key', e.message);
		if (e.code === 'no_rpc') return error(res, 503, 'no_rpc', e.message);
		console.error('[portfolio/send] failed', e?.message);
		return error(res, 502, 'send_failed', e?.message || 'transaction failed');
	}
}

// ── 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
//   chain_id = optional EVM chain id; defaults to the chain of the wallets that
//              actually hold the asset, then to the caller's first EVM wallet.
//
// Native maps to SOL on Solana and to the chain's gas token on EVM (the coin
// IDs come from the chain registry; the holding is read from live balances).

// 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,
	};
}

// 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 chain's native
// coin id, 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.
//
// Returns `{ market, symbol, decimals }` so a lane that knows the token's
// ticker can label a holding CoinGecko could not identify at all.
async function fallbackMarket({ chain, id, isNative, chainId }) {
	if (chain === 'solana') {
		if (isNative) {
			const [price, change] = await Promise.all([solPriceUsd(), solChange24hPct()]);
			return price > 0 ? { market: { name: 'Solana', price_usd: price, change_24h_pct: change } } : null;
		}
		const md = await fetchTokenMarketData(id);
		if (!md?.price_usd) return null;
		return {
			market: {
				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,
			},
			decimals: Number.isInteger(md.decimals) ? md.decimals : null,
		};
	}

	// An unlisted or test chain has no price oracle at all. Answering with the
	// Ethereum lane would price a contract address that does not exist there,
	// which is how a Base holding used to come back unpriceable.
	const registry = evmChainMarket(chainId);
	if (!registry) return null;

	if (isNative) {
		const price = await fetchCoinPriceUsdOrNull(registry.nativeCoingeckoId);
		return price > 0 ? { market: { name: registry.nativeName, price_usd: price }, symbol: registry.nativeSymbol } : null;
	}
	const key = `${registry.llamaChain}:${id.toLowerCase()}`;
	const coin = await fetchFirstOrNull(
		[
			{
				name: 'llama-contract',
				url: `https://coins.llama.fi/prices/current/${key}`,
				parse: async (r) => {
					const c = (await r.json())?.coins?.[key];
					const p = Number(c?.price);
					return Number.isFinite(p) && p > 0 ? { price: p, symbol: c?.symbol, decimals: c?.decimals } : null;
				},
			},
		],
		{ timeoutMs: 6000, label: `evm-token-price:${registry.llamaChain}:${id.slice(0, 10)}` },
	);
	if (!coin) return null;
	return {
		market: { price_usd: coin.price },
		symbol: coin.symbol ? String(coin.symbol).toUpperCase() : null,
		decimals: Number.isInteger(coin.decimals) ? coin.decimals : null,
	};
}

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 rateLimited(res, rl);

	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 = parseDays(url, 30);
	const chainIdRaw = url.searchParams.get('chain_id');

	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');

	// The caller may pin the EVM chain; otherwise it is inferred below from the
	// wallets that hold the asset.
	let chainId = null;
	if (chainIdRaw !== null && chainIdRaw.trim() !== '') {
		const n = Number(chainIdRaw);
		if (!Number.isInteger(n) || n <= 0) return error(res, 400, 'validation_error', 'chain_id must be a positive whole number');
		chainId = n;
	}

	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' : null;
	let logo = null;
	let decimals = isNative ? (chain === 'solana' ? 9 : 18) : null;
	let unitPrice = 0;
	// The chain of the first wallet that actually holds this asset, which beats
	// any default when the caller did not pin one.
	let holdingChainId = null;

	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;
				if (holdingChainId === null) holdingChainId = w.chain_id ?? null;
			}
		} 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;
			if (holdingChainId === null) holdingChainId = w.chain_id ?? null;
		}
	}

	// 2) Resolve which EVM chain this asset lives on before asking any upstream.
	//    A pinned chain_id wins, then the chain of the wallets holding it, then
	//    the caller's first EVM wallet, then the fleet default. This used to be
	//    hardcoded to Ethereum, so a Base contract (the chain nearly every agent
	//    wallet runs on) missed at CoinGecko AND at DefiLlama and the page
	//    reported a real holding as unpriceable.
	let registry = null;
	if (chain === 'evm') {
		chainId = chainId ?? holdingChainId ?? chainWallets[0]?.chain_id ?? DEFAULT_EVM_CHAIN_ID;
		registry = evmChainMarket(chainId);
		if (isNative) symbol = symbol || registry?.nativeSymbol || 'ETH';
	}

	// 3) Pull market data + price history from CoinGecko.
	//    For native: use the chain's coin id ("solana", "ethereum", "celo", …).
	//    For tokens: use /coins/{platform}/contract/{address}.
	//    A chain no upstream indexes (a testnet) skips the lookup rather than
	//    asking Ethereum about an address that only exists elsewhere.
	const platform = chain === 'solana' ? 'solana' : registry?.coingeckoPlatform || null;
	const nativeCoinId = chain === 'solana' ? 'solana' : registry?.nativeCoingeckoId || null;
	let market = null;
	let chartPoints = [];
	if (platform && (!isNative || nativeCoinId)) {
		const base = isNative ? `/coins/${nativeCoinId}` : `/coins/${platform}/contract/${encodeURIComponent(id)}`;
		const loaded = 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 ? nativeCoinId : id,
			days,
		});
		market = loaded.market;
		chartPoints = loaded.points;
		symbol = loaded.symbol || symbol;
		logo = logo || loaded.logo;
	}

	if (!market?.price_usd) {
		try {
			const fb = await fallbackMarket({ chain, id, isNative, chainId });
			if (fb) {
				market = { ...EMPTY_MARKET, ...(market || {}), ...fb.market };
				symbol = symbol || fb.symbol || null;
				decimals = decimals ?? fb.decimals ?? null;
			}
		} 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;
		for (const h of holdings) h.usd = h.amount * market.price_usd;
		unitPrice = market.price_usd;
	}

	return json(res, 200, {
		chain,
		// Which EVM chain the answer is about, so a client can round-trip it back
		// as `chain_id` and never re-guess. Null on Solana, which has one chain.
		chain_id: chain === 'evm' ? chainId : null,
		id,
		is_native: isNative,
		// 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,
		total_amount: totalAmount,
		total_usd: totalUsd,
		holdings,
		market,
		chart: { days, points: chartPoints },
	});
}

// ── Dispatcher ─────────────────────────────────────────────────────────────

export default wrap(async (req, res) => {
	const action = String(req.query?.action || '').toLowerCase();
	switch (action) {
		case 'summary':
			return handleSummary(req, res);
		case 'history':
			return handleHistory(req, res);
		case 'asset':
			return handleAsset(req, res);
		case 'send':
			return handleSend(req, res);
		default:
			return error(res, 404, 'not_found', `unknown action: ${action}`);
	}
});