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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
docs(market): document the Tokens API integration and cover the rung with tests
nirholase163688615d2
diff --git a/api/_lib/tokens-xyz.js b/api/_lib/tokens-xyz.jsindex 742e54ad7..896c0bcf6 100644--- a/api/_lib/tokens-xyz.js+++ b/api/_lib/tokens-xyz.js@@ -23,7 +23,7 @@// failover cascade in api/_lib/market/token-market.js, which already owns an// L1 + L2 + single-flight cache and would otherwise cache the same value twice.//-// Contract reference: docs/integrations/tokens-xyz.md+// Contract reference: docs/tokens-xyz.mdimport { cacheWrap } from './cache.js';diff --git a/data/pages.json b/data/pages.jsonindex 5f7239a3b..c5e32f1d1 100644--- a/data/pages.json+++ b/data/pages.json@@ -3489,6 +3489,14 @@"priority": 0.6,"changefreq": "monthly"},+ {+ "path": "/docs/tokens-xyz",+ "title": "Docs · Tokens API on three.ws",+ "description": "The Solana Foundation asset layer wired into three.ws: how one canonical asset maps to every Solana mint that represents it, the batch market read that prices a whole portfolio in one call, and where it sits in the price failover chain behind Birdeye.",+ "priority": 0.6,+ "changefreq": "monthly",+ "added": "2026-08-11"+ },{"path": "/docs/free-llm-providers","title": "Docs · The free LLM failover chain",diff --git a/docs/start-here.md b/docs/start-here.mdindex 23a1d29d2..4c8f6e8f5 100644--- a/docs/start-here.md+++ b/docs/start-here.md@@ -156,6 +156,7 @@ Deeper references that don't fit a track above but answer real questions:- [Design tokens](./DESIGN-TOKENS.md): the canonical design vocabulary (colors, spacing, type, motion) every surface builds from- [NVIDIA models on three.ws](./nvidia-models.md): the free hosted inference layer model by model, one key behind text-to-3D, chat, vision, embeddings, safety, and speech- [Free LLM providers](./free-llm-providers.md): the failover chain of a dozen free AI providers behind every text completion, what each free tier gives, and how to add the next rung+- [Tokens API on three.ws](./tokens-xyz.md): the Solana Foundation asset layer that tells us which mints are the same asset, why it sits second in the market-data cascade, and the one env var that turns it on- [NVIDIA Inception membership](./nvidia-inception.md): what the platform already runs on NVIDIA silicon and what the program adds on top- [The generator was never the hard part](./nvidia-nemotron-spotlight.md): our Nemotron Nano write-up, published on the NVIDIA Developer Forums- [three.ws on the AWS Builder Center](./aws-builder-center.md): the index of our published AWS engineering writing, what code each article documents, and the checklist for publishing the next onediff --git a/docs/tokens-xyz.md b/docs/tokens-xyz.mdnew file mode 100644index 000000000..e97ea4884--- /dev/null+++ b/docs/tokens-xyz.md@@ -0,0 +1,144 @@+# Tokens API on three.ws++[api.tokens.xyz](https://api.tokens.xyz) is the Solana Foundation's asset layer. Every other market source this platform reads is **mint-scoped**: DexScreener, GeckoTerminal, Birdeye and Raydium each answer "what is this one mint worth?" and nothing more. Tokens API answers a question none of them can: **which mints are the same asset?**++That is the whole reason it is wired in. wSOL, bridged SOL and a liquid-staking derivative are three unrelated base58 strings to every other source. Tokens API groups them into one canonical asset (`solana`) and hands back each variant with its own market, liquidity tier, trust tier and, where covered, a cached fill-quality score. A wallet panel can then say "you hold $412 of USD across 3 mints" instead of printing three rows it cannot relate to each other.++- Client: [api/\_lib/tokens-xyz.js](../api/_lib/tokens-xyz.js)+- Market-data rung: [api/\_lib/market/token-market.js](../api/_lib/market/token-market.js)+- Tests: [tests/tokens-xyz.test.js](../tests/tokens-xyz.test.js), [tests/api/token-market-tokensxyz.test.js](../tests/api/token-market-tokensxyz.test.js)+- Upstream contract: <https://docs.tokens.xyz/v1/quickstart>++## Configuration++One environment variable, server-side only:++```+TOKENS_XYZ_API_KEY=<key from the Tokens API dashboard>+```++**Without it every entry point is inert.** `resolveAsset` returns `null`, the list readers return `[]`, the batch reader returns an empty `Map`, and the market rung is skipped before it makes a request. An unconfigured deployment behaves exactly as it did before this module existed, which is why the integration can ship ahead of the key.++The key is never sent in a URL and never reaches the browser. It travels as the `x-api-key` header from server-side handlers only.++## What the client exposes++```js+import {+ tokensXyzConfigured,+ resolveAsset,+ fetchAssetVariants,+ fetchVariantMarkets,+ fetchMintMarket,+ fetchTrending,+ fetchRiskSummary,+} from '../_lib/tokens-xyz.js';+```++### Resolve any reference to a canonical asset++`ref` accepts a canonical id (`usd`), an alias, a raw Solana mint, or the `solana-<mint>` singleton form. A mint belonging to no canonical group comes back as its own singleton asset, so a real mint the registry has seen never resolves to nothing.++```js+const asset = await resolveAsset({ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' });+// {+// asset_id: 'three', resolved_by: 'mint', mint: 'FeMb…pump',+// name: 'Three', symbol: 'THREE', category: 'crypto', aliases: [],+// variant: { mint: 'FeMb…pump', chain: 'solana', kind: 'native',+// liquidity_tier: 'tier2', trust_tier: 'tier2', tags: [], … },+// }+```++Cached for 6 hours: a mint-to-asset mapping changes when the upstream registry does, which is rare, and the key carries a monthly quota worth protecting.++### List every variant of an asset++```js+const variants = await fetchAssetVariants(asset.asset_id, { sortBy: 'liquidity' });+for (const v of variants) {+ console.log(v.label, v.mint, v.market?.price_usd, v.market?.liquidity, v.execution?.score);+}+```++`sortBy` accepts `liquidity` (default), `execution_quality`, or `stock_redeemability`. Optional filters: `kind`, `liquidityTier`, `stockVariantTier`.++Each row carries:++| Field | Meaning |+| --- | --- |+| `mint`, `chain`, `kind`, `label` | Variant identity (`native`, `wrapped`, `bridged`, `lst`, `tokenized_equity`, …) |+| `liquidity_tier`, `trust_tier` | Upstream's depth and trust banding, `tier1` strongest |+| `market` | Price, liquidity, volume, cap, change, decimals, logo, and which upstream produced them |+| `execution` | Cached 24h fill quality (score, bot-volume ratio, fee bps, flow sources), or `null` where uncovered |+| `stock_variant_tier` | Redeemability for tokenized equities. Provider metadata for routing and display, never advice |++`market.metrics_source` is worth reading before you trust a number. `clickhouse_trades` means the figures were materialized from direct USD-stable on-chain fills; `birdeye` and `rwa_xyz` mean they came from an aggregator.++### Batch market data for a whole portfolio++This is the read the per-mint sources cannot do. Forty tokens cost forty DexScreener calls but one Tokens API call:++```js+const markets = await fetchVariantMarkets(mintsHeldByWallet);+const total = mintsHeldByWallet.reduce(+ (sum, mint) => sum + (markets.get(mint)?.market?.price_usd ?? 0) * balanceOf(mint),+ 0,+);+```++Requests are chunked to the upstream cap of 50 mints per call and the input is de-duplicated first. A mint with no cached snapshot comes back as `{ asset_id, market: null, execution: null }` rather than being dropped, so the caller can tell "no data" apart from "not requested". Pass `{ strict: true }` to get an upstream failure thrown instead of a partial map.++The sibling `POST /assets/market-snapshots` endpoint takes 250 mints, but its row shape is documented as unstable, so this client uses the typed `variant-markets` endpoint and chunks instead.++### Trending, risk++```js+const hot = await fetchTrending({ limit: 20, category: 'crypto' });+const risk = await fetchRiskSummary(mint);+```++Trending ranks individual mints by short-window momentum from direct USD-stable trades. Native/wrapped SOL and stablecoins are excluded upstream because they dominate Solana routing volume.++`fetchRiskSummary` passes an `insufficient_data: true` verdict straight through. Upstream needs a cached market snapshot to score at all, and a token it has never seen is reported as unscored, never as a pass.++## Where it sits in the market-data cascade++[api/\_lib/market/token-market.js](../api/_lib/market/token-market.js) reads a mint through an ordered chain, each rung normalized to one shape:++1. **Birdeye** (keyed) - richest, the only rung carrying a holder count+2. **Tokens API** (keyed) - price, liquidity, volume, cap, and direct on-chain trade metrics+3. **DexScreener** (keyless)+4. **GeckoTerminal** (keyless)+5. **DefiLlama coins** (keyless, price only)+6. **Raydium** (keyless, price only)++Tokens API sits second because it carries no holder count (so it cannot displace Birdeye) but its numbers can come from real fills rather than a pool estimate (so it belongs ahead of the keyless aggregators). It reports `source: 'tokensxyz'` and derives `supply` from cap over price, the same way the DexScreener rung does.++Two behaviors are load-bearing and covered by tests:++- With no key the rung is skipped **before** any request, so the cascade is byte-for-byte the one that ran before it existed.+- A 429 (rate limit or exhausted monthly quota) is rethrown with the status leading the message, which is what the cascade's circuit breaker matches on to bench the source for its cooldown window. A throttled key costs one request, not one per read.++## Errors and retries++The client follows the upstream retry matrix exactly:++| Status | Behavior |+| --- | --- |+| 429, transient 5xx | Retried with exponential backoff plus jitter (2 attempts by default) |+| 400, 401, 403, 404 | Thrown immediately - retrying burns quota and cannot succeed |++The market rung overrides `retries` to 0: a failover chain would rather move to the next source than sit through a backoff.++Upstream's error envelope (`{ error: { _tag, message } }`) is unwrapped into the thrown message, prefixed with the numeric status: `429 RateLimitedError: slow down`.++## Caching and quota++Limits **and** monthly quotas are enforced per key and both answer 429, so every read whose answer is stable goes through the shared cache: resolve 6h, variants 10m, trending 60s, risk 5m. A transient failure returns `null` internally so `cacheWrap` never pins an outage as "this asset has no variants".++The batch market read is deliberately **not** cached here. Its caller in the market cascade already owns an L1 in-process cache, an L2 cross-instance cache and a fleet-wide single-flight lock; caching the same value twice would only make the second copy stale in a different way.++## Related++- [Market Data API](./market-data-api.md) - the pay-per-call x402 endpoints behind every `/markets` page+- [Free LLM providers](./free-llm-providers.md) - the same failover-chain pattern applied to text completiondiff --git a/tests/api/token-market-tokensxyz.test.js b/tests/api/token-market-tokensxyz.test.jsnew file mode 100644index 000000000..9d23cc716--- /dev/null+++ b/tests/api/token-market-tokensxyz.test.js@@ -0,0 +1,140 @@+// The Tokens API rung inside api/_lib/market/token-market.js.+//+// Two properties matter and neither is obvious from reading the cascade:+// 1. Without TOKENS_XYZ_API_KEY the rung must be completely inert, so an+// unconfigured deployment keeps the exact source order it had before.+// 2. With the key it must sit behind Birdeye and ahead of DexScreener, and a+// throttled key must reach the circuit breaker rather than being swallowed+// inside the client.+//+// Fetch is fully stubbed; no network. The mint is a synthetic placeholder.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++let fetchCalls = [];+let fetchResponses = [];+vi.stubGlobal('fetch', (url) => {+ fetchCalls.push(String(url));+ const resp = fetchResponses.shift();+ if (!resp) throw new Error(`Unexpected fetch: ${url}`);+ return Promise.resolve({+ ok: resp.ok ?? true,+ status: resp.status ?? 200,+ json: async () => resp.body,+ text: async () => (typeof resp.body === 'string' ? resp.body : JSON.stringify(resp.body)),+ });+});++import { fetchTokenMarketData, __resetMarketCache } from '../../api/_lib/market/token-market.js';++const MINT = 'THREEsynthetic111111111111111111111111111111';++const BIRDEYE_DOWN = { ok: false, status: 500, body: 'upstream down' };+const TOKENS_XYZ_OK = {+ body: {+ variants: [+ {+ mint: MINT,+ assetId: 'three',+ chain: 'solana',+ market: {+ price: 0.25,+ liquidity: 90_000,+ volume24hUSD: 12_000,+ marketCap: 250_000,+ priceChange24hPercent: 3.2,+ decimals: 6,+ metricsSource: 'clickhouse_trades',+ },+ executionQuality: null,+ },+ ],+ },+};+const DEX_OK = {+ body: {+ pairs: [+ { priceUsd: '0.5', marketCap: 500_000, liquidity: { usd: 100_000 }, volume: { h24: 5_000 }, priceChange: { h24: 1.5 } },+ ],+ },+};++beforeEach(() => {+ fetchCalls = [];+ fetchResponses = [];+ __resetMarketCache();+});++afterEach(() => {+ delete process.env.BIRDEYE_API_KEY;+ delete process.env.TOKENS_XYZ_API_KEY;+ if (fetchResponses.length) throw new Error(`Test left ${fetchResponses.length} unconsumed fetch mock(s)`);+});++describe('tokens.xyz rung', () => {+ it('is skipped entirely when the key is absent', async () => {+ fetchResponses = [DEX_OK];+ const out = await fetchTokenMarketData(MINT, { fresh: true });++ expect(out.source).toBe('dexscreener');+ expect(fetchCalls.some((u) => u.includes('tokens.xyz'))).toBe(false);+ });++ it('answers ahead of DexScreener once the key is configured', async () => {+ process.env.TOKENS_XYZ_API_KEY = 'test-key';+ fetchResponses = [TOKENS_XYZ_OK];+ const out = await fetchTokenMarketData(MINT, { fresh: true });++ expect(out).toMatchObject({+ source: 'tokensxyz',+ price_usd: 0.25,+ price_change_24h: 3.2,+ market_cap: 250_000,+ volume_24h: 12_000,+ liquidity: 90_000,+ decimals: 6,+ });+ // No supply field upstream; derived from cap / price like the DexScreener rung.+ expect(out.supply).toBe(1_000_000);+ expect(fetchCalls.some((u) => u.includes('dexscreener'))).toBe(false);+ });++ it('sits behind Birdeye and takes over when Birdeye is down', async () => {+ process.env.BIRDEYE_API_KEY = 'birdeye-key';+ process.env.TOKENS_XYZ_API_KEY = 'test-key';+ fetchResponses = [BIRDEYE_DOWN, TOKENS_XYZ_OK];+ const out = await fetchTokenMarketData(MINT, { fresh: true });++ expect(out.source).toBe('tokensxyz');+ expect(fetchCalls[0]).toContain('birdeye');+ expect(fetchCalls[1]).toContain('tokens.xyz');+ });++ it('falls through to DexScreener when the mint has no cached snapshot upstream', async () => {+ process.env.TOKENS_XYZ_API_KEY = 'test-key';+ fetchResponses = [+ { body: { variants: [{ mint: MINT, assetId: null, chain: 'solana', market: null, executionQuality: null }] } },+ DEX_OK,+ ];+ const out = await fetchTokenMarketData(MINT, { fresh: true });++ expect(out.source).toBe('dexscreener');+ });++ it('benches the source for the cooldown window after a 429', async () => {+ process.env.TOKENS_XYZ_API_KEY = 'test-key';+ fetchResponses = [+ { ok: false, status: 429, body: { error: { _tag: 'RateLimitedError', message: 'slow down' } } },+ DEX_OK,+ ];+ const first = await fetchTokenMarketData(MINT, { fresh: true });+ expect(first.source).toBe('dexscreener');++ // Second read must not touch tokens.xyz again: the breaker holds it down.+ fetchCalls = [];+ fetchResponses = [DEX_OK];+ const second = await fetchTokenMarketData(MINT, { fresh: true });+ expect(second.source).toBe('dexscreener');+ expect(fetchCalls.some((u) => u.includes('tokens.xyz'))).toBe(false);+ });+});