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(portfolio): price each token on its own chain instead of always asking Ethereum

nirholas76f772b77a69
diff --git a/api/_lib/evm/chain-market.js b/api/_lib/evm/chain-market.js
new file mode 100644
index 000000000..9f460ae81
--- /dev/null
+++ b/api/_lib/evm/chain-market.js
@@ -0,0 +1,48 @@
+// Market-data identifiers per EVM chain.
+//
+// Three different upstreams address the same chain by three different names,
+// and every one of them is a silent miss when it is wrong: CoinGecko keys its
+// contract lookups by an asset-platform slug (`/coins/base/contract/0x…`),
+// DefiLlama keys its price oracle by a chain prefix (`base:0x…`), and the
+// chain's native gas token is its own CoinGecko coin id. Callers used to
+// hardcode `ethereum` for all three, which priced a Base or Arbitrum token
+// against a contract address that does not exist on Ethereum: both upstreams
+// answered "unknown", and the caller reported the holding as unpriceable.
+//
+// Only chains with real market data are listed. A testnet, or a chain no
+// upstream indexes, resolves to null so a caller skips the lookup entirely
+// rather than asking the wrong chain and trusting the answer.
+
+export const EVM_CHAIN_MARKET = {
+ 1: { coingeckoPlatform: 'ethereum', llamaChain: 'ethereum', nativeCoingeckoId: 'ethereum', nativeSymbol: 'ETH', nativeName: 'Ethereum' },
+ 10: { coingeckoPlatform: 'optimistic-ethereum', llamaChain: 'optimism', nativeCoingeckoId: 'ethereum', nativeSymbol: 'ETH', nativeName: 'Ethereum' },
+ 56: { coingeckoPlatform: 'binance-smart-chain', llamaChain: 'bsc', nativeCoingeckoId: 'binancecoin', nativeSymbol: 'BNB', nativeName: 'BNB' },
+ 100: { coingeckoPlatform: 'xdai', llamaChain: 'xdai', nativeCoingeckoId: 'xdai', nativeSymbol: 'XDAI', nativeName: 'xDAI' },
+ // POL, not MATIC: the `matic-network` coin id stopped resolving after the
+ // token migration, so anything still asking for it prices Polygon at null.
+ 137: { coingeckoPlatform: 'polygon-pos', llamaChain: 'polygon', nativeCoingeckoId: 'polygon-ecosystem-token', nativeSymbol: 'POL', nativeName: 'Polygon Ecosystem Token' },
+ 250: { coingeckoPlatform: 'fantom', llamaChain: 'fantom', nativeCoingeckoId: 'fantom', nativeSymbol: 'FTM', nativeName: 'Fantom' },
+ 324: { coingeckoPlatform: 'zksync', llamaChain: 'era', nativeCoingeckoId: 'ethereum', nativeSymbol: 'ETH', nativeName: 'Ethereum' },
+ 1284: { coingeckoPlatform: 'moonbeam', llamaChain: 'moonbeam', nativeCoingeckoId: 'moonbeam', nativeSymbol: 'GLMR', nativeName: 'Moonbeam' },
+ 5000: { coingeckoPlatform: 'mantle', llamaChain: 'mantle', nativeCoingeckoId: 'mantle', nativeSymbol: 'MNT', nativeName: 'Mantle' },
+ 8453: { coingeckoPlatform: 'base', llamaChain: 'base', nativeCoingeckoId: 'ethereum', nativeSymbol: 'ETH', nativeName: 'Ethereum' },
+ 42161: { coingeckoPlatform: 'arbitrum-one', llamaChain: 'arbitrum', nativeCoingeckoId: 'ethereum', nativeSymbol: 'ETH', nativeName: 'Ethereum' },
+ 42220: { coingeckoPlatform: 'celo', llamaChain: 'celo', nativeCoingeckoId: 'celo', nativeSymbol: 'CELO', nativeName: 'Celo' },
+ 43114: { coingeckoPlatform: 'avalanche', llamaChain: 'avax', nativeCoingeckoId: 'avalanche-2', nativeSymbol: 'AVAX', nativeName: 'Avalanche' },
+ 59144: { coingeckoPlatform: 'linea', llamaChain: 'linea', nativeCoingeckoId: 'ethereum', nativeSymbol: 'ETH', nativeName: 'Ethereum' },
+ 534352: { coingeckoPlatform: 'scroll', llamaChain: 'scroll', nativeCoingeckoId: 'ethereum', nativeSymbol: 'ETH', nativeName: 'Ethereum' },
+};
+
+// The chain every agent wallet lands on when `agent_identities.chain_id` is
+// null, which is the majority of the fleet.
+export const DEFAULT_EVM_CHAIN_ID = 8453;
+
+export function evmChainMarket(chainId) {
+ return EVM_CHAIN_MARKET[Number(chainId)] || null;
+}
+
+// CoinGecko coin id for a chain's native gas token, or null on a chain no
+// upstream prices (testnets included).
+export function evmNativeCoingeckoId(chainId) {
+ return evmChainMarket(chainId)?.nativeCoingeckoId || null;
+}
diff --git a/api/_lib/trust/subject-reputation.js b/api/_lib/trust/subject-reputation.js
index a671acf55..0a5fc03df 100644
--- a/api/_lib/trust/subject-reputation.js
+++ b/api/_lib/trust/subject-reputation.js
@@ -458,13 +458,12 @@ async function readEvmWallet(chainId, address) {
// Native-asset USD price by chain, keyless, through the shared coin-price
// failover (CoinGecko → DefiLlama → exchange tickers). Best-effort: a miss just
// leaves holdings unpriced (dimension unavailable), never an error.
-const CG_NATIVE_ID = {
- 1: 'ethereum', 8453: 'ethereum', 42161: 'ethereum', 10: 'ethereum', 59144: 'ethereum',
- 534352: 'ethereum', 324: 'ethereum', 5000: 'mantle', 56: 'binancecoin', 137: 'matic-network',
- 43114: 'avalanche-2', 100: 'xdai', 250: 'fantom', 42220: 'celo', 1284: 'moonbeam',
-};
+// The chain→coin-id table lives in the EVM chain registry, which the portfolio
+// asset lane reads too; a second copy here drifted the moment one of them
+// gained a chain.
async function evmNativePriceUsd(chainId) {
- const cgId = CG_NATIVE_ID[chainId];
+ const { evmNativeCoingeckoId } = await import('../evm/chain-market.js');
+ const cgId = evmNativeCoingeckoId(chainId);
if (!cgId) return null;
const { fetchCoinPriceUsdOrNull } = await import('../market-fallbacks.js');
return await fetchCoinPriceUsdOrNull(cgId);
diff --git a/api/portfolio/[action].js b/api/portfolio/[action].js
index cbc773d98..8a205772a 100644
--- a/api/portfolio/[action].js
+++ b/api/portfolio/[action].js
@@ -26,6 +26,7 @@ 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';
@@ -455,12 +456,14 @@ async function handleSend(req, res) {
// 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 = "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 ETH on EVM (mainnet coin IDs are used for
-// the price chart; the holding is read directly from the live balances).
+// 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
@@ -526,43 +529,63 @@ const EMPTY_MARKET = {
// within minutes, which left this page with `market: null` and a $0 valuation
// for holdings the user really has. Fall back to the price lanes the platform
// already runs, Solana first: the mint cascade (Birdeye, DexScreener,
-// GeckoTerminal, DefiLlama, Raydium), the SOL spot lane, the coingecko-id spot
-// lane for ETH, and DefiLlama's contract oracle for an ERC-20. These carry
-// price and (where available) 24h change, cap and volume; the descriptive
-// fields stay null and the page already degrades on those.
-async function fallbackMarket({ chain, id, isNative }) {
+// 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 ? { name: 'Solana', price_usd: price, change_24h_pct: change } : null;
+ 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 {
- 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,
+ 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('ethereum');
- return price > 0 ? { name: 'Ethereum', price_usd: price } : null;
+ const price = await fetchCoinPriceUsdOrNull(registry.nativeCoingeckoId);
+ return price > 0 ? { market: { name: registry.nativeName, price_usd: price }, symbol: registry.nativeSymbol } : null;
}
- const price = await fetchFirstOrNull(
+ const key = `${registry.llamaChain}:${id.toLowerCase()}`;
+ const coin = await fetchFirstOrNull(
[
{
name: 'llama-contract',
- url: `https://coins.llama.fi/prices/current/ethereum:${id}`,
+ url: `https://coins.llama.fi/prices/current/${key}`,
parse: async (r) => {
- const p = Number((await r.json())?.coins?.[`ethereum:${id}`]?.price);
- return Number.isFinite(p) && p > 0 ? p : null;
+ 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:${id.slice(0, 10)}` },
+ { timeoutMs: 6000, label: `evm-token-price:${registry.llamaChain}:${id.slice(0, 10)}` },
);
- return price > 0 ? { price_usd: price } : null;
+ 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) {
@@ -579,6 +602,7 @@ async function handleAsset(req, res) {
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');
@@ -586,6 +610,15 @@ async function handleAsset(req, res) {
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;
@@ -599,10 +632,13 @@ async function handleAsset(req, res) {
const holdings = [];
let totalAmount = 0;
let totalUsd = 0;
- let symbol = isNative ? (chain === 'solana' ? 'SOL' : 'ETH') : null;
+ 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];
@@ -625,6 +661,7 @@ async function handleAsset(req, res) {
totalAmount += a;
totalUsd += u;
if (!unitPrice && a > 0) unitPrice = u / a;
+ if (holdingChainId === null) holdingChainId = w.chain_id ?? null;
}
} else {
const tokens = bal.tokens || [];
@@ -651,29 +688,56 @@ async function handleAsset(req, res) {
totalAmount += a;
totalUsd += u;
if (!unitPrice && a > 0) unitPrice = u / a;
+ if (holdingChainId === null) holdingChainId = w.chain_id ?? null;
}
}
- // 2) Pull market data + price history from CoinGecko.
- // For native: use coin id ("solana" or "ethereum").
+ // 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}.
- const platform = chain === 'solana' ? 'solana' : 'ethereum';
- const base = isNative ? `/coins/${platform}` : `/coins/${platform}/contract/${encodeURIComponent(id)}`;
- let { market, symbol: cgSymbol, logo: cgLogo, points: chartPoints } = await loadMarket({
- metaPath: isNative
- ? `${base}?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false`
- : base,
- chartPath: `${base}/market_chart?vs_currency=usd&days=${days}`,
- coingeckoId: isNative ? platform : id,
- days,
- });
- symbol = cgSymbol || symbol;
- logo = logo || cgLogo;
+ // 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 });
- if (fb) market = { ...EMPTY_MARKET, ...(market || {}), ...fb };
+ 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);
}
@@ -689,6 +753,9 @@ async function handleAsset(req, res) {
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
diff --git a/data/changelog.json b/data/changelog.json
index 680d6927a..e63b34dec 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,14 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-08-15",
+ "title": "Portfolio token pages price Base and Arbitrum holdings correctly",
+ "summary": "Opening a token from your portfolio asked Ethereum for the price no matter which chain the token was actually on. Almost every agent wallet runs on Base, so the most common holdings came back with no price, no chart and a shortened contract address instead of a ticker, even though the balance was right there in the list. Each token is now priced on its own chain, labelled with its real symbol and decimals, and native gas tokens use the right coin per chain (POL on Polygon, BNB on BNB Chain, AVAX on Avalanche) instead of always quoting ETH. Chains nobody prices, such as testnets, now say so plainly rather than showing another chain's number.",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-08-15",
"title": "Scanning a skill purchase QR tells you when your wallet is short",
diff --git a/packages/portfolio-mcp/README.md b/packages/portfolio-mcp/README.md
index 74e28e0ca..3a050cae9 100644
--- a/packages/portfolio-mcp/README.md
+++ b/packages/portfolio-mcp/README.md
@@ -84,7 +84,7 @@ Everything reads live state — balances, feeds, and broadcasts all move between
**`get_portfolio_history`** — `days` (1–365, default 90).
-**`get_portfolio_asset`** — `chain` (`solana` | `evm`, required), `id` (`native` or the base58 mint / 0x contract, required), `days` (1–365, default 30).
+**`get_portfolio_asset`**: `chain` (`solana` | `evm`, required), `id` (`native` or the base58 mint / 0x contract, required), `days` (1 to 365, default 30), `chain_id` (optional EVM chain id: 8453 Base, 1 Ethereum, 42161 Arbitrum, 10 Optimism, 137 Polygon, 56 BNB, and the other chains the platform indexes). Leave `chain_id` off and the API prices the contract on whatever chain your wallets hold it on, defaulting to Base; set it when the same address exists on more than one chain.
**`get_trades_feed`** — `network` (`mainnet` | `devnet`, default mainnet), `window` (`1h` | `6h` | `24h` | `7d` | `30d` | `all`, default 24h), `min_pnl_pct` (default 10), `limit` (1–80, default 40), `cursor` (ISO timestamp for pagination), `mint` (filter to one coin).
diff --git a/packages/portfolio-mcp/src/tools/portfolio-asset.js b/packages/portfolio-mcp/src/tools/portfolio-asset.js
index 2bc754a16..9bbb3d5f9 100644
--- a/packages/portfolio-mcp/src/tools/portfolio-asset.js
+++ b/packages/portfolio-mcp/src/tools/portfolio-asset.js
@@ -1,8 +1,8 @@
// `get_portfolio_asset` — a single token's combined position across all of your
// agent wallets, plus live market data and a price chart. Account-scoped. Read-only.
//
-// Wraps GET /api/portfolio/asset?chain&id&days. Combines your holdings of one
-// asset with CoinGecko market data + a price-history chart for that asset.
+// Wraps GET /api/portfolio/asset?chain&id&days&chain_id. Combines your holdings
+// of one asset with CoinGecko market data + a price-history chart for that asset.
import { z } from 'zod';
@@ -31,15 +31,25 @@ export const def = {
.max(365)
.default(30)
.describe('Days of price history for the chart, 1–365 (default 30).'),
+ chain_id: z
+ .number()
+ .int()
+ .positive()
+ .optional()
+ .describe(
+ 'Optional EVM chain id (8453 Base, 1 Ethereum, 42161 Arbitrum, …). Pins which chain the contract ' +
+ 'is priced on; defaults to the chain of the wallets holding it. Ignored on solana.',
+ ),
},
async handler(args) {
const data = await apiRequest('/api/portfolio/asset', {
auth: true,
- query: { chain: args?.chain, id: args?.id, days: args?.days ?? 30 },
+ query: { chain: args?.chain, id: args?.id, days: args?.days ?? 30, chain_id: args?.chain_id },
});
return {
ok: true,
chain: data?.chain ?? args?.chain,
+ chain_id: data?.chain_id ?? args?.chain_id ?? null,
id: data?.id ?? args?.id,
is_native: data?.is_native ?? false,
symbol: data?.symbol ?? null,
diff --git a/prompts/swarm-100/api-portfolio-01.md b/prompts/swarm-100/api-portfolio-01.md
deleted file mode 100644
index 1108ee8f6..000000000
--- a/prompts/swarm-100/api-portfolio-01.md
+++ /dev/null
@@ -1,101 +0,0 @@
-# API audit: api/portfolio batch 01 (1 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/portfolio/[action].js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-portfolio-01.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/public/dashboard/portfolio-asset.html b/public/dashboard/portfolio-asset.html
index e37e680ee..ac10f674a 100644
--- a/public/dashboard/portfolio-asset.html
+++ b/public/dashboard/portfolio-asset.html
@@ -269,6 +269,9 @@
const params = new URLSearchParams(location.search);
const chain = params.get('chain') || '';
const id = params.get('id') || '';
+ // Which EVM chain the token lives on, forwarded from the holdings list so
+ // the API prices the contract on its own chain rather than guessing.
+ const chainId = params.get('chain_id') || '';
let csrfToken = null;
let chart = null;
@@ -348,7 +351,8 @@
}
async function loadAsset(days) {
- const u = `${apiUrl}/portfolio/asset?chain=${encodeURIComponent(chain)}&id=${encodeURIComponent(id)}&days=${days || 30}`;
+ const chainIdQs = chainId ? `&chain_id=${encodeURIComponent(chainId)}` : '';
+ const u = `${apiUrl}/portfolio/asset?chain=${encodeURIComponent(chain)}&id=${encodeURIComponent(id)}${chainIdQs}&days=${days || 30}`;
const r = await fetch(u, { credentials: 'include' });
if (!r.ok) {
const e = await r.json().catch(() => ({}));
diff --git a/public/dashboard/portfolio.html b/public/dashboard/portfolio.html
index 10c8bae8c..bd97fd836 100644
--- a/public/dashboard/portfolio.html
+++ b/public/dashboard/portfolio.html
@@ -878,7 +878,7 @@
const key = `${w.chain}:native`;
let entry = map.get(key);
if (!entry) {
- entry = { key, chain: w.chain, id: 'native', is_native: true, symbol: native.symbol, name: native.name || native.symbol, logo: null, price: native.price || 0, change24h: native.change24h ?? null, amount: 0, usd: 0, wallets: [] };
+ entry = { key, chain: w.chain, chain_id: w.chain_id ?? null, id: 'native', is_native: true, symbol: native.symbol, name: native.name || native.symbol, logo: null, price: native.price || 0, change24h: native.change24h ?? null, amount: 0, usd: 0, wallets: [] };
map.set(key, entry);
}
entry.amount += Number(native.amount || 0);
@@ -891,7 +891,7 @@
const key = `${w.chain}:${id.toLowerCase()}`;
let entry = map.get(key);
if (!entry) {
- entry = { key, chain: w.chain, id, is_native: false, symbol: t.symbol || id.slice(0, 6), name: t.name || t.symbol || id.slice(0, 8), logo: t.logo || null, price: t.price || 0, change24h: t.change24h ?? null, amount: 0, usd: 0, wallets: [] };
+ entry = { key, chain: w.chain, chain_id: w.chain_id ?? null, id, is_native: false, symbol: t.symbol || id.slice(0, 6), name: t.name || t.symbol || id.slice(0, 8), logo: t.logo || null, price: t.price || 0, change24h: t.change24h ?? null, amount: 0, usd: 0, wallets: [] };
map.set(key, entry);
}
entry.amount += Number(t.amount || 0);
@@ -998,7 +998,8 @@
: escapeHtml((r.symbol || '?').slice(0, 3));
const chainCls = r.chain === 'solana' ? 'sol' : 'evm';
const chainText = r.chain === 'solana' ? 'SOL' : 'EVM';
- const href = `/dashboard/portfolio/asset?chain=${encodeURIComponent(r.chain)}&id=${encodeURIComponent(r.is_native ? 'native' : r.id)}`;
+ const chainIdQs = r.chain_id ? `&chain_id=${encodeURIComponent(r.chain_id)}` : '';
+ const href = `/dashboard/portfolio/asset?chain=${encodeURIComponent(r.chain)}&id=${encodeURIComponent(r.is_native ? 'native' : r.id)}${chainIdQs}`;
return `
<a class="h-row" href="${escapeHtml(href)}">
<div class="tok-cell">
diff --git a/src/dashboard-next/pages/portfolio.js b/src/dashboard-next/pages/portfolio.js
index ca8ecc3a2..d16cdfe45 100644
--- a/src/dashboard-next/pages/portfolio.js
+++ b/src/dashboard-next/pages/portfolio.js
@@ -730,7 +730,7 @@ function mergeHoldings(summary) {
if (!ex.price && w.native.price) ex.price = w.native.price;
} else {
map.set(key, {
- chain: w.chain, id: 'native',
+ chain: w.chain, chain_id: w.chain_id ?? null, id: 'native',
symbol: w.native.symbol, name: w.native.name || w.native.symbol,
amount: w.native.amount, price: w.native.price || 0,
change24h: w.native.change24h, usd: w.native.usd || 0, logo: null,
@@ -748,7 +748,7 @@ function mergeHoldings(summary) {
if (!ex.logo && t.logo) ex.logo = t.logo;
} else {
map.set(key, {
- chain: w.chain, id: t.mint || t.contract || '',
+ chain: w.chain, chain_id: w.chain_id ?? null, id: t.mint || t.contract || '',
symbol: t.symbol, name: t.name || t.symbol,
amount: t.amount || 0, price: t.price || 0,
change24h: t.change24h, usd: t.usd || 0, logo: t.logo || null,
@@ -904,7 +904,8 @@ async function openAssetDrawer(token) {
openDrawer();
try {
- const data = await get(`/api/portfolio/asset?chain=${encodeURIComponent(token.chain)}&id=${encodeURIComponent(token.id)}&days=30`);
+ const chainIdQs = token.chain_id ? `&chain_id=${encodeURIComponent(token.chain_id)}` : '';
+ const data = await get(`/api/portfolio/asset?chain=${encodeURIComponent(token.chain)}&id=${encodeURIComponent(token.id)}${chainIdQs}&days=30`);
renderDrawerContent(content, data, token);
} catch (err) {
content.innerHTML = `
diff --git a/tests/api/portfolio-action.test.js b/tests/api/portfolio-action.test.js
index f65afb428..5c083b9d5 100644
--- a/tests/api/portfolio-action.test.js
+++ b/tests/api/portfolio-action.test.js
@@ -9,6 +9,8 @@
// * /asset answered `symbol: "SOL"` for an unknown Solana mint.
// * /asset went blank (`market: null`) whenever CoinGecko throttled our
// egress IP, instead of falling through to the platform's price lanes.
+// * every EVM lookup was hardcoded to Ethereum, so a Base contract (the chain
+// nearly every agent wallet runs on) missed at CoinGecko AND at DefiLlama.
//
// The upstreams (DB, RPC, CoinGecko, the price-fallback lanes) are stubbed at
// their module boundary; everything else in the handler runs for real.
@@ -62,9 +64,10 @@ vi.mock('../../src/solana/sns.js', () => ({
// CoinGecko is the throttled upstream the fallback lanes exist for, so these
// cases run with it failing unless a test opts in.
-const geckoState = { meta: null, chart: null, fail: true };
+const geckoState = { meta: null, chart: null, fail: true, paths: [] };
vi.mock('../../api/_lib/coingecko.js', () => ({
geckoFetch: vi.fn(async (path) => {
+ geckoState.paths.push(path);
if (geckoState.fail) throw Object.assign(new Error('CoinGecko 429'), { status: 429 });
return /market_chart/.test(path) ? geckoState.chart : geckoState.meta;
}),
@@ -72,6 +75,9 @@ vi.mock('../../api/_lib/coingecko.js', () => ({
}));
const priceState = { sol: 0, solChange: null, token: null, coin: null };
+// Every URL the contract-price lane requested, so a test can assert WHICH chain
+// was asked rather than only that a price came back.
+const llamaState = { urls: [], byUrl: {} };
vi.mock('../../api/_lib/sol-price.js', () => ({
solPriceUsd: vi.fn(async () => priceState.sol),
solChange24hPct: vi.fn(async () => priceState.solChange),
@@ -82,8 +88,19 @@ vi.mock('../../api/_lib/market/token-market.js', () => ({
vi.mock('../../api/_lib/market-fallbacks.js', () => ({
fetchCoinPriceUsdOrNull: vi.fn(async () => priceState.coin),
}));
+// Runs each source's real `parse` against a canned payload, so a test asserts
+// the exact upstream URL the handler built (the chain prefix is the whole point).
vi.mock('../../src/shared/failover-fetch.js', () => ({
- fetchFirstOrNull: vi.fn(async () => priceState.coin),
+ fetchFirstOrNull: vi.fn(async (sources) => {
+ for (const s of sources) {
+ llamaState.urls.push(s.url);
+ const payload = llamaState.byUrl[s.url];
+ if (payload === undefined) continue;
+ const out = await s.parse({ ok: true, status: 200, json: async () => payload });
+ if (out != null) return out;
+ }
+ return null;
+ }),
}));
// The signing path must never reach a real RPC or a real key.
@@ -149,6 +166,9 @@ beforeEach(() => {
geckoState.fail = true;
geckoState.meta = null;
geckoState.chart = null;
+ geckoState.paths = [];
+ llamaState.urls = [];
+ llamaState.byUrl = {};
priceState.sol = 0;
priceState.solChange = null;
priceState.token = null;
@@ -244,6 +264,80 @@ describe('asset pricing', () => {
expect((await get('/api/portfolio/asset?chain=bitcoin&id=native', { action: 'asset' })).statusCode).toBe(400);
expect((await get('/api/portfolio/asset?chain=solana', { action: 'asset' })).statusCode).toBe(400);
});
+
+ it('rejects a malformed chain_id', async () => {
+ const r = await get('/api/portfolio/asset?chain=evm&id=native&chain_id=abc', { action: 'asset' });
+ expect(r.statusCode).toBe(400);
+ expect(body(r).error).toBe('validation_error');
+ });
+});
+
+// The EVM asset lane used to ask Ethereum about every contract, whatever chain
+// the wallet was on. Base is the default for an agent wallet, so the single
+// most common EVM holding on the platform came back unpriced and unlabelled.
+describe('asset EVM chain routing', () => {
+ const EVM_WALLET = '0x' + 'ab'.repeat(20);
+ const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+
+ function withEvmWallet(chainId) {
+ sqlState.agent = { id: AGENT_ID, name: 'A', wallet_address: EVM_WALLET, chain_id: chainId, meta: {} };
+ balanceState.byAddress[EVM_WALLET] = {
+ native: { symbol: 'ETH', amount: 0, usd: 0 },
+ tokens: [{ contract: USDC_BASE, symbol: null, decimals: null, amount: 25, usd: 0 }],
+ };
+ }
+
+ it('prices a Base contract on Base, not on Ethereum', async () => {
+ withEvmWallet(8453);
+ llamaState.byUrl[`https://coins.llama.fi/prices/current/base:${USDC_BASE.toLowerCase()}`] = {
+ coins: { [`base:${USDC_BASE.toLowerCase()}`]: { price: 0.9996, symbol: 'USDC', decimals: 6 } },
+ };
+ const r = await get(`/api/portfolio/asset?chain=evm&id=${USDC_BASE}`, { action: 'asset' });
+ expect(r.statusCode).toBe(200);
+ const b = body(r);
+ expect(b.chain_id).toBe(8453);
+ expect(b.market.price_usd).toBe(0.9996);
+ // Labelled from the price lane rather than the 0x83..2913 stub.
+ expect(b.symbol).toBe('USDC');
+ expect(b.decimals).toBe(6);
+ // 25 USDC revalued at the lane's price, not the balance provider's $0.
+ expect(b.total_usd).toBeCloseTo(24.99, 2);
+ expect(llamaState.urls.some((u) => u.includes('ethereum:'))).toBe(false);
+ expect(geckoState.paths.some((p) => p.startsWith('/coins/base/contract/'))).toBe(true);
+ });
+
+ it('honors a pinned chain_id over the wallet default', async () => {
+ withEvmWallet(8453);
+ const arb = '0xaf88d065e77c8cC2239327C5EDb3A432268e5831';
+ llamaState.byUrl[`https://coins.llama.fi/prices/current/arbitrum:${arb.toLowerCase()}`] = {
+ coins: { [`arbitrum:${arb.toLowerCase()}`]: { price: 1.0001, symbol: 'USDC', decimals: 6 } },
+ };
+ const b = body(await get(`/api/portfolio/asset?chain=evm&id=${arb}&chain_id=42161`, { action: 'asset' }));
+ expect(b.chain_id).toBe(42161);
+ expect(b.market.price_usd).toBe(1.0001);
+ expect(geckoState.paths.some((p) => p.startsWith('/coins/arbitrum-one/contract/'))).toBe(true);
+ });
+
+ it('asks no upstream at all for a chain nobody indexes', async () => {
+ withEvmWallet(84532);
+ const b = body(await get(`/api/portfolio/asset?chain=evm&id=${USDC_BASE}`, { action: 'asset' }));
+ expect(b.chain_id).toBe(84532);
+ expect(b.market).toBeNull();
+ expect(geckoState.paths).toHaveLength(0);
+ expect(llamaState.urls).toHaveLength(0);
+ });
+
+ it('prices EVM native from the chain gas token, not always ETH', async () => {
+ withEvmWallet(137);
+ priceState.coin = 0.42;
+ const b = body(await get('/api/portfolio/asset?chain=evm&id=native', { action: 'asset' }));
+ expect(b.chain_id).toBe(137);
+ expect(b.symbol).toBe('POL');
+ expect(b.market.price_usd).toBe(0.42);
+ // POL's coin id, not the retired `matic-network` and not `ethereum`.
+ expect(geckoState.paths.some((p) => p.startsWith('/coins/polygon-ecosystem-token'))).toBe(true);
+ expect(geckoState.paths.some((p) => p.startsWith('/coins/ethereum'))).toBe(false);
+ });
});
describe('send', () => {
diff --git a/tests/fixtures/mcp-golden-tools.json b/tests/fixtures/mcp-golden-tools.json
index b9077d187..fc74e49ca 100644
--- a/tests/fixtures/mcp-golden-tools.json
+++ b/tests/fixtures/mcp-golden-tools.json
@@ -2665,7 +2665,7 @@
"idempotentHint": false,
"openWorldHint": true
},
- "schemaHash": "b8b2b70c9e52"
+ "schemaHash": "ccd5ad86fcd2"
}
],
"packages/portfolio-mcp/src/tools/portfolio-history.js": [