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(x402-revenue): name the settlement chain instead of leaking its CAIP-2 id

nirholas273e166789cb
diff --git a/api/_lib/x402/revenue-networks.js b/api/_lib/x402/revenue-networks.js
new file mode 100644
index 000000000..c3427af3e
--- /dev/null
+++ b/api/_lib/x402/revenue-networks.js
@@ -0,0 +1,197 @@
+// Network identity for the revenue ledger (x402_audit_log.network).
+//
+// Settlements record their chain as a CAIP-2 id: 'solana:5eykt4Us…' for the
+// Solana rail, 'eip155:8453' for Base, and so on. Two things need that raw id
+// turned into something usable:
+//
+// 1. Display. 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' is not a label a
+// reader should ever see. `networkIdentity()` folds it to a stable family
+// slug ('solana') plus a human label ('Solana').
+// 2. Filtering. A visitor filters by family ('?network=solana'), not by
+// genesis hash, and older rows were written with the bare legacy name
+// ('solana', 'base'). `resolveNetworkFilter()` maps one family slug to
+// every raw id that belongs to it, so a filter matches both spellings.
+//
+// The explorer link is derived from the same identity: a Base settlement's tx
+// hash on solscan.io is a dead link, so `revenueTxUrl()` routes each family to
+// its own explorer and returns null rather than guessing.
+
+import { CHAIN_BY_ID } from '../erc8004-chains.js';
+
+// Families we name explicitly. `ids` lists every raw value the ledger may hold
+// for that family: the canonical CAIP-2 id first, then legacy spellings. The
+// table is the single source of truth for both directions (id → family and
+// family → ids), so display and filtering can never disagree.
+const FAMILIES = [
+ {
+ family: 'solana',
+ label: 'Solana',
+ ids: ['solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', 'solana:mainnet', 'solana', 'mainnet'],
+ },
+ {
+ family: 'solana-devnet',
+ label: 'Solana devnet',
+ cluster: 'devnet',
+ ids: ['solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1', 'solana:devnet', 'devnet'],
+ },
+ {
+ family: 'solana-testnet',
+ label: 'Solana testnet',
+ cluster: 'testnet',
+ ids: ['solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z', 'solana:testnet'],
+ },
+ { family: 'base', label: 'Base', chainId: 8453, ids: ['eip155:8453', 'base'] },
+ {
+ family: 'base-sepolia',
+ label: 'Base Sepolia',
+ chainId: 84532,
+ ids: ['eip155:84532', 'base-sepolia'],
+ },
+ { family: 'bsc', label: 'BNB Chain', chainId: 56, ids: ['eip155:56', 'bsc', 'bnb'] },
+ { family: 'ethereum', label: 'Ethereum', chainId: 1, ids: ['eip155:1', 'ethereum'] },
+ { family: 'arbitrum', label: 'Arbitrum One', chainId: 42161, ids: ['eip155:42161', 'arbitrum'] },
+ { family: 'optimism', label: 'Optimism', chainId: 10, ids: ['eip155:10', 'optimism'] },
+ { family: 'polygon', label: 'Polygon', chainId: 137, ids: ['eip155:137', 'polygon'] },
+ { family: 'xlayer', label: 'X Layer', chainId: 196, ids: ['eip155:196', 'xlayer', 'x-layer'] },
+];
+
+const BY_ID = new Map();
+for (const f of FAMILIES) for (const id of f.ids) BY_ID.set(id.toLowerCase(), f);
+
+const BY_FAMILY = new Map(FAMILIES.map((f) => [f.family, f]));
+
+const UNKNOWN = { family: 'unknown', label: 'Unknown network', cluster: null, chainId: null };
+
+const EVM_TX_RE = /^0x[0-9a-f]{64}$/i;
+
+/**
+ * Fold a raw ledger network value into a stable family slug plus a display label.
+ * Unrecognised CAIP-2 ids still resolve: an `eip155:<id>` borrows its name from
+ * the chain table, and any other `solana:<ref>` reads as Solana.
+ *
+ * @param {string|null|undefined} raw
+ * @returns {{ id: string|null, family: string, label: string, cluster: string|null, chainId: number|null }}
+ */
+export function networkIdentity(raw) {
+ const id = typeof raw === 'string' ? raw.trim() : '';
+ if (!id) return { id: null, ...UNKNOWN };
+
+ const known = BY_ID.get(id.toLowerCase());
+ if (known) {
+ return {
+ id,
+ family: known.family,
+ label: known.label,
+ cluster: known.cluster || null,
+ chainId: known.chainId || null,
+ };
+ }
+
+ const evm = /^eip155:(\d{1,9})$/i.exec(id);
+ if (evm) {
+ const chainId = Number(evm[1]);
+ const chain = CHAIN_BY_ID[chainId];
+ return {
+ id,
+ family: `eip155-${chainId}`,
+ label: chain?.name || `EVM chain ${chainId}`,
+ cluster: null,
+ chainId,
+ };
+ }
+
+ // Any other Solana reference (a cluster we have not named) is still Solana.
+ if (/^solana:/i.test(id)) {
+ return { id, family: 'solana', label: 'Solana', cluster: null, chainId: null };
+ }
+
+ return { id, ...UNKNOWN };
+}
+
+/** Display label for a raw ledger network value. */
+export function networkLabel(raw) {
+ return networkIdentity(raw).label;
+}
+
+/**
+ * Turn a caller-supplied `?network=` value into the set of raw ledger ids it
+ * selects. Accepts a family slug ('solana', 'base'), a legacy bare name, or a
+ * full CAIP-2 id, so a deep link built from any of them resolves to the same
+ * rows. Returns null when the value names no network we can match, which callers
+ * treat as "no filter" rather than "match nothing".
+ *
+ * @param {string|null|undefined} input
+ * @returns {{ family: string, ids: string[] }|null}
+ */
+export function resolveNetworkFilter(input) {
+ const v = typeof input === 'string' ? input.trim().toLowerCase() : '';
+ if (!v) return null;
+
+ const direct = BY_FAMILY.get(v);
+ if (direct) return { family: direct.family, ids: [...direct.ids] };
+
+ const byId = BY_ID.get(v);
+ if (byId) return { family: byId.family, ids: [...byId.ids] };
+
+ const evm = /^(?:eip155-|eip155:)(\d{1,9})$/.exec(v);
+ if (evm) return { family: `eip155-${evm[1]}`, ids: [`eip155:${evm[1]}`] };
+
+ return null;
+}
+
+/**
+ * Explorer URL for a settlement transaction on its own chain. Returns null when
+ * the chain has no explorer we know, so the UI renders no link instead of one
+ * that lands on the wrong chain's 404.
+ *
+ * @param {string|null|undefined} hash
+ * @param {string|null|undefined} raw network id from the ledger
+ * @returns {string|null}
+ */
+export function revenueTxUrl(hash, raw) {
+ const sig = typeof hash === 'string' ? hash.trim() : '';
+ if (!sig) return null;
+ const net = networkIdentity(raw);
+
+ if (net.chainId) {
+ const explorer = CHAIN_BY_ID[net.chainId]?.explorer;
+ return explorer ? `${explorer}/tx/${sig}` : null;
+ }
+ if (net.family.startsWith('solana')) {
+ return `https://solscan.io/tx/${sig}${net.cluster ? `?cluster=${net.cluster}` : ''}`;
+ }
+ if (net.family.startsWith('eip155-')) return null;
+
+ // Unknown network: the signature shape still tells the two rails apart, and
+ // only Solana can be resolved without a chain id.
+ return EVM_TX_RE.test(sig) ? null : `https://solscan.io/tx/${sig}`;
+}
+
+/**
+ * Collapse per-raw-id revenue rows into one row per family, so the UI shows
+ * "Solana" once instead of a genesis hash per cluster spelling. Rows keep the
+ * raw ids they folded in (`caip`) for anyone reconciling against the ledger.
+ *
+ * @param {Array<{network: string|null, count: number, gross_usd: number}>} rows
+ * @returns {Array<{network: string, label: string, count: number, gross_usd: number, caip: string[]}>}
+ */
+export function foldNetworkRows(rows) {
+ const byFamily = new Map();
+ for (const r of rows || []) {
+ const net = networkIdentity(r.network);
+ const cur = byFamily.get(net.family) || {
+ network: net.family,
+ label: net.label,
+ count: 0,
+ gross_usd: 0,
+ caip: [],
+ };
+ cur.count += Number(r.count) || 0;
+ cur.gross_usd += Number(r.gross_usd) || 0;
+ if (r.network && !cur.caip.includes(r.network)) cur.caip.push(r.network);
+ byFamily.set(net.family, cur);
+ }
+ return [...byFamily.values()]
+ .map((r) => ({ ...r, gross_usd: Number(r.gross_usd.toFixed(6)) }))
+ .sort((a, b) => b.gross_usd - a.gross_usd || b.count - a.count);
+}
diff --git a/api/x402-revenue.js b/api/x402-revenue.js
index b7f3c0c1a..f85b077b7 100644
--- a/api/x402-revenue.js
+++ b/api/x402-revenue.js
@@ -27,9 +27,14 @@ import { sql, isDbUnavailableError } from './_lib/db.js';
import { cors, json, method, error, serverError, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { cacheGet, cacheSet } from './_lib/cache.js';
-import { explorerTxUrl } from './_lib/avatar-wallet.js';
import { atomicsToUsdc } from './_lib/agent-paid-services.js';
import { buildRevenueReport, resolvePeriod } from './_lib/x402/revenue-analytics.js';
+import {
+ networkIdentity,
+ resolveNetworkFilter,
+ revenueTxUrl,
+ foldNetworkRows,
+} from './_lib/x402/revenue-networks.js';
const STATS_TTL_S = 30;
const FEED_TTL_S = 8;
@@ -57,25 +62,31 @@ function routeForEndpoint(slug) {
return clean ? `/api/x402/${clean}` : null;
}
-function normNetwork(n) {
- if (!n) return null;
- const v = String(n).trim().toLowerCase();
- return ['solana', 'base', 'bsc', 'devnet', 'mainnet'].includes(v) ? v : null;
+// A `?network=` value → the raw ledger ids it selects, as a comma-joined string
+// bound once and expanded in SQL. The ledger holds CAIP-2 ids ('solana:5eykt4Us…',
+// 'eip155:8453') while callers filter by family ('solana', 'base'), so comparing
+// the two directly matches nothing; see _lib/x402/revenue-networks.js.
+function networkFilterIds(n) {
+ const f = resolveNetworkFilter(n);
+ return f ? f.ids.join(',') : null;
}
// Shape a settled-payment row into a privacy-safe public event.
function shapeSettlement(r) {
const atomics = /^[0-9]+$/.test(String(r.amount_atomics || '')) ? Number(r.amount_atomics) : 0;
const net = r.network || null;
+ const identity = networkIdentity(net);
return {
id: r.id,
route: r.route || 'unknown',
network: net,
+ network_family: identity.family,
+ network_label: identity.label,
amount_usd: atomicsToUsdc(atomics),
asset: r.asset || 'USDC',
payer: shortAddr(r.payer),
tx: r.tx_hash || null,
- tx_url: r.tx_hash ? explorerTxUrl(r.tx_hash, net) : null,
+ tx_url: revenueTxUrl(r.tx_hash, net),
ts: r.created_at instanceof Date ? r.created_at.toISOString() : r.created_at,
};
}
@@ -121,10 +132,11 @@ async function revenueSeries(period) {
};
}
-// Revenue split by settlement network.
+// Revenue split by settlement network, folded to one row per chain family so the
+// UI names "Solana" rather than the genesis hash the ledger stores.
async function revenueByNetwork(since) {
const rows = await sql`
- SELECT coalesce(network, 'unknown') AS network,
+ SELECT network,
count(*)::int AS count,
coalesce(sum(CASE WHEN amount_atomics ~ '^[0-9]+$' THEN amount_atomics::numeric ELSE 0 END), 0) AS gross_atomics
FROM x402_audit_log
@@ -133,11 +145,13 @@ async function revenueByNetwork(since) {
GROUP BY network
ORDER BY gross_atomics DESC
`;
- return rows.map((r) => ({
- network: r.network,
- count: r.count,
- gross_usd: atomicsToUsdc(Number(r.gross_atomics || 0)),
- }));
+ return foldNetworkRows(
+ rows.map((r) => ({
+ network: r.network,
+ count: r.count,
+ gross_usd: atomicsToUsdc(Number(r.gross_atomics || 0)),
+ })),
+ );
}
// Momentum: this window's gross vs the immediately-preceding equal window, plus a
@@ -179,7 +193,7 @@ async function handleStats(period) {
async function handleFeed({ since, cursor, limit, endpoint, network }) {
const route = routeForEndpoint(endpoint);
- const net = normNetwork(network);
+ const netIds = networkFilterIds(network);
const rows = await sql`
SELECT id, route, network, amount_atomics, asset, tx_hash, payer, created_at
FROM x402_audit_log
@@ -187,7 +201,7 @@ async function handleFeed({ since, cursor, limit, endpoint, network }) {
AND (${since}::timestamptz IS NULL OR created_at > ${since}::timestamptz)
AND (${cursor}::timestamptz IS NULL OR created_at < ${cursor}::timestamptz)
AND (${route}::text IS NULL OR route = ${route})
- AND (${net}::text IS NULL OR network = ${net})
+ AND (${netIds}::text IS NULL OR network = ANY(string_to_array(${netIds}::text, ',')))
ORDER BY created_at DESC
LIMIT ${limit}
`;
@@ -202,7 +216,10 @@ async function handleFeed({ since, cursor, limit, endpoint, network }) {
events,
count: events.length,
next_cursor: events.length === limit ? nextCursor : null,
- filter: { endpoint: route ? endpoint : null, network: net },
+ filter: {
+ endpoint: route ? endpoint : null,
+ network: resolveNetworkFilter(network)?.family || null,
+ },
};
}
@@ -210,28 +227,30 @@ async function handleFeed({ since, cursor, limit, endpoint, network }) {
async function handleExport(res, { period, endpoint, network }) {
const { since } = resolvePeriod(period);
const route = routeForEndpoint(endpoint);
- const net = normNetwork(network);
+ const netIds = networkFilterIds(network);
const rows = await sql`
SELECT route, network, amount_atomics, asset, tx_hash, payer, created_at
FROM x402_audit_log
WHERE event_type = 'payment_settled'
AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)
AND (${route}::text IS NULL OR route = ${route})
- AND (${net}::text IS NULL OR network = ${net})
+ AND (${netIds}::text IS NULL OR network = ANY(string_to_array(${netIds}::text, ',')))
ORDER BY created_at DESC
LIMIT ${EXPORT_MAX_ROWS}
`;
- const header = 'timestamp,endpoint,network,amount_usd,asset,payer,tx_hash\n';
+ const header = 'timestamp,endpoint,network,chain,amount_usd,asset,payer,tx_hash,tx_url\n';
const csv = rows.reduce((acc, r) => {
const ev = shapeSettlement(r);
const cells = [
ev.ts,
ev.route,
ev.network || '',
+ ev.network_label,
ev.amount_usd,
ev.asset,
r.payer || '',
ev.tx || '',
+ ev.tx_url || '',
].map((c) => {
const s = String(c ?? '');
return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
@@ -289,7 +308,7 @@ export default async function handler(req, res) {
}
// Filtered feeds and older pages: a short cache smooths the live-poll cadence.
- const filterKey = `${routeForEndpoint(endpoint) || 'all'}:${normNetwork(network) || 'all'}`;
+ const filterKey = `${routeForEndpoint(endpoint) || 'all'}:${resolveNetworkFilter(network)?.family || 'all'}`;
const cacheKey = `x402rev:feed:${cursor || 'head'}:${limit}:${filterKey}`;
let body = await cacheGet(cacheKey);
if (body === null) {
diff --git a/src/x402-revenue.js b/src/x402-revenue.js
index 7efebdf93..66c912009 100644
--- a/src/x402-revenue.js
+++ b/src/x402-revenue.js
@@ -18,14 +18,17 @@ import { timeAgo } from './shared/pulse-format.js';
const POLL_MS = 12_000; // live delta cadence when visible
const STATS_REFRESH_MS = 60_000;
const PERIODS = ['24h', '7d', '30d', 'all'];
-const NETWORKS = ['solana', 'base', 'bsc'];
+// Chain families the API filters by ('solana', 'base', 'eip155-8453', …). The
+// ledger stores CAIP-2 ids; the API folds them to these slugs, so the page never
+// needs a hardcoded chain list — it validates the shape and lets the API decide.
+const NETWORK_SLUG_RE = /^[a-z0-9][a-z0-9-]{1,31}$/;
const $ = (id) => document.getElementById(id);
const state = {
period: '24h',
endpoint: null, // slug feed filter
- network: null, // network feed filter
+ network: null, // chain-family feed filter
query: '', // client-side search
paused: false,
sound: false,
@@ -35,6 +38,8 @@ const state = {
pollTimer: null,
statsTimer: null,
firstChart: true,
+ hasStats: false, // a successful stats render has landed at least once
+ hasFeed: false, // the feed has rendered rows or an honest empty state
};
// ── formatters ───────────────────────────────────────────────────────────────
@@ -76,8 +81,8 @@ function readUrl() {
if (PERIODS.includes(per)) state.period = per;
const ep = (p.get('endpoint') || '').replace(/[^a-z0-9-]/gi, '');
if (ep) state.endpoint = ep;
- const net = (p.get('network') || '').toLowerCase();
- if (NETWORKS.includes(net)) state.network = net;
+ const net = (p.get('network') || '').trim().toLowerCase();
+ if (NETWORK_SLUG_RE.test(net)) state.network = net;
}
function writeUrl() {
const p = new URLSearchParams();
@@ -123,23 +128,92 @@ function setCounter(id, value, format) {
}
async function loadStats() {
- let res;
+ let data = null;
+ let reason = '';
try {
- res = await fetch(
+ const res = await fetch(
`/api/x402-revenue?view=stats&period=${encodeURIComponent(state.period)}`,
{
headers: { accept: 'application/json' },
},
);
+ if (res.ok) ({ data } = await res.json());
+ else
+ reason =
+ res.status === 503
+ ? 'The revenue ledger is temporarily unavailable.'
+ : `The revenue service answered ${res.status}.`;
} catch {
- return; // transient blip — keep last-known
+ reason = 'The revenue service could not be reached.';
}
- if (!res.ok) return;
- const { data } = await res.json();
- if (!data) return;
+ if (!data) {
+ // A blip after a good render keeps the last-known numbers (they are still
+ // true, just ageing); a failure before any render has nothing to show, so
+ // the page says so and offers the retry instead of sitting on em-dashes.
+ if (state.hasStats) markStale();
+ else renderStatsError(reason || 'Revenue data is unavailable right now.');
+ return;
+ }
+ state.hasStats = true;
renderStats(data);
const u = $('xr-updated');
- if (u) u.textContent = `updated ${timeAgo(new Date().toISOString())}`;
+ if (u) {
+ u.dataset.state = 'ok';
+ u.textContent = `updated ${timeAgo(new Date().toISOString())}`;
+ }
+}
+
+// A degraded-but-not-empty signal: the numbers on screen are the last good ones.
+function markStale() {
+ const u = $('xr-updated');
+ if (!u) return;
+ u.dataset.state = 'stale';
+ u.textContent = 'reconnecting to the revenue ledger…';
+}
+
+// Nothing has ever loaded: replace every data region with one honest, actionable
+// explanation rather than leaving placeholder dashes and a spinner forever.
+function renderStatsError(reason) {
+ const u = $('xr-updated');
+ if (u) {
+ u.dataset.state = 'error';
+ u.textContent = 'revenue data unavailable';
+ }
+ const chartHost = $('xr-chart');
+ if (chartHost) chartHost.innerHTML = '';
+ const empty = $('xr-chart-empty');
+ if (empty) {
+ empty.hidden = false;
+ empty.textContent = reason;
+ }
+ for (const id of ['xr-top', 'xr-networks']) {
+ const host = $(id);
+ if (host) host.innerHTML = `<p class="xr-empty">${esc(reason)}</p>`;
+ }
+ const chips = $('xr-chips');
+ if (chips) chips.innerHTML = '';
+ mountRetry('xr-stats-retry', $('xr-top'), () => {
+ loadStats();
+ if (!state.hasFeed) loadInitialFeed();
+ });
+}
+
+// One retry affordance, reused by the stats and feed error states. Replaces any
+// previous instance so repeated failures never stack up buttons.
+function mountRetry(id, host, onRetry) {
+ if (!host) return;
+ document.getElementById(id)?.remove();
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.id = id;
+ btn.className = 'xr-retry';
+ btn.textContent = 'Try again';
+ btn.addEventListener('click', () => {
+ btn.disabled = true;
+ btn.textContent = 'Retrying…';
+ onRetry();
+ });
+ host.appendChild(btn);
}
function renderStats(d) {
@@ -229,6 +303,8 @@ function renderTopEndpoints(rows) {
}
}
+// The rail rows double as the network filter: clicking one scopes the feed to
+// that chain, the same toggle the chips above the feed drive.
function renderNetworks(rows) {
const host = $('xr-networks');
if (!host) return;
@@ -242,15 +318,29 @@ function renderNetworks(rows) {
.map((r) => {
const g = Number(r.gross_usd) || 0;
const pct = max > 0 ? Math.max(3, Math.round((g / max) * 100)) : 3;
+ const slug = r.network || 'unknown';
+ const label = r.label || slug;
+ const active = state.network === slug ? ' active' : '';
return (
- `<div class="xr-net-row">` +
- `<span class="xr-net-name">${esc(r.network)}</span>` +
+ `<div class="xr-net-row${active}" role="button" tabindex="0" data-network="${esc(slug)}" ` +
+ `aria-label="Filter feed to ${esc(label)}">` +
+ `<span class="xr-net-name">${esc(label)}</span>` +
`<span class="xr-net-track"><span class="xr-net-fill" style="width:${pct}%"></span></span>` +
- `<span class="xr-net-val">${fmtUsd(g)}</span>` +
+ `<span class="xr-net-val">${fmtUsd(g)}<small>${fmtInt(r.count)} call${r.count === 1 ? '' : 's'}</small></span>` +
`</div>`
);
})
.join('');
+ for (const el of host.querySelectorAll('[data-network]')) {
+ const slug = el.dataset.network;
+ el.addEventListener('click', () => toggleNetwork(slug));
+ el.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ toggleNetwork(slug);
+ }
+ });
+ }
}
// ── SVG area chart ────────────────────────────────────────────────────────────
@@ -302,7 +392,10 @@ function renderChart(series) {
const hasData = points.some((p) => p.gross_usd > 0);
if (!points.length || !hasData) {
host.innerHTML = '';
- if (empty) empty.hidden = false;
+ if (empty) {
+ empty.textContent = 'No revenue in this window yet.';
+ empty.hidden = false;
+ }
host._points = null;
return;
}
@@ -407,10 +500,10 @@ function renderChips(topEndpoints, networks) {
);
}
for (const r of networks.filter((nr) => Number(nr.count) > 0).slice(0, 4)) {
- if (!NETWORKS.includes(r.network)) continue;
+ if (!r.network || r.network === 'unknown') continue;
const active = state.network === r.network ? ' active' : '';
chips.push(
- `<button type="button" class="xr-chip${active}" data-network="${esc(r.network)}">${esc(r.network)}</button>`,
+ `<button type="button" class="xr-chip${active}" data-network="${esc(r.network)}">${esc(r.label || r.network)}</button>`,
);
}
host.innerHTML = chips.join('');
@@ -461,8 +554,14 @@ function setFeedState(s) {
: 'connecting…';
}
+// The chain a row settled on reads as its family name ('Solana'), but the raw
+// CAIP-2 id stays searchable so a ledger reconciliation can find it by id.
+function networkName(e) {
+ return e.network_label || e.network_family || e.network || '';
+}
+
function searchText(e) {
- return `${endpointLabel(e.route)} ${e.payer || ''} ${e.tx || ''} ${e.network || ''}`.toLowerCase();
+ return `${endpointLabel(e.route)} ${e.payer || ''} ${e.tx || ''} ${e.network || ''} ${networkName(e)}`.toLowerCase();
}
function rowHTML(e) {
@@ -473,10 +572,13 @@ function rowHTML(e) {
const payer = e.payer
? `<span class="xr-row-payer" title="payer wallet">${esc(e.payer)}</span>`
: '';
- const net = e.network ? `<span class="xr-row-net">${esc(e.network)}</span>` : '';
+ const chain = networkName(e);
+ const net = chain
+ ? `<span class="xr-row-net" title="${esc(e.network || chain)}">${esc(chain)}</span>`
+ : '';
const hidden = state.query && !searchText(e).includes(state.query) ? ' hidden' : '';
return (
- `<div class="xr-row${hidden}" data-id="${esc(e.id)}" data-tx="${esc(e.tx || '')}" data-search="${esc(searchText(e))}" role="button" tabindex="0" aria-label="${esc(label)} settled ${esc(e.amount_usd)} — click to copy tx">` +
+ `<div class="xr-row${hidden}" data-id="${esc(e.id)}" data-tx="${esc(e.tx || '')}" data-search="${esc(searchText(e))}" role="button" tabindex="0" aria-label="${esc(label)} settled ${fmtUsd(e.amount_usd)} on ${esc(chain || 'chain')}. Activate to copy the transaction signature.">` +
`<span class="xr-row-glyph" aria-hidden="true">→</span>` +
`<span class="xr-row-body">` +
`<span class="xr-row-line"><span class="xr-row-ep">${esc(label)}</span> ${payer}</span>` +
@@ -487,19 +589,43 @@ function rowHTML(e) {
);
}
+// Clipboard access is denied in plenty of real contexts (an insecure origin, a
+// denied permission prompt). Fall back to a selection-based copy so the click
+// still does what the row promises instead of dead-ending in a toast.
+function copyText(text) {
+ if (navigator.clipboard?.writeText) {
+ return navigator.clipboard.writeText(text).catch(() => legacyCopy(text));
+ }
+ return legacyCopy(text);
+}
+
+function legacyCopy(text) {
+ const ta = document.createElement('textarea');
+ ta.value = text;
+ ta.setAttribute('readonly', '');
+ ta.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none';
+ document.body.appendChild(ta);
+ ta.select();
+ const ok = document.execCommand?.('copy');
+ ta.remove();
+ return ok ? Promise.resolve() : Promise.reject(new Error('copy unavailable'));
+}
+
function wireRow(node) {
node.addEventListener('click', (e) => {
if (e.target.closest('.xr-row-tx')) return; // let the explorer link work
const tx = node.dataset.tx;
- if (tx && navigator.clipboard) {
- navigator.clipboard.writeText(tx).then(
- () => toast('Transaction signature copied'),
- () => toast(tx.slice(0, 16) + '…'),
- );
- }
+ if (!tx) return;
+ copyText(tx).then(
+ () => toast('Transaction signature copied'),
+ () => toast('Copy blocked by the browser. Open the tx link instead.'),
+ );
});
node.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') node.click();
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ node.click();
+ }
});
}
@@ -525,15 +651,33 @@ function renderInitialFeed(events) {
`</div>`;
setFeedState('empty');
state.latestTs = null;
+ state.hasFeed = true;
return;
}
host.innerHTML = events.map(rowHTML).join('');
for (const node of host.querySelectorAll('.xr-row')) wireRow(node);
for (const e of events) state.seen.add(e.id);
state.latestTs = events[0].ts;
+ state.hasFeed = true;
setFeedState(state.paused ? 'paused' : 'live');
}
+// The feed could not be read at all. Say what happened, keep the filter escape
+// hatch reachable, and offer the retry — never leave skeletons pulsing forever.
+function renderFeedError(reason) {
+ const host = $('xr-feed');
+ if (!host) return;
+ setFeedState('error');
+ host.innerHTML =
+ `<div class="xr-feed-empty xr-feed-empty--error" role="alert">` +
+ `<p class="xr-feed-empty-h">Live settlements are unavailable.</p>` +
+ `<p class="xr-feed-empty-p">${esc(reason)} Nothing is lost: every settlement stays in the ledger and the feed refills the moment the service answers.</p>` +
+ `</div>`;
+ mountRetry('xr-feed-retry', host.querySelector('.xr-feed-empty'), () => loadInitialFeed());
+ const more = $('xr-more');
+ if (more) more.hidden = true;
+}
+
function prependEvents(events) {
const host = $('xr-feed');
if (!host) return;
@@ -556,26 +700,37 @@ function prependEvents(events) {
for (let i = 240; i < rows.length; i++) rows[i].remove();
}
-async function loadInitialFeed() {
- setFeedState('loading');
- showSkeleton();
+// `background` re-reads the head of the feed without tearing the current view
+// down: the 12s poll on a quiet (empty) feed used to flash six skeletons over
+// the empty state every cycle.
+async function loadInitialFeed({ background = false } = {}) {
+ if (!background) {
+ setFeedState('loading');
+ showSkeleton();
+ }
state.seen.clear();
- let res;
+ let data = null;
+ let reason = '';
try {
- res = await fetch(`/api/x402-revenue?view=feed&limit=30&${feedParams()}`, {
+ const res = await fetch(`/api/x402-revenue?view=feed&limit=30&${feedParams()}`, {
headers: { accept: 'application/json' },
});
+ if (res.ok) ({ data } = await res.json());
+ else
+ reason =
+ res.status === 503
+ ? 'The revenue ledger is temporarily unavailable.'
+ : `The revenue service answered ${res.status}.`;
} catch {
- setFeedState('error');
- return;
+ reason = 'The revenue service could not be reached.';
}
- if (!res.ok) {
- setFeedState('error');
+ if (!data) {
+ if (state.hasFeed) setFeedState('error');
+ else renderFeedError(reason || 'The revenue service is not responding.');
return;
}
- const { data } = await res.json();
- renderInitialFeed(data?.events || []);
- state.cursor = data?.next_cursor || null;
+ renderInitialFeed(data.events || []);
+ state.cursor = data.next_cursor || null;
const more = $('xr-more');
if (more) more.hidden = !state.cursor;
}
@@ -643,7 +798,7 @@ function startPolling() {
if (state.pollTimer) return;
state.pollTimer = setInterval(() => {
if (document.hidden || state.paused) return;
- state.latestTs ? pollDelta() : loadInitialFeed();
+ state.latestTs ? pollDelta() : loadInitialFeed({ background: true });
}, POLL_MS);
}