Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: shared agent coin chip + reliable zauth telemetry drain

nirholas2a737b023307
diff --git a/.env.example b/.env.example
index 0ef8dd540..c92978264 100644
--- a/.env.example
+++ b/.env.example
@@ -374,6 +374,11 @@ CDP_API_KEY_SECRET=
ZAUTH_API_KEY=
# Set to "1" to enable verbose [zauthSDK:*] logs in Vercel.
ZAUTH_DEBUG=
+# Set to "1" to include request/response bodies in zauth telemetry. OFF by
+# default — these are payment + MCP endpoints, so bodies (payment payloads,
+# tool args) are withheld from the third-party backend. Endpoint health is
+# reported regardless. Enable only for short-lived debugging.
+ZAUTH_INCLUDE_BODIES=
# ── Resend (transactional email) ─────────────────────────────────────────────
# Powers: account welcome, email verification codes, password reset, subscription
diff --git a/api/_lib/env.js b/api/_lib/env.js
index dc7747d3a..3b48e44ce 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -509,6 +509,15 @@ export const env = {
return opt('ZAUTH_DEBUG');
},
+ // Set to "1" to include request/response bodies in zauth telemetry. OFF by
+ // default: these endpoints carry payment payloads and MCP tool args, which
+ // must not be shipped to a third-party backend. Enable only for short-lived
+ // debugging. Endpoint health (status/timing/validation verdict) is reported
+ // regardless — body capture is not needed for WORKING/FAILING classification.
+ get ZAUTH_INCLUDE_BODIES() {
+ return opt('ZAUTH_INCLUDE_BODIES');
+ },
+
// Solana RPC URL — single source of truth for all Solana RPC calls.
// Set to a Helius/QuickNode/Triton URL in production to avoid public RPC rate limits.
get SOLANA_RPC_URL() {
diff --git a/api/_lib/zauth.js b/api/_lib/zauth.js
index d881bcdc9..67e7af596 100644
--- a/api/_lib/zauth.js
+++ b/api/_lib/zauth.js
@@ -21,6 +21,43 @@ import { env } from './env.js';
let cached;
let _bootLogged = false;
+// The SDK submits telemetry with a fire-and-forget `fetch` it never hands back
+// a promise for, so on Vercel the function can freeze mid-POST and silently
+// drop the event. We wrap `fetch` once (only when monitoring is enabled) to
+// track in-flight POSTs to the zauth backend; `drain()` then awaits exactly
+// those, capped — reliable delivery instead of a fixed-time guess. Only
+// zauth-host requests are ever tracked; all other traffic passes through
+// untouched and unobserved.
+const ZAUTH_HOST = (process.env.ZAUTH_API_ENDPOINT || 'https://back.zauthx402.com')
+ .replace(/^https?:\/\//, '')
+ .replace(/\/.*$/, '');
+const _inflight = new Set();
+let _fetchWrapped = false;
+
+function trackZauthFetch() {
+ if (_fetchWrapped || typeof globalThis.fetch !== 'function') return;
+ _fetchWrapped = true;
+ const realFetch = globalThis.fetch.bind(globalThis);
+ globalThis.fetch = (input, init) => {
+ const url = typeof input === 'string' ? input : input?.url || '';
+ const promise = realFetch(input, init);
+ if (url.includes(ZAUTH_HOST)) {
+ _inflight.add(promise);
+ const clear = () => _inflight.delete(promise);
+ promise.then(clear, clear);
+ }
+ return promise;
+ };
+}
+
+// The deploy environment reported to the Provider Hub dashboard. The SDK
+// defaults to 'development'; without this, production telemetry would be
+// mislabeled. VERCEL_ENV is 'production' | 'preview' | 'development' on Vercel.
+function resolveEnvironment() {
+ if (env.VERCEL_ENV === 'production' || env.NODE_ENV === 'production') return 'production';
+ return env.VERCEL_ENV || 'development';
+}
+
function buildMiddleware() {
const apiKey = env.ZAUTH_API_KEY;
if (!apiKey) {
@@ -36,11 +73,39 @@ function buildMiddleware() {
// POST to back.zauthx402.com). Force flush-per-event so submission
// starts immediately; the `drain()` helper below keeps the lambda
// alive long enough for that POST to complete.
+ const includeBodies = env.ZAUTH_INCLUDE_BODIES === '1';
const mw = zauthProvider(apiKey, {
+ environment: resolveEnvironment(),
shouldMonitor: shouldMonitorReq,
debug: env.ZAUTH_DEBUG === '1',
batching: { maxBatchSize: 1, maxBatchWaitMs: 0, retry: false },
+ // Privacy: the monitored routes are payment and MCP endpoints. Ship
+ // status/timing/validation telemetry, but NOT the request/response
+ // bodies (payment payloads, tool args) unless explicitly opted in.
+ // The SDK validates responses locally and only reports the verdict,
+ // so health classification is unaffected when bodies are withheld.
+ telemetry: {
+ includeRequestBody: includeBodies,
+ includeResponseBody: includeBodies,
+ // redactHeaders replaces (not merges) the SDK default list, so we
+ // restate its entries and add every header that can carry a payment
+ // proof, session, or secret on these routes.
+ redactHeaders: [
+ 'authorization',
+ 'cookie',
+ 'set-cookie',
+ 'x-api-key',
+ 'x-api-secret',
+ 'x-payment',
+ 'x-payment-intent',
+ 'x-payment-signature',
+ 'x-payment-response',
+ 'payment-signature',
+ 'sign-in-with-x',
+ ],
+ },
});
+ trackZauthFetch();
if (env.ZAUTH_DEBUG === '1' && !_bootLogged) {
console.log('[zauth] middleware initialized');
_bootLogged = true;
@@ -76,6 +141,7 @@ export function status() {
initialized,
hasKey: Boolean(apiKey),
keyPrefix: apiKey ? apiKey.slice(0, 14) : null,
+ environment: resolveEnvironment(),
debug: env.ZAUTH_DEBUG === '1',
};
}
@@ -152,10 +218,27 @@ export function instrument(req, res) {
}
/**
- * Wait briefly for the SDK's fire-and-forget POST to `back.zauthx402.com`
- * to complete before Vercel freezes the function. Only call this on
- * requests where `instrument()` returned true.
+ * Hold the lambda open until the SDK's in-flight telemetry POST(s) to the
+ * zauth backend actually settle, so Vercel doesn't freeze the function
+ * mid-flush and drop the event. Awaits the tracked fetches rather than a fixed
+ * delay; capped by ZAUTH_DRAIN_MAX_MS (default 1500ms) so a hung backend can
+ * never stall the response runtime. Only call this on requests where
+ * `instrument()` returned true.
*/
export function drain() {
- return new Promise((resolve) => setTimeout(resolve, 250));
+ const capMs = Number(process.env.ZAUTH_DRAIN_MAX_MS) || 1500;
+ if (_inflight.size === 0) {
+ // The POST may be scheduled on the next microtask; give it a beat to
+ // register, then settle whatever appeared.
+ return new Promise((resolve) => setTimeout(resolve, 50)).then(() =>
+ _inflight.size ? settleInflight(capMs) : undefined,
+ );
+ }
+ return settleInflight(capMs);
+}
+
+function settleInflight(capMs) {
+ const pending = Promise.allSettled([..._inflight]);
+ const cap = new Promise((resolve) => setTimeout(resolve, capMs));
+ return Promise.race([pending, cap]);
}
diff --git a/api/healthz.js b/api/healthz.js
index f1b527a09..96566cfac 100644
--- a/api/healthz.js
+++ b/api/healthz.js
@@ -157,6 +157,21 @@ async function probeX402() {
result.facilitator = 'not_configured';
}
+ // Provider Hub (zauthx402) x402 telemetry — report whether the SDK
+ // initialized so the integration is observable in prod. Booleans only:
+ // no key material is surfaced on this public, unauthenticated endpoint.
+ try {
+ const { status: zauthStatus } = await import('./_lib/zauth.js');
+ const z = zauthStatus();
+ result.telemetry = {
+ provider: 'zauthx402',
+ configured: z.hasKey,
+ initialized: z.initialized,
+ };
+ } catch {
+ result.telemetry = { provider: 'zauthx402', configured: false, initialized: false };
+ }
+
// Recent payments from audit log
result.recent_payments = await countRecentPayments(60);
diff --git a/scripts/verify-zauth-runtime.mjs b/scripts/verify-zauth-runtime.mjs
new file mode 100644
index 000000000..76ef82b1c
--- /dev/null
+++ b/scripts/verify-zauth-runtime.mjs
@@ -0,0 +1,133 @@
+// Runtime proof that the zauth (Provider Hub) telemetry layer actually fires.
+//
+// Static review already confirmed the wiring matches the SDK + docs; this goes
+// further and exercises our REAL api/_lib/zauth.js (instrument → res.end →
+// drain) with a test API key, intercepting global.fetch to confirm the SDK
+// emits a telemetry POST to back.zauthx402.com for monitored requests — and
+// stays silent for non-monitored ones.
+//
+// node scripts/verify-zauth-runtime.mjs
+//
+// Uses a synthetic key, so the upstream would reject it; we only assert that
+// the request lifecycle drives an outbound telemetry submission.
+import { EventEmitter } from 'node:events';
+
+// Enable the layer with a synthetic key BEFORE importing our module (env.js
+// reads process.env live, and the middleware is built lazily on first use).
+process.env.ZAUTH_API_KEY = 'zk_test_runtime_verify_0001';
+process.env.ZAUTH_DEBUG = '1';
+
+// Capture every outbound telemetry POST instead of hitting the network.
+const telemetryCalls = [];
+const realFetch = globalThis.fetch;
+globalThis.fetch = async (url, init = {}) => {
+ const u = typeof url === 'string' ? url : url?.url || String(url);
+ if (/zauthx402\.com/i.test(u)) {
+ telemetryCalls.push({ url: u, method: init.method || 'GET', body: init.body });
+ return new Response(JSON.stringify({ ok: true, accepted: 1 }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+ }
+ return realFetch ? realFetch(url, init) : new Response('null', { status: 200 });
+};
+
+const { instrument, drain, status } = await import('../api/_lib/zauth.js');
+
+function makeReq({ url, method = 'GET', headers = {} }) {
+ return {
+ url,
+ method,
+ headers: { host: 'three.ws', ...headers },
+ socket: { remoteAddress: '203.0.113.7' },
+ };
+}
+
+// Minimal ServerResponse stand-in: an EventEmitter exposing the surface the
+// Express-shaped SDK touches (statusCode, header accessors, end/write).
+function makeRes() {
+ const res = new EventEmitter();
+ const headersStore = {};
+ res.statusCode = 200;
+ res.headersSent = false;
+ res.writableEnded = false;
+ res.setHeader = (k, v) => {
+ headersStore[String(k).toLowerCase()] = v;
+ };
+ res.getHeader = (k) => headersStore[String(k).toLowerCase()];
+ res.removeHeader = (k) => delete headersStore[String(k).toLowerCase()];
+ res.write = () => true;
+ res.end = function end(body) {
+ res.writableEnded = true;
+ res.headersSent = true;
+ res.emit('finish');
+ res.emit('close');
+ return res;
+ };
+ return res;
+}
+
+async function runCase({ name, req: reqSpec, statusCode = 200, expectMonitored }) {
+ telemetryCalls.length = 0;
+ const req = makeReq(reqSpec);
+ const res = makeRes();
+ const monitored = instrument(req, res);
+
+ // Simulate a handler producing a response.
+ res.statusCode = statusCode;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ ok: true }));
+
+ if (monitored) await drain();
+ // Give any microtask-scheduled submission a beat to run.
+ await new Promise((r) => setTimeout(r, 50));
+
+ const emitted = telemetryCalls.length > 0;
+ const pass = monitored === expectMonitored && emitted === expectMonitored;
+ console.log(
+ `${pass ? '✓' : '✗'} ${name}\n` +
+ ` shouldMonitor=${monitored} (expected ${expectMonitored}) · ` +
+ `telemetryPOSTs=${telemetryCalls.length}` +
+ (telemetryCalls[0] ? ` → ${telemetryCalls[0].method} ${telemetryCalls[0].url}` : ''),
+ );
+ return pass;
+}
+
+console.log('— zauth runtime verification —');
+const st = status();
+console.log('status():', JSON.stringify(st));
+const initOk = st.initialized && st.hasKey;
+console.log(initOk ? '✓ middleware initialized with key' : '✗ middleware did NOT initialize');
+
+const results = [];
+// Paid call: carries an x402 payment header → monitored on ANY path.
+results.push(
+ await runCase({
+ name: 'paid x402 service (X-PAYMENT header) on /api/x402/tutor',
+ req: { url: '/api/x402/tutor', method: 'POST', headers: { 'x-payment': 'eyJ0eXAiOiJ...' } },
+ statusCode: 200,
+ expectMonitored: true,
+ }),
+);
+// 402 challenge on a path the regex covers (no payment header yet).
+results.push(
+ await runCase({
+ name: '402 challenge on /api/mcp (path-matched)',
+ req: { url: '/api/mcp', method: 'POST' },
+ statusCode: 402,
+ expectMonitored: true,
+ }),
+);
+// Unrelated traffic must NOT be reported.
+results.push(
+ await runCase({
+ name: 'unrelated GET /api/agents (must be ignored)',
+ req: { url: '/api/agents?limit=10', method: 'GET' },
+ statusCode: 200,
+ expectMonitored: false,
+ }),
+);
+
+const allPass = initOk && results.every(Boolean);
+console.log('\nRESULT:', allPass ? 'PASS ✓ — telemetry fires for monitored x402 traffic' : 'FAIL ✗');
+process.exitCode = allPass ? 0 : 1;
diff --git a/scripts/verify-zauth.mjs b/scripts/verify-zauth.mjs
new file mode 100644
index 000000000..b5266dda2
--- /dev/null
+++ b/scripts/verify-zauth.mjs
@@ -0,0 +1,123 @@
+// End-to-end verification for the zauthx402 telemetry integration.
+//
+// Drives the REAL @zauthx402/sdk through our Vercel adapter (api/_lib/zauth.js)
+// with a synthetic x402 request, then watches whether the SDK forms and sends a
+// telemetry POST to https://back.zauthx402.com/api/sdk/events.
+//
+// Usage:
+// ZAUTH_API_KEY=zx_live_... node scripts/verify-zauth.mjs
+// node scripts/verify-zauth.mjs # probe with a dummy key
+//
+// A real key should yield HTTP 200 from the events endpoint. A dummy key
+// proves the request is well-formed and reaches zauth (expect 401/403).
+
+import { EventEmitter } from 'node:events';
+
+process.env.ZAUTH_DEBUG = '1';
+if (!process.env.ZAUTH_API_KEY) {
+ process.env.ZAUTH_API_KEY = 'zx_test_verify_dummy_key';
+ console.log('[verify] no ZAUTH_API_KEY set — using dummy key (expect auth rejection from backend)\n');
+}
+
+// Capture the real outbound telemetry POST without mocking the SDK internals.
+const realFetch = globalThis.fetch;
+let telemetry = null;
+globalThis.fetch = async (url, init) => {
+ const u = typeof url === 'string' ? url : url?.url;
+ if (u && u.includes('zauthx402.com')) {
+ telemetry = { url: u, status: null, body: null, headers: init?.headers, payload: init?.body };
+ try {
+ const res = await realFetch(url, init);
+ telemetry.status = res.status;
+ telemetry.body = await res.clone().text().catch(() => '');
+ return res;
+ } catch (err) {
+ telemetry.status = 'NETWORK_ERROR';
+ telemetry.body = err.message;
+ throw err;
+ }
+ }
+ return realFetch(url, init);
+};
+
+const { instrument, drain, status } = await import('../api/_lib/zauth.js');
+
+console.log('[verify] adapter status:', JSON.stringify(status()), '\n');
+
+// Build a Vercel-shaped (raw Node http) req/res for a monitored x402 path.
+function makeReqRes(path) {
+ const req = new EventEmitter();
+ Object.assign(req, {
+ method: 'POST',
+ url: path,
+ headers: {
+ host: 'three.ws',
+ 'x-forwarded-proto': 'https',
+ 'x-forwarded-for': '203.0.113.7',
+ 'content-type': 'application/json',
+ // Simulate an x402 settlement so shouldMonitor() matches on header too.
+ 'x-payment': 'eyJzY2hlbWUiOiJ0ZXN0In0=',
+ },
+ socket: { remoteAddress: '203.0.113.7' },
+ });
+
+ const res = new EventEmitter();
+ const chunks = [];
+ Object.assign(res, {
+ statusCode: 200,
+ headersSent: false,
+ writableEnded: false,
+ _headers: {},
+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this._headers[k.toLowerCase()]; },
+ end(chunk) {
+ if (chunk) chunks.push(chunk);
+ this.headersSent = true;
+ this.writableEnded = true;
+ this.emit('finish');
+ return this;
+ },
+ });
+ return { req, res };
+}
+
+const path = '/api/agents/x402/run';
+const { req, res } = makeReqRes(path);
+
+const monitored = instrument(req, res);
+console.log(`[verify] instrument("${path}") → monitored=${monitored}`);
+console.log(`[verify] shimmed req.path=${req.path} protocol=${req.protocol} ip=${req.ip}`);
+
+// Produce a realistic paid response, then drain so the lambda-style flush lands.
+res.statusCode = 200;
+res.setHeader('content-type', 'application/json');
+res.end(JSON.stringify({ data: { ok: true, result: 'verification probe' } }));
+
+await drain();
+// Give a little extra headroom for the network round-trip in this CLI context.
+await new Promise((r) => setTimeout(r, 1500));
+
+console.log('\n[verify] ---- result ----');
+if (!monitored) {
+ console.log('FAIL: request was not selected for monitoring (shouldMonitor returned false).');
+ process.exit(1);
+}
+if (!telemetry) {
+ console.log('FAIL: SDK never attempted a telemetry POST to zauthx402.com.');
+ process.exit(1);
+}
+console.log(`telemetry POST → ${telemetry.url}`);
+console.log(`HTTP status → ${telemetry.status}`);
+console.log(`response body → ${String(telemetry.body).slice(0, 300)}`);
+const okStatuses = [200, 201, 202];
+if (okStatuses.includes(telemetry.status)) {
+ console.log('\nPASS: telemetry accepted by zauth backend. Integration is live and working.');
+ process.exit(0);
+} else if ([401, 403].includes(telemetry.status)) {
+ console.log('\nPARTIAL PASS: request is well-formed and reached zauth, but the key was rejected.');
+ console.log('Wiring is correct — set a valid ZAUTH_API_KEY from https://zauth.inc/provider-hub to go live.');
+ process.exit(0);
+} else {
+ console.log(`\nWARN: unexpected backend status ${telemetry.status}. Inspect the body above.`);
+ process.exit(2);
+}
diff --git a/src/agent-detail.js b/src/agent-detail.js
index 9c146f2d1..88f195e64 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -26,6 +26,7 @@ const solanaWeb3 = {
};
import { openSwapModal } from './swap-jupiter.js';
import { onchainBadgeEl } from './shared/onchain-badge.js';
+import { openCoinLaunch } from './shared/agent-coin.js';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -207,27 +208,7 @@ function render(agent) {
launchBtn.addEventListener('click', async () => {
launchBtn.disabled = true;
try {
- const { openLaunchTokenModal } = await import('/src/pump/launch-token-modal.js');
- const rec = agent.rawMetadata || {};
- const onchain = rec.onchain || rec.meta?.onchain || null;
- const needsDeploy = !onchain || onchain.family !== 'solana';
- const imageUrl =
- rec.avatar_thumbnail_url || rec.meta?.thumbnail_url || agent.avatar || '';
- openLaunchTokenModal({
- agentId: agent.id,
- agentName: agent.name,
- imageUrl,
- needsDeploy,
- agentForDeploy: needsDeploy
- ? {
- id: agent.id,
- name: rec.name || agent.name,
- description: rec.description || '',
- avatar_id: rec.avatar_id || null,
- skills: rec.skills || undefined,
- }
- : null,
- });
+ await openCoinLaunch(agent);
} finally {
launchBtn.disabled = false;
}
diff --git a/src/dashboard-next/pages/agents.js b/src/dashboard-next/pages/agents.js
index ab3d75450..1efff228b 100644
--- a/src/dashboard-next/pages/agents.js
+++ b/src/dashboard-next/pages/agents.js
@@ -17,6 +17,7 @@ import { requireUser, get, post, put, del, esc, relTime, ApiError } from '../api
import { openAvatarPicker } from '../../avatar-gallery-picker.js';
import { openLaunchTokenModal } from '../../pump/launch-token-modal.js';
import { onchainBadgeHTML } from '../../shared/onchain-badge.js';
+import { coinChipHTML } from '../../shared/agent-coin.js';
const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;
@@ -449,7 +450,7 @@ function agentCard(a, avatars) {
<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:4px">
<span style="font-size:15px;font-weight:600;color:var(--nxt-ink)">${name}</span>
${onchainBadge || `<span class="dn-tag" style="font-size:11px">off-chain</span>`}
- ${pumpMint ? `<span class="dn-tag" style="font-size:11px;background:rgba(168,173,181,0.12);border-color:rgba(168,173,181,0.28);color:#a8adb5">pump.fun</span>` : ''}
+ ${coinChipHTML(a, { launchable: false })}
</div>
${wallet ? `<div style="font-family:${MONO};font-size:12px;color:var(--nxt-ink-fade);margin-bottom:6px">${esc(truncMid(wallet, 8, 6))}</div>` : ''}
<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;font-size:12.5px;color:var(--nxt-ink-dim)">
diff --git a/src/marketplace-detail.js b/src/marketplace-detail.js
index 7b744b88c..bb4333702 100644
--- a/src/marketplace-detail.js
+++ b/src/marketplace-detail.js
@@ -11,6 +11,7 @@
*/
import { onchainBadgeHTML } from './shared/onchain-badge.js';
+import { coinChipHTML } from './shared/agent-coin.js';
const API = '/api';
const $ = (id) => document.getElementById(id);
@@ -305,10 +306,11 @@ function renderCreatorModal(payload, deps) {
// so a nested explorer anchor would double-fire. The explorer link lives
// on the agent detail page this card opens.
const onchain = onchainBadgeHTML(a, { link: false, size: 'sm' });
+ const coin = coinChipHTML(a, { link: false, size: 'sm' });
return `<div class="creator-mini-card" data-agent-id="${escapeHtml(a.id)}">
${thumb}
<div class="name">${escapeHtml(a.name)}</div>
- ${onchain ? `<div class="meta">${onchain}</div>` : ''}
+ ${onchain || coin ? `<div class="meta">${onchain}${coin}</div>` : ''}
<div class="meta">⊙ ${fmtNumber(a.views_count)} · ⑂ ${fmtNumber(a.forks_count)}</div>
</div>`;
}).join('');
diff --git a/src/marketplace.js b/src/marketplace.js
index c7c33aaf9..c771a3a33 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -17,6 +17,7 @@ import {
bindDetailExtras,
} from './marketplace-detail.js';
import { onchainBadgeHTML } from './shared/onchain-badge.js';
+import { coinChipHTML } from './shared/agent-coin.js';
const API = '/api';
@@ -3768,6 +3769,7 @@ function renderCard(a) {
<div class="desc">${escapeHtml(a.description || '')}</div>
<div class="stats">
${onchainBadge}
+ ${coinChipHTML(a)}
<span class="stat-pill">⊙ ${fmtNumber(views)}</span>
<span class="stat-pill">⑂ ${fmtNumber(forks)}</span>
${skillsCount ? `<span class="stat-pill">▤ ${skillsCount}</span>` : ''}
diff --git a/src/shared/agent-coin.js b/src/shared/agent-coin.js
new file mode 100644
index 000000000..db8b7f003
--- /dev/null
+++ b/src/shared/agent-coin.js
@@ -0,0 +1,277 @@
+/**
+ * Single source of truth for the agent "$coin" affordance.
+ *
+ * Every agent on three.ws can have exactly one pump.fun coin. This module
+ * surfaces that one fact consistently wherever an agent is drawn — a card, a
+ * profile, a dashboard row — so the launchpad stops living only inside /studio
+ * and becomes a first-class, one-tap action next to the agent itself.
+ *
+ * Two states, one chip:
+ * - has a coin → a gold "$SYMBOL" pill linking straight to pump.fun (anyone).
+ * - no coin yet → an understated "Launch coin" pill, shown only to the owner,
+ * that opens the existing launch flow (src/pump/launch-token-modal.js).
+ *
+ * The launch pill is deliberately low-emphasis (muted until hover): present
+ * everywhere, but never shouting — visible enough to discover, quiet enough not
+ * to clutter a wall of agents. The coin detail/launch logic lives here once;
+ * callers just drop in `coinChipHTML(agent)` (string sites) or `coinChipEl(agent)`
+ * (element sites), exactly like the on-chain badge.
+ *
+ * Detection piggybacks on getOnchainStatus() (the on-chain badge normalizer) and
+ * additionally accepts the dashboard's `meta.pumpfun.mint` shape.
+ */
+
+import { getOnchainStatus } from './onchain-badge.js';
+
+const STYLE_ID = 'tws-agent-coin-styles';
+
+function esc(s) {
+ return String(s == null ? '' : s).replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+function pumpfunUrl(mint, cluster) {
+ if (!mint) return null;
+ if (cluster === 'devnet') return `https://explorer.solana.com/address/${mint}?cluster=devnet`;
+ return `https://pump.fun/coin/${mint}`;
+}
+
+/**
+ * Normalize any agent record into a coin descriptor, or null when it has no coin.
+ * @returns {null | { mint: string, symbol: string|null, cluster: 'mainnet'|'devnet', url: string|null }}
+ */
+export function getCoinStatus(agent) {
+ if (!agent || typeof agent !== 'object') return null;
+
+ // Prefer the canonical on-chain normalizer — it already resolves the pump.fun
+ // token across every surfaced shape (onchain block, token block, meta.token).
+ const status = getOnchainStatus(agent);
+ if (status && status.isToken && status.address) {
+ const cluster = status.cluster === 'devnet' ? 'devnet' : 'mainnet';
+ return {
+ mint: status.address,
+ symbol: status.tokenSymbol || null,
+ cluster,
+ // Prefer the pump.fun coin page on mainnet — this is a launchpad, not a
+ // block explorer. Fall back to the explorer only when there's no better link.
+ url: status.pumpfunUrl || pumpfunUrl(status.address, cluster) || status.explorerUrl,
+ };
+ }
+
+ // Dashboard / older shapes the badge normalizer doesn't reach: meta.pumpfun.
+ const token = agent.token || agent.meta?.token || agent.meta?.pumpfun || null;
+ const mint = token?.mint || token?.contract_address || token?.ca || null;
+ if (mint) {
+ const cluster = token.cluster === 'devnet' ? 'devnet' : 'mainnet';
+ return {
+ mint,
+ symbol: token.symbol || token.name || null,
+ cluster,
+ url: token.pumpfun_url || pumpfunUrl(mint, cluster),
+ };
+ }
+
+ return null;
+}
+
+/** True when the agent already has a coin. */
+export function hasCoin(agent) {
+ return getCoinStatus(agent) != null;
+}
+
+/**
+ * True when the viewer can launch this agent's coin: it has no coin yet and the
+ * viewer owns it. Ownership is read from the record (`is_owner`/`isOwner`) or
+ * forced by the caller via `opts.owner` on surfaces that only ever render the
+ * owner's own agents (e.g. the dashboard).
+ */
+export function canLaunchCoin(agent, opts = {}) {
+ if (!agent || getCoinStatus(agent)) return false;
+ if (opts.owner === true) return true;
+ return agent.is_owner === true || agent.isOwner === true;
+}
+
+// ── Single launch entry point ───────────────────────────────────────────────
+// One place builds the launch context (image, needsDeploy, deploy fields) and
+// opens the existing modal. Card chips and the agent-detail panel both call it,
+// so the launchpad behaves identically no matter where it's triggered from.
+
+/**
+ * Open the pump.fun launch flow for an agent record (any surfaced shape).
+ * @param {object} agent
+ */
+export async function openCoinLaunch(agent) {
+ if (!agent) return;
+ const rec = agent.rawMetadata || agent;
+ const id = agent.id || rec.id || agent.agent_id || rec.agent_id;
+ if (!id) return;
+
+ const onchain = rec.onchain || rec.meta?.onchain || agent.onchain || null;
+ const needsDeploy = !onchain || onchain.family !== 'solana';
+ const name = rec.name || agent.name || 'Agent';
+ const imageUrl =
+ rec.avatar_thumbnail_url ||
+ rec.meta?.thumbnail_url ||
+ agent.thumbnail_url ||
+ agent.avatar ||
+ agent.image ||
+ '';
+
+ const { openLaunchTokenModal } = await import('/src/pump/launch-token-modal.js');
+ openLaunchTokenModal({
+ agentId: id,
+ agentName: name,
+ imageUrl,
+ needsDeploy,
+ agentForDeploy: needsDeploy
+ ? {
+ id,
+ name,
+ description: rec.description || agent.description || '',
+ avatar_id: rec.avatar_id || agent.avatar_id || null,
+ skills: rec.skills || agent.skills || undefined,
+ }
+ : null,
+ });
+}
+
+// ── Delegated launch handler ────────────────────────────────────────────────
+// String-render sites (innerHTML) can't attach listeners, so the launch pill is
+// a plain `[data-tws-coin-launch]` button and one capture-phase document listener
+// drives it. Capture phase + stopPropagation means clicking the pill never
+// triggers the surrounding card's navigation.
+
+const _launchCtx = new Map();
+let _delegated = false;
+
+function _ensureDelegate() {
+ if (_delegated || typeof document === 'undefined') return;
+ _delegated = true;
+ document.addEventListener(
+ 'click',
+ (e) => {
+ const btn = e.target?.closest?.('[data-tws-coin-launch]');
+ if (!btn) return;
+ e.preventDefault();
+ e.stopPropagation();
+ if (btn.disabled) return;
+ const id = btn.getAttribute('data-tws-coin-launch');
+ const agent = _launchCtx.get(String(id)) || { id };
+ btn.disabled = true;
+ Promise.resolve(openCoinLaunch(agent)).finally(() => {
+ btn.disabled = false;
+ });
+ },
+ true,
+ );
+}
+
+function _registerLaunchCtx(id, agent) {
+ if (!id) return;
+ _launchCtx.set(String(id), agent);
+ _ensureDelegate();
+}
+
+/** Inject the shared coin stylesheet once. Idempotent and SSR-safe. */
+export function ensureCoinStyles() {
+ if (typeof document === 'undefined') return;
+ if (document.getElementById(STYLE_ID)) return;
+ const style = document.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = `
+.tws-coin{display:inline-flex;align-items:center;gap:6px;padding:3px 9px;border-radius:999px;
+ font:600 11px/1 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;letter-spacing:.01em;
+ white-space:nowrap;vertical-align:middle;text-decoration:none;cursor:pointer;
+ border:1px solid transparent;background:transparent;font-family:inherit;
+ transition:background .15s ease,border-color .15s ease,transform .15s ease,color .15s ease;}
+.tws-coin-glyph{flex:none;font-size:12px;line-height:1;}
+.tws-coin-label{overflow:hidden;text-overflow:ellipsis;}
+.tws-coin--md{padding:4px 11px;font-size:12px;gap:7px;}
+.tws-coin--md .tws-coin-glyph{font-size:13px;}
+/* Live coin — a real, tradable thing: gold, confident, links to pump.fun. */
+.tws-coin--live{color:#eab308;background:rgba(234,179,8,.12);border-color:rgba(234,179,8,.34);}
+a.tws-coin--live:hover{background:rgba(234,179,8,.2);border-color:rgba(234,179,8,.6);transform:translateY(-1px);}
+a.tws-coin--live:active{transform:translateY(0);}
+.tws-coin--live:focus-visible{outline:2px solid rgba(234,179,8,.7);outline-offset:2px;}
+/* Launch action — understated by default so a wall of agents never reads as a
+ wall of buttons. Reveals its gold identity only on hover/focus. */
+.tws-coin--launch{color:rgba(235,236,240,.5);background:rgba(255,255,255,.035);border-color:rgba(255,255,255,.13);}
+.tws-coin--launch .tws-coin-glyph{font-weight:700;}
+.tws-coin--launch:hover{color:#eab308;background:rgba(234,179,8,.12);border-color:rgba(234,179,8,.42);transform:translateY(-1px);}
+.tws-coin--launch:active{transform:translateY(0);}
+.tws-coin--launch:focus-visible{outline:2px solid rgba(234,179,8,.6);outline-offset:2px;}
+.tws-coin--launch:disabled{opacity:.55;cursor:progress;transform:none;}
+@media (prefers-reduced-motion: reduce){.tws-coin{transition:none;}}
+`;
+ (document.head || document.documentElement).appendChild(style);
+}
+
+/**
+ * Render the coin chip as an HTML string. Returns '' when there's nothing to show
+ * (no coin and the viewer can't launch one).
+ *
+ * @param {object} agent
+ * @param {object} [opts]
+ * @param {'sm'|'md'} [opts.size='sm']
+ * @param {boolean} [opts.owner=false] Force owner context (owner-only surfaces).
+ * @param {boolean} [opts.link=true] Link the live coin to pump.fun. Pass false
+ * inside a fully-clickable card so the chip is a plain (non-anchor) indicator.
+ * @param {boolean} [opts.launchable=true] Render the owner "Launch coin" pill.
+ * Pass false on a surface that already has its own launch control, so the chip
+ * stays a pure coin indicator and never duplicates the launch entry point.
+ * @param {string} [opts.launchLabel='Launch coin']
+ */
+export function coinChipHTML(agent, opts = {}) {
+ const { size = 'sm', owner = false, link = true, launchable = true, launchLabel = 'Launch coin' } = opts;
+ const sz = size === 'md' ? ' tws-coin--md' : '';
+ const coin = getCoinStatus(agent);
+
+ if (coin) {
+ ensureCoinStyles();
+ const sym = coin.symbol ? `$${esc(coin.symbol)}` : 'Coin';
+ const aria = `Trade ${coin.symbol ? coin.symbol + ' ' : ''}coin on pump.fun`;
+ const inner = `<span class="tws-coin-glyph" aria-hidden="true">◎</span><span class="tws-coin-label">${sym}</span>`;
+ if (link && coin.url) {
+ return `<a class="tws-coin tws-coin--live${sz}" href="${esc(coin.url)}" target="_blank" rel="noopener noreferrer" title="${esc(aria)}" aria-label="${esc(aria)}">${inner}</a>`;
+ }
+ return `<span class="tws-coin tws-coin--live${sz}" role="img" aria-label="${esc(aria)}">${inner}</span>`;
+ }
+
+ if (!launchable || !canLaunchCoin(agent, { owner })) return '';
+ ensureCoinStyles();
+ const id = agent?.id || agent?.rawMetadata?.id || '';
+ if (!id) return '';
+ _registerLaunchCtx(id, agent);
+ return `<button type="button" class="tws-coin tws-coin--launch${sz}" data-tws-coin-launch="${esc(id)}" title="Launch this agent's coin on pump.fun" aria-label="Launch this agent's coin on pump.fun"><span class="tws-coin-glyph" aria-hidden="true">+</span><span class="tws-coin-label">${esc(launchLabel)}</span></button>`;
+}
+
+/**
+ * Render the coin chip as a DOM node, or null when there's nothing to show.
+ * Launch buttons are driven by the shared delegated listener; coin links get a
+ * local stopPropagation so they don't trigger an enclosing clickable card.
+ */
+export function coinChipEl(agent, opts = {}) {
+ const html = coinChipHTML(agent, opts);
+ if (!html) return null;
+ const tpl = document.createElement('template');
+ tpl.innerHTML = html.trim();
+ const node = tpl.content.firstElementChild;
+ if (node && node.tagName === 'A') {
+ node.addEventListener('click', (e) => e.stopPropagation());
+ }
+ return node;
+}
+
+if (typeof window !== 'undefined') {
+ window.twsAgentCoin = {
+ getCoinStatus,
+ hasCoin,
+ canLaunchCoin,
+ openCoinLaunch,
+ coinChipHTML,
+ coinChipEl,
+ ensureCoinStyles,
+ };
+}