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
feat(trader-card): add the engine and endpoint the docs already describe
nirholas66a7293d95fb
diff --git a/api/_lib/trader-card.js b/api/_lib/trader-card.jsnew file mode 100644index 000000000..80383fccf--- /dev/null+++ b/api/_lib/trader-card.js@@ -0,0 +1,120 @@+/**+ * The trader card model: one trader reduced to what fits in someone else's page.+ *+ * `/api/sniper/trader` answers "show me everything", and for a well-traded agent+ * that is a quarter of a megabyte of history. A widget running in a stranger's+ * blog, stream overlay or link-in-bio cannot pay that, and does not need it: it+ * needs the headline record, the last few results, whatever is open right now,+ * and a way to act. This module is that projection, pure and separate from the+ * endpoint that serves it so the shape can be tested without a database.+ *+ * Every number here is copied from `computeTraderMetrics`, the same truth layer+ * the leaderboard and the profile read, so an embedded card on a third-party+ * site cannot show a record that three.ws itself would dispute.+ */++const SITE = 'https://three.ws';++/** Round to `d` places, preserving null rather than turning it into a zero. */+function round(n, d = 6) {+ if (n == null || !Number.isFinite(Number(n))) return null;+ return Number(Number(n).toFixed(d));+}++/**+ * The return multiple of a closed round-trip, derived from its realized+ * percentage rather than exit over entry: a position that took its initials out+ * first rewrote its own cost basis, so exit/entry would understate it. Matches+ * how the Live Trade Feed derives the same number.+ */+export function multipleFromPct(pct) {+ if (pct == null || !Number.isFinite(Number(pct))) return null;+ return round(1 + Number(pct) / 100, 3);+}++/** Absolute three.ws links, because the card renders on someone else's origin. */+export function cardLinks({ agentId, mint = null, size = null, window: win = '30d', ref = null }) {+ const q = (params) => {+ const u = new URLSearchParams(params);+ if (ref) u.set('ref', ref);+ const s = u.toString();+ return s ? `?${s}` : '';+ };+ return {+ profile: `${SITE}/trader/${agentId}${q({})}`,+ ghost_copy: `${SITE}/ghost-copy${q({ leader: agentId, window: win })}`,+ fork: mint ? `${SITE}/trades${q({ fork: mint, ...(size ? { fork_size: String(size) } : {}) })}` : null,+ site: `${SITE}${q({})}`,+ };+}++/**+ * Project a full `getTraderStats` result into the card payload.+ *+ * `recentLimit` closed round-trips and `openLimit` live positions is the whole+ * budget: enough to prove the record is moving, small enough that the card stays+ * a few kilobytes no matter how long the trader has been running.+ */+export function buildTraderCard(stats, { recentLimit = 3, openLimit = 2, ref = null } = {}) {+ if (!stats || !stats.agent) return null;+ const m = stats.metrics || {};+ const agentId = stats.agent.id;+ const win = stats.window;++ const recent = (stats.closed || [])+ .slice(0, recentLimit)+ .map((t) => ({+ mint: t.mint,+ symbol: t.symbol || null,+ pnl_sol: round(t.pnl_sol),+ pnl_pct: round(t.pnl_pct, 2),+ multiple: multipleFromPct(t.pnl_pct),+ exit_reason: t.exit_reason || null,+ closed_at: t.closed_at,+ moonbag_held: !!t.moonbag_held,+ tx_url: t.sell_url || t.buy_url || null,+ fork_url: cardLinks({ agentId, mint: t.mint, window: win, ref }).fork,+ }));++ const open = (stats.open || [])+ .slice(0, openLimit)+ .map((t) => ({+ mint: t.mint,+ symbol: t.symbol || null,+ entry_sol: round(t.entry_sol),+ unrealized_pct: round(t.unrealized_pct, 2),+ opened_at: t.opened_at,+ fork_url: cardLinks({ agentId, mint: t.mint, size: round(t.entry_sol, 4), window: win, ref }).fork,+ }));++ return {+ agent: {+ id: agentId,+ name: stats.agent.name || 'Unnamed trader',+ image: stats.agent.image || null,+ verified: !!m.verified,+ copiers: Number(stats.agent.copiers || 0),+ },+ network: stats.network,+ window: win,+ sol_usd: stats.sol_usd ?? null,+ stats: {+ score: m.score ?? null,+ closed: m.closed_count ?? 0,+ wins: m.wins ?? 0,+ losses: m.losses ?? 0,+ win_rate: m.win_rate ?? null,+ realized_pnl_sol: round(m.realized_pnl_sol),+ realized_pnl_usd: round(m.realized_pnl_usd, 2),+ roi_pct: m.roi_pct ?? null,+ best_pnl_pct: m.best_pnl_pct ?? null,+ max_drawdown_pct: m.max_drawdown_pct ?? null,+ open_positions: m.open_count ?? 0,+ last_active_at: m.last_active_at || null,+ },+ recent,+ open,+ links: cardLinks({ agentId, window: win, ref }),+ computed_at: new Date().toISOString(),+ };+}diff --git a/api/sniper/trader-card.js b/api/sniper/trader-card.jsnew file mode 100644index 000000000..513dbffdc--- /dev/null+++ b/api/sniper/trader-card.js@@ -0,0 +1,63 @@+/**+ * Trader card: the compact, embeddable read of one trader's record.+ *+ * GET /api/sniper/trader-card?agent=<uuid>&network=mainnet&window=30d&ref=<code>+ *+ * What `<trader-card>` (public/trader-card/element.js) renders on a third-party+ * page, and small enough to be worth putting there: the headline record, the+ * last few closed round-trips, whatever is open right now, and absolute links+ * back into three.ws to fork a coin or ghost-copy the trader.+ *+ * Same truth layer as the leaderboard and the profile (`getTraderStats`), so an+ * embedded card cannot claim a record three.ws would dispute. Public, CORS open+ * by design (an embed is cross-origin by definition) and IP rate-limited.+ */++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getTraderStats, WINDOWS } from '../_lib/trader-stats.js';+import { buildTraderCard } from '../_lib/trader-card.js';+import { isUuid } from '../_lib/validate.js';++const NETWORKS = new Set(['mainnet', 'devnet']);+// Referral codes travel from the widget into every link it renders, so the value+// is bounded and character-checked before it is ever put in a URL.+const REF_RE = /^[A-Za-z0-9_-]{1,32}$/;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;+ const agentId = (params.get('agent') || params.get('agent_id') || '').trim();+ if (!isUuid(agentId)) {+ return error(res, 400, 'invalid_agent', 'agent must be a valid agent UUID');+ }+ const rawNetwork = params.get('network');+ if (rawNetwork && !NETWORKS.has(rawNetwork)) {+ return error(res, 400, 'invalid_network', 'network must be mainnet or devnet');+ }+ const rawWindow = params.get('window');+ if (rawWindow && !WINDOWS.has(rawWindow)) {+ return error(res, 400, 'invalid_window', `window must be one of ${[...WINDOWS].join(', ')}`);+ }+ const ref = params.get('ref');+ if (ref && !REF_RE.test(ref)) {+ return error(res, 400, 'invalid_ref', 'ref must be 1 to 32 letters, digits, hyphens or underscores');+ }++ const stats = await getTraderStats({+ agentId,+ network: rawNetwork || 'mainnet',+ window: rawWindow || '30d',+ });+ if (!stats || !stats.agent.is_public) {+ return error(res, 404, 'not_found', 'No such agent, or it is not public.');+ }++ const card = buildTraderCard(stats, { ref: ref || null });+ return json(res, 200, card, { 'cache-control': 'public, max-age=60, s-maxage=120' });+});