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(receipts): page the whole vault and stop printing non-dollar assets as dollars

nirholase98bb2c27cfe
diff --git a/pages/receipts.html b/pages/receipts.html
index 7ddcd1a61..d2683ba72 100644
--- a/pages/receipts.html
+++ b/pages/receipts.html
@@ -180,17 +180,24 @@
</div>
<div class="rc-search-wrap">
+ <label class="rc-search-label" for="rc-search">Filter loaded receipts</label>
<input
type="search"
class="rc-search"
id="rc-search"
placeholder="Filter by endpoint, network, or tx hash"
- aria-label="Filter receipts"
/>
</div>
<div class="rc-list" id="rc-list" aria-live="polite"></div>
+ <div class="rc-more-wrap" id="rc-more-wrap" hidden>
+ <p class="rc-shown" id="rc-shown"></p>
+ <button type="button" class="rc-btn rc-btn-secondary rc-more" id="rc-more">
+ <span class="rc-btn-label">Load 200 more</span>
+ </button>
+ </div>
+
<div class="rc-empty" id="rc-empty" hidden>
<h3 id="rc-empty-title"></h3>
<p id="rc-empty-body"></p>
diff --git a/src/receipts-lib.js b/src/receipts-lib.js
index 5832e5b43..a5bd2a589 100644
--- a/src/receipts-lib.js
+++ b/src/receipts-lib.js
@@ -124,21 +124,67 @@ export function resourceDisplay(resourceUrl) {
}
}
+/**
+ * Settlement assets whose atomic amounts denominate a US dollar, so a bare
+ * "$" prefix is an honest label. Everything else (the platform coin included)
+ * renders as a quantity plus its ticker: printing 22,000 THREE as "$22000.00"
+ * claims a dollar value nobody quoted.
+ */
+const USD_PEGGED_SYMBOLS = new Set(['USDC', 'USDC.E', 'USDT', 'USD\u20AE0', 'USD', 'PYUSD', 'DAI']);
+
+/** @param {string|null|undefined} symbol */
+export function isUsdPegged(symbol) {
+ if (symbol == null || symbol === '') return true; // legacy rows: dollars
+ return USD_PEGGED_SYMBOLS.has(String(symbol).toUpperCase());
+}
+
+/** Thousands-separated integer, so a 60,559-receipt vault reads as one. */
+export function formatCount(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return '\u00B7';
+ return v.toLocaleString('en-US');
+}
+
+/**
+ * Render a decimal quantity at the precision the number deserves: sub-cent
+ * micropayments are the norm on this rail, so a $0.001 call must not collapse
+ * to $0.00, while a 22,000-token payment must not carry four decimals.
+ * @param {number} value
+ */
+function quantityLabel(value) {
+ if (value > 0 && value < 0.01) {
+ return value.toFixed(4).replace(/0+$/, '').replace(/\.$/, '');
+ }
+ return value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
+}
+
+/**
+ * Compose the human label for an amount already scaled out of atomics.
+ * @param {number} value
+ * @param {string|null|undefined} symbol
+ */
+export function amountLabel(value, symbol) {
+ const q = quantityLabel(value);
+ return isUsdPegged(symbol) ? `$${q}` : `${q} ${symbol}`;
+}
+
/**
* Human amount for a settled receipt, or null when we can't render it safely.
*
- * The scale comes from the API's `assetDecimals` field, which the server
- * resolves from the same env config that builds the 402 accepts. The client
- * deliberately keeps NO copy of our asset addresses: a local registry would
- * silently drift the day an asset is repointed, and rendering an amount at the
- * wrong scale is worse than not rendering it. An unrecognised asset arrives
- * with `assetDecimals: null` and stays unformatted.
+ * The scale comes from the API's `assetDecimals` field and the ticker from its
+ * `assetSymbol`, both resolved server-side from the same env config that builds
+ * the 402 accepts. The client deliberately keeps NO copy of our asset
+ * addresses: a local registry would silently drift the day an asset is
+ * repointed, and rendering an amount at the wrong scale (or under the wrong
+ * ticker) is worse than not rendering it. An unrecognised asset arrives with
+ * `assetDecimals: null` and stays unformatted.
*
* @param {string|number|null|undefined} amountAtomics
* @param {number|null|undefined} assetDecimals
- * @returns {{ value: number, label: string }|null}
+ * @param {string|null|undefined} [assetSymbol]
+ * @returns {{ value: number, label: string, symbol: string|null, usd: boolean }|null}
*/
-export function formatReceiptAmount(amountAtomics, assetDecimals) {
+export function formatReceiptAmount(amountAtomics, assetDecimals, assetSymbol) {
if (amountAtomics == null || amountAtomics === '') return null;
const atomic = Number(amountAtomics);
if (!Number.isFinite(atomic)) return null;
@@ -148,35 +194,80 @@ export function formatReceiptAmount(amountAtomics, assetDecimals) {
const decimals = Number(assetDecimals);
if (!Number.isInteger(decimals) || decimals < 0 || decimals > 18) return null;
const value = atomic / 10 ** decimals;
- // Sub-cent micropayments are the norm on this rail, so show enough
- // precision that a $0.001 call doesn't render as $0.00.
- const label =
- value > 0 && value < 0.01
- ? `$${value.toFixed(4).replace(/0+$/, '').replace(/\.$/, '')}`
- : `$${value.toFixed(2)}`;
- return { value, label };
+ const symbol = assetSymbol == null || assetSymbol === '' ? null : String(assetSymbol);
+ return { value, label: amountLabel(value, symbol), symbol, usd: isUsdPegged(symbol) };
}
/**
- * Total spend across rows whose amount we can render, plus how many rows had
- * no recorded amount (receipts issued before settlement capture landed).
- * @param {Array<{amountAtomics?: string|null, assetDecimals?: number|null}>} rows
+ * Spend across rows, kept per-asset because different settlement assets have
+ * different scales and different units. USD-pegged assets fold into one dollar
+ * figure (the headline a buyer wants); everything else is reported under its
+ * own ticker rather than converted at a rate we have no business inventing.
+ *
+ * `total`/`label` stay the dollar figure so the headline KPI has one number.
+ *
+ * @param {Array<{amountAtomics?: string|null, assetDecimals?: number|null,
+ * assetSymbol?: string|null}>} rows
*/
export function totalSpend(rows) {
let total = 0;
let priced = 0;
let unpriced = 0;
+ const others = new Map();
for (const r of rows || []) {
- const amt = formatReceiptAmount(r.amountAtomics, r.assetDecimals);
- if (amt) {
+ const amt = formatReceiptAmount(r.amountAtomics, r.assetDecimals, r.assetSymbol);
+ if (!amt) {
+ unpriced++;
+ continue;
+ }
+ priced++;
+ if (amt.usd) {
total += amt.value;
- priced++;
} else {
- unpriced++;
+ others.set(amt.symbol, (others.get(amt.symbol) || 0) + amt.value);
}
}
- const label = total > 0 && total < 0.01 ? `$${total.toFixed(4)}` : `$${total.toFixed(2)}`;
- return { total, label, priced, unpriced };
+ return {
+ total,
+ label: amountLabel(total, null),
+ priced,
+ unpriced,
+ others: [...others.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .map(([symbol, value]) => ({ symbol, value, label: amountLabel(value, symbol) })),
+ };
+}
+
+/**
+ * Same shape as totalSpend(), built from the API's account-wide `summary.spend`
+ * aggregate instead of the loaded page. A wallet with 60k receipts must be
+ * shown what it actually spent, not the spend of the newest page it happens to
+ * be holding, so the KPI strip prefers this whenever the API supplies it.
+ *
+ * @param {Array<{asset?: string, count?: number, atomics?: string,
+ * decimals?: number|null, symbol?: string|null}>} spend
+ * @param {number} [unpriced] account-wide count of receipts with no amount
+ */
+export function formatSpendEntries(spend, unpriced = 0) {
+ let total = 0;
+ let priced = 0;
+ const others = new Map();
+ for (const s of spend || []) {
+ const amt = formatReceiptAmount(s.atomics, s.decimals, s.symbol);
+ if (!amt) continue;
+ priced += Number(s.count) || 0;
+ if (amt.usd) total += amt.value;
+ else others.set(amt.symbol, (others.get(amt.symbol) || 0) + amt.value);
+ }
+ return {
+ total,
+ label: amountLabel(total, null),
+ priced,
+ unpriced: Number(unpriced) || 0,
+ others: [...others.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .map(([symbol, value]) => ({ symbol, value, label: amountLabel(value, symbol) })),
+ };
}
function csvCell(value) {
diff --git a/src/receipts.js b/src/receipts.js
index a0e025c77..2d1a86cfc 100644
--- a/src/receipts.js
+++ b/src/receipts.js
@@ -22,6 +22,8 @@ import {
receiptsToCsv,
summarizeReceipts,
formatReceiptAmount,
+ formatSpendEntries,
+ formatCount,
totalSpend,
} from './receipts-lib.js';
import { timeAgo } from './shared/pulse-format.js';
@@ -35,8 +37,14 @@ const $ = (id) => document.getElementById(id);
const state = {
session: null, // { address, network, signature, issuedAt }
rows: [],
+ // Account-wide aggregate from the API. The KPI strip reads THIS, never the
+ // loaded page: a wallet with 60k receipts must be told it has 60k, not the
+ // size of the window it happens to be holding.
+ summary: null,
+ nextCursor: null,
query: '',
loading: false,
+ loadingMore: false,
};
// ── wallet providers ─────────────────────────────────────────────────────────
@@ -122,7 +130,7 @@ function clearSession() {
// ── data ─────────────────────────────────────────────────────────────────────
-async function fetchReceipts(session) {
+async function fetchReceipts(session, cursor) {
const params = new URLSearchParams({
address: session.address,
signature: session.signature,
@@ -130,6 +138,7 @@ async function fetchReceipts(session) {
network: session.network,
limit: String(FETCH_LIMIT),
});
+ if (cursor) params.set('cursor', cursor);
const res = await fetch(`${API_URL}?${params}`);
const body = await res.json().catch(() => null);
if (!res.ok) {
@@ -137,7 +146,11 @@ async function fetchReceipts(session) {
const detail = body?.error_description || 'The receipt service returned an error.';
throw Object.assign(new Error(detail), { code });
}
- return body?.receipts || [];
+ return {
+ receipts: body?.receipts || [],
+ summary: body?.summary || null,
+ nextCursor: body?.nextCursor || null,
+ };
}
async function connect(kind) {
@@ -176,7 +189,10 @@ async function refresh({ resign = true } = {}) {
state.session = active;
saveSession(active);
}
- state.rows = await fetchReceipts(active);
+ const page = await fetchReceipts(active);
+ state.rows = page.receipts;
+ state.summary = page.summary;
+ state.nextCursor = page.nextCursor;
renderVault();
} catch (err) {
if (err?.code === 'stale_signature' || err?.code === 'invalid_signature') {
@@ -193,10 +209,45 @@ async function refresh({ resign = true } = {}) {
}
}
+/**
+ * Append the next keyset page. The API caps a page at 200 rows and hands back
+ * a cursor whenever more exist; without following it a heavy buyer could only
+ * ever see their newest 200 receipts, which is not "retrievable forever".
+ */
+async function loadMore() {
+ const session = state.session;
+ if (!session || !state.nextCursor || state.loading || state.loadingMore) return;
+ if (!signatureStillFresh(session.issuedAt)) {
+ showMoreError('Your signature expired. Hit Refresh to sign again.');
+ return;
+ }
+ state.loadingMore = true;
+ setMoreBusy(true);
+ try {
+ const page = await fetchReceipts(session, state.nextCursor);
+ state.rows = state.rows.concat(page.receipts);
+ state.nextCursor = page.nextCursor;
+ renderVault();
+ } catch (err) {
+ showMoreError(err?.message || 'Could not load more receipts.');
+ } finally {
+ state.loadingMore = false;
+ setMoreBusy(false);
+ }
+}
+
function disconnect() {
state.session = null;
state.rows = [];
+ state.summary = null;
+ state.nextCursor = null;
+ // A stale filter carried into the next session renders the new wallet's
+ // vault as "no receipts match your search", which reads as an empty vault.
+ state.query = '';
+ $('rc-search').value = '';
clearSession();
+ $('rc-load-error').hidden = true;
+ $('rc-more-wrap').hidden = true;
$('rc-vault').hidden = true;
$('rc-signin').hidden = false;
}
@@ -225,11 +276,13 @@ function renderSkeleton() {
.join('');
$('rc-empty').hidden = true;
$('rc-load-error').hidden = true;
+ $('rc-more-wrap').hidden = true;
}
function renderLoadError(message) {
$('rc-list').innerHTML = '';
$('rc-empty').hidden = true;
+ $('rc-more-wrap').hidden = true;
const el = $('rc-load-error');
el.hidden = false;
$('rc-load-error-msg').textContent = message;
@@ -242,29 +295,64 @@ function filteredRows() {
(r) =>
resourceDisplay(r.resourceUrl).toLowerCase().includes(q) ||
String(r.transaction || '').toLowerCase().includes(q) ||
+ String(r.assetSymbol || '').toLowerCase().includes(q) ||
networkLabel(r.network).toLowerCase().includes(q),
);
}
+/**
+ * KPI inputs: the API's account-wide summary when it supplied one, else the
+ * loaded page. Networks arrive as raw CAIP-2 ids in the summary, so they get
+ * the same label treatment the rows do.
+ */
+function vaultStats() {
+ const s = state.summary;
+ if (!s) {
+ return { stats: summarizeReceipts(state.rows), spend: totalSpend(state.rows), wide: false };
+ }
+ return {
+ stats: {
+ total: s.total,
+ endpoints: s.endpoints,
+ networks: (s.networks || []).map(networkLabel),
+ lastAt: s.lastAt,
+ },
+ spend: formatSpendEntries(s.spend, s.unpriced),
+ wide: true,
+ };
+}
+
+function renderPager(shown, total) {
+ const wrap = $('rc-more-wrap');
+ if (!state.nextCursor) {
+ wrap.hidden = true;
+ return;
+ }
+ wrap.hidden = false;
+ $('rc-shown').textContent = `Showing the newest ${formatCount(shown)} of ${formatCount(total)} receipts.`;
+}
+
function renderVault() {
- const stats = summarizeReceipts(state.rows);
- const spend = totalSpend(state.rows);
- $('rc-k-total').textContent = String(stats.total);
- $('rc-k-endpoints').textContent = String(stats.endpoints);
+ const { stats, spend } = vaultStats();
+ $('rc-k-total').textContent = formatCount(stats.total);
+ $('rc-k-endpoints').textContent = formatCount(stats.endpoints);
$('rc-k-networks').textContent = stats.networks.length ? stats.networks.join(' · ') : '·';
$('rc-k-last').textContent = stats.lastAt ? timeAgo(stats.lastAt) : '·';
- // Receipts issued before settlement capture landed carry no amount; say so
- // rather than quietly under-reporting the total.
+ // Receipts issued before settlement capture landed carry no amount, and
+ // non-dollar assets are never folded into the dollar figure. Say both,
+ // rather than quietly under-reporting or mislabelling the total.
$('rc-k-spend').textContent = spend.priced ? spend.label : '·';
- $('rc-k-spend-note').textContent = spend.unpriced
- ? `${spend.priced} of ${stats.total} priced`
- : 'USDC settled';
+ const notes = [];
+ for (const other of spend.others) notes.push(`+ ${other.label}`);
+ if (spend.unpriced) notes.push(`${formatCount(spend.priced)} of ${formatCount(stats.total)} priced`);
+ $('rc-k-spend-note').textContent = notes.length ? notes.join(' · ') : 'USDC settled';
$('rc-load-error').hidden = true;
const rows = filteredRows();
const list = $('rc-list');
if (!state.rows.length) {
list.innerHTML = '';
+ $('rc-more-wrap').hidden = true;
$('rc-empty').hidden = false;
$('rc-empty-title').textContent = 'No receipts for this wallet yet';
$('rc-empty-body').innerHTML =
@@ -275,12 +363,14 @@ function renderVault() {
}
if (!rows.length) {
list.innerHTML = '';
+ $('rc-more-wrap').hidden = true;
$('rc-empty').hidden = false;
$('rc-empty-title').textContent = 'No receipts match your search';
$('rc-empty-body').textContent = 'Try a different endpoint path, network, or transaction hash.';
return;
}
$('rc-empty').hidden = true;
+ renderPager(state.rows.length, stats.total);
list.innerHTML = rows
.map((r, i) => {
@@ -293,9 +383,9 @@ function renderVault() {
const when = r.issuedAt
? `<time datetime="${esc(r.issuedAt)}" title="${esc(new Date(r.issuedAt).toLocaleString())}">${esc(timeAgo(r.issuedAt))}</time>`
: '·';
- const amount = formatReceiptAmount(r.amountAtomics, r.assetDecimals);
+ const amount = formatReceiptAmount(r.amountAtomics, r.assetDecimals, r.assetSymbol);
const amountCell = amount
- ? `<span class="rc-amount" title="${esc(r.amountAtomics)} atomic units">${esc(amount.label)}</span>`
+ ? `<span class="rc-amount" title="${esc(r.amountAtomics)} atomic units of ${esc(r.asset || amount.symbol || 'the settlement asset')}">${esc(amount.label)}</span>`
: '';
return `
<div class="rc-row" data-idx="${i}">