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: x402 access gate, analytics + developer + three-token page updates, marketplace + viewer fixes

nirholas2a447ec0ddf3
diff --git a/api/healthz.js b/api/healthz.js
index 9519abaef..b174e91dd 100644
--- a/api/healthz.js
+++ b/api/healthz.js
@@ -7,17 +7,23 @@
// when downstream systems are degraded so it's safe to wire to uptime probes.
import { cors, json, method, wrap } from './_lib/http.js';
+import { countRecentPayments } from './_lib/x402/audit-log.js';
const STARTED_AT = Date.now();
const VERSION = process.env.VERCEL_GIT_COMMIT_SHA || process.env.npm_package_version || 'dev';
-const RESEND_CACHE_TTL_MS = 5 * 60 * 1000;
+const CACHE_TTL_MS = 5 * 60 * 1000;
+const RESEND_CACHE_TTL_MS = CACHE_TTL_MS;
let _resendCache = { value: null, expiresAt: 0 };
+let _x402Cache = { value: null, expiresAt: 0 };
// Exported for tests so each case starts with a cold cache.
export function _resetResendCache() {
_resendCache = { value: null, expiresAt: 0 };
}
+export function _resetX402Cache() {
+ _x402Cache = { value: null, expiresAt: 0 };
+}
async function probeResend() {
const now = Date.now();
@@ -57,12 +63,62 @@ async function probeResend() {
return result;
}
+async function probeX402() {
+ const now = Date.now();
+ if (_x402Cache.value && _x402Cache.expiresAt > now) {
+ return _x402Cache.value;
+ }
+
+ const result = {};
+
+ // Check if PAY_TO addresses are configured
+ const hasBase = !!process.env.X402_PAY_TO_BASE;
+ const hasSolana = !!process.env.X402_PAY_TO_SOLANA || !!process.env.X402_PAY_TO;
+ result.configured = hasBase || hasSolana;
+ result.networks = [];
+ if (hasBase) result.networks.push('base');
+ if (hasSolana) result.networks.push('solana');
+
+ // Probe facilitator connectivity (cached at this level, 5 min TTL)
+ const facilitatorUrl = process.env.X402_CDP_FACILITATOR_URL || process.env.X402_FACILITATOR_URL_BASE;
+ if (facilitatorUrl) {
+ try {
+ const r = await fetch(facilitatorUrl + '/supported', {
+ method: 'GET',
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(5000),
+ });
+ result.facilitator = r.ok ? 'reachable' : 'error_' + r.status;
+ } catch {
+ result.facilitator = 'unreachable';
+ }
+ } else {
+ result.facilitator = 'not_configured';
+ }
+
+ // Recent payments from audit log
+ result.recent_payments = await countRecentPayments(60);
+
+ // SIWX reachability (just check if the table exists)
+ try {
+ const rows = await (await import('./_lib/db.js')).sql`
+ SELECT 1 FROM siwx_payments LIMIT 1
+ `;
+ result.siwx = 'reachable';
+ } catch {
+ result.siwx = 'unavailable';
+ }
+
+ _x402Cache = { value: result, expiresAt: now + CACHE_TTL_MS };
+ return result;
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
const uptimeMs = Date.now() - STARTED_AT;
- const resend = await probeResend();
+ const [resend, x402] = await Promise.all([probeResend(), probeX402()]);
return json(res, 200, {
status: 'ok',
service: '3d-agent',
@@ -70,6 +126,7 @@ export default wrap(async (req, res) => {
uptime: Math.floor(uptimeMs / 1000),
uptimeMs,
resend,
+ x402,
// Match the pump-dashboard health shape so the existing UI binding works
// without conditional logic.
monitor: { running: true, mode: 'serverless', claimsDetected: 0 },
diff --git a/pages/features.html b/pages/features.html
index abd67cea7..d7f68905f 100644
--- a/pages/features.html
+++ b/pages/features.html
@@ -160,6 +160,36 @@
</div>
</section>
+ <!-- ── Traction stats bar ── -->
+ <section class="h-traction" aria-label="Platform traction">
+ <div class="h-traction-inner">
+ <div class="h-traction-stat" data-traction-key="agents">
+ <span class="h-traction-val" data-traction-val="agents">—</span>
+ <span class="h-traction-label">Agents created</span>
+ </div>
+ <div class="h-traction-divider" aria-hidden="true"></div>
+ <div class="h-traction-stat" data-traction-key="views">
+ <span class="h-traction-val" data-traction-val="views">—</span>
+ <span class="h-traction-label">Widget views</span>
+ </div>
+ <div class="h-traction-divider" aria-hidden="true"></div>
+ <div class="h-traction-stat" data-traction-key="chats">
+ <span class="h-traction-val" data-traction-val="chats">—</span>
+ <span class="h-traction-label">Conversations</span>
+ </div>
+ <div class="h-traction-divider" aria-hidden="true"></div>
+ <div class="h-traction-stat" data-traction-key="countries">
+ <span class="h-traction-val" data-traction-val="countries">—</span>
+ <span class="h-traction-label">Countries reached</span>
+ </div>
+ <div class="h-traction-divider" aria-hidden="true"></div>
+ <div class="h-traction-stat" data-traction-key="chains">
+ <span class="h-traction-val" data-traction-val="chains">—</span>
+ <span class="h-traction-label">Chains supported</span>
+ </div>
+ </div>
+ </section>
+
<!-- ── Pillars transition band ── -->
<section class="h-pillars" aria-label="What you get">
<div class="h-pillars-inner">
@@ -1412,5 +1442,67 @@
}
})();
</script>
+
+ <script>
+ // Traction stats — fetch /api/platform/stats, animate counters on scroll into view.
+ (function () {
+ function fmtNum(n) {
+ if (n >= 1_000_000) return (n / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M';
+ if (n >= 1_000) return (n / 1_000).toFixed(1).replace(/\.0$/, '') + 'K';
+ return String(n);
+ }
+
+ function animateCount(el, target) {
+ const duration = 1200;
+ const start = performance.now();
+ function step(now) {
+ const t = Math.min((now - start) / duration, 1);
+ const ease = 1 - Math.pow(1 - t, 3);
+ const val = Math.round(target * ease);
+ el.textContent = fmtNum(val);
+ if (t < 1) requestAnimationFrame(step);
+ }
+ requestAnimationFrame(step);
+ }
+
+ const section = document.querySelector('.h-traction');
+ const vals = document.querySelectorAll('[data-traction-val]');
+ if (!section) return;
+ vals.forEach((el) => el.classList.add('is-loading'));
+
+ let statsData = null;
+ let animated = false;
+
+ function triggerAnimation() {
+ if (animated || !statsData) return;
+ animated = true;
+ vals.forEach((el) => {
+ const key = el.dataset.tractionVal;
+ const raw = statsData[key];
+ if (raw == null) return;
+ el.classList.remove('is-loading');
+ animateCount(el, Number(raw));
+ });
+ }
+
+ const io = new IntersectionObserver((entries) => {
+ if (entries[0].isIntersecting) {
+ io.disconnect();
+ triggerAnimation();
+ }
+ }, { threshold: 0.3 });
+ io.observe(section);
+
+ fetch('/api/platform/stats')
+ .then((r) => r.ok ? r.json() : Promise.reject(r.status))
+ .then((data) => {
+ statsData = data;
+ triggerAnimation();
+ })
+ .catch(() => {
+ section.hidden = true;
+ });
+ })();
+ </script>
</body>
</html>
diff --git a/pages/home.html b/pages/home.html
index 051e4e7e0..264f08c2f 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -199,8 +199,8 @@
One GLB. Any LLM. Owned on Solana. Earn USDC with every interaction.
</p>
<div class="h-cta-row h-reveal">
- <a href="/dashboard" class="h-btn-primary">
- <span>Launch Dashboard</span>
+ <a href="/create" class="h-btn-primary">
+ <span>Get Started Free</span>
<span class="arrow">→</span>
</a>
<a href="/marketplace" class="h-btn-ghost">Browse Marketplace</a>
diff --git a/public/x402-paywall.js b/public/x402-paywall.js
new file mode 100644
index 000000000..35a7438c9
--- /dev/null
+++ b/public/x402-paywall.js
@@ -0,0 +1,542 @@
+// x402-paywall.js — drop-in content paywall component.
+//
+// Usage:
+//
+// <div data-x402-paywall="/api/x402/dance-tip?dancer=1&dance=rumba">
+// <p>This content is premium. Pay to unlock.</p>
+// </div>
+//
+// Or programmatically:
+//
+// window.X402Paywall.init({
+// selector: '[data-x402-paywall]',
+// onUnlock: (el, data) => { ... }
+// });
+//
+// The component:
+// 1. Fetches the 402 body from the endpoint to read price/description.
+// 2. Renders a frosted glass overlay with price, network, and unlock button.
+// 3. On click, delegates to window.X402.pay() for the wallet flow.
+// 4. On success, removes the overlay and reveals the content.
+// 5. Saves access in localStorage so repeat visits skip the paywall.
+
+(function () {
+ 'use strict';
+
+ var STORAGE_PREFIX = 'x402_paywall_';
+ var CSS_INJECTED = false;
+
+ // ── Styles ────────────────────────────────────────────────────────────
+
+ function injectStyles() {
+ if (CSS_INJECTED) return;
+ CSS_INJECTED = true;
+ var style = document.createElement('style');
+ style.textContent = [
+ '[data-x402-paywall] {',
+ ' position: relative;',
+ ' overflow: hidden;',
+ '}',
+
+ '.x402-pw-overlay {',
+ ' position: absolute;',
+ ' inset: 0;',
+ ' z-index: 100;',
+ ' display: flex;',
+ ' flex-direction: column;',
+ ' align-items: center;',
+ ' justify-content: center;',
+ ' gap: 16px;',
+ ' padding: 32px 24px;',
+ ' background: rgba(5, 5, 5, 0.75);',
+ ' backdrop-filter: blur(16px);',
+ ' -webkit-backdrop-filter: blur(16px);',
+ ' border: 1px solid rgba(255, 255, 255, 0.06);',
+ ' border-radius: inherit;',
+ ' text-align: center;',
+ ' font-family: "Inter", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;',
+ ' -webkit-font-smoothing: antialiased;',
+ ' transition: opacity 0.35s ease, backdrop-filter 0.35s ease;',
+ '}',
+
+ '.x402-pw-overlay.x402-pw-unlocking {',
+ ' opacity: 0;',
+ ' pointer-events: none;',
+ '}',
+
+ '.x402-pw-badge {',
+ ' display: inline-flex;',
+ ' align-items: center;',
+ ' gap: 6px;',
+ ' padding: 4px 12px;',
+ ' border-radius: 100px;',
+ ' background: rgba(255, 255, 255, 0.06);',
+ ' border: 1px solid rgba(255, 255, 255, 0.08);',
+ ' font-size: 11px;',
+ ' letter-spacing: 0.08em;',
+ ' text-transform: uppercase;',
+ ' color: #a8a8a8;',
+ '}',
+
+ '.x402-pw-badge-dot {',
+ ' width: 6px;',
+ ' height: 6px;',
+ ' border-radius: 50%;',
+ ' background: #2dd4bf;',
+ '}',
+
+ '.x402-pw-price {',
+ ' font-size: 36px;',
+ ' font-weight: 700;',
+ ' letter-spacing: -0.04em;',
+ ' color: #f6f6f6;',
+ ' line-height: 1.1;',
+ ' font-variant-numeric: tabular-nums;',
+ '}',
+
+ '.x402-pw-desc {',
+ ' font-size: 14px;',
+ ' color: #a8a8a8;',
+ ' max-width: 320px;',
+ ' line-height: 1.5;',
+ '}',
+
+ '.x402-pw-unlock {',
+ ' display: inline-flex;',
+ ' align-items: center;',
+ ' gap: 8px;',
+ ' padding: 12px 28px;',
+ ' border: none;',
+ ' border-radius: 10px;',
+ ' background: #f6f6f6;',
+ ' color: #050505;',
+ ' font-size: 14.5px;',
+ ' font-weight: 600;',
+ ' font-family: inherit;',
+ ' cursor: pointer;',
+ ' transition: transform 0.12s, box-shadow 0.12s, background 0.12s;',
+ '}',
+ '.x402-pw-unlock:hover {',
+ ' transform: translateY(-1px);',
+ ' box-shadow: 0 4px 16px rgba(255, 255, 255, 0.08);',
+ '}',
+ '.x402-pw-unlock:active {',
+ ' transform: translateY(0);',
+ '}',
+ '.x402-pw-unlock:disabled {',
+ ' opacity: 0.5;',
+ ' cursor: not-allowed;',
+ ' transform: none;',
+ ' box-shadow: none;',
+ '}',
+
+ '.x402-pw-siwx {',
+ ' display: inline-flex;',
+ ' align-items: center;',
+ ' gap: 6px;',
+ ' padding: 8px 20px;',
+ ' border: 1px solid rgba(255, 255, 255, 0.1);',
+ ' border-radius: 8px;',
+ ' background: transparent;',
+ ' color: #a8a8a8;',
+ ' font-size: 13px;',
+ ' font-weight: 500;',
+ ' font-family: inherit;',
+ ' cursor: pointer;',
+ ' transition: border-color 0.12s, color 0.12s;',
+ '}',
+ '.x402-pw-siwx:hover {',
+ ' border-color: rgba(255, 255, 255, 0.25);',
+ ' color: #f6f6f6;',
+ '}',
+
+ '.x402-pw-network {',
+ ' font-size: 12px;',
+ ' color: #6a6a6a;',
+ '}',
+
+ '.x402-pw-error {',
+ ' font-size: 13px;',
+ ' color: #f87171;',
+ ' max-width: 320px;',
+ '}',
+
+ '.x402-pw-footer {',
+ ' font-size: 11px;',
+ ' color: #4a4a4a;',
+ '}',
+ '.x402-pw-footer a {',
+ ' color: #6a6a6a;',
+ ' text-decoration: none;',
+ '}',
+ '.x402-pw-footer a:hover {',
+ ' color: #a8a8a8;',
+ '}',
+
+ // Blur the content behind the paywall
+ '[data-x402-paywall]:not(.x402-pw-unlocked) > :not(.x402-pw-overlay) {',
+ ' filter: blur(8px);',
+ ' pointer-events: none;',
+ ' user-select: none;',
+ '}',
+ '[data-x402-paywall].x402-pw-unlocked > :not(.x402-pw-overlay) {',
+ ' filter: none;',
+ ' pointer-events: auto;',
+ ' user-select: auto;',
+ '}',
+ ].join('\n');
+ document.head.appendChild(style);
+ }
+
+ // ── Price formatting ──────────────────────────────────────────────────
+
+ function formatAmount(amount, decimals) {
+ decimals = decimals || 6;
+ var n = Number(amount || 0);
+ var usd = n / Math.pow(10, decimals);
+ if (usd === 0) return '$0.00';
+ if (usd < 0.000001) return '$' + usd.toFixed(8).replace(/\.?0+$/, '');
+ if (usd < 0.01) return '$' + usd.toFixed(6).replace(/\.?0+$/, '');
+ if (usd < 1) return '$' + usd.toFixed(4).replace(/\.?0+$/, '');
+ return '$' + usd.toFixed(2);
+ }
+
+ function networkLabel(network) {
+ var n = String(network || '');
+ if (n.startsWith('eip155:8453') && !n.startsWith('eip155:84532')) return 'Base';
+ if (n.startsWith('eip155:84532')) return 'Base Sepolia';
+ if (n.startsWith('eip155:42161')) return 'Arbitrum';
+ if (n.startsWith('eip155:10')) return 'Optimism';
+ if (n.startsWith('eip155:56')) return 'BNB Chain';
+ if (n.startsWith('solana:')) return 'Solana';
+ return 'Unknown';
+ }
+
+ function explorerUrl(network, txHash) {
+ var n = String(network || '');
+ if (n.startsWith('eip155:8453') && !n.startsWith('eip155:84532')) return 'https://basescan.org/tx/' + txHash;
+ if (n.startsWith('eip155:84532')) return 'https://sepolia.basescan.org/tx/' + txHash;
+ if (n.startsWith('eip155:42161')) return 'https://arbiscan.io/tx/' + txHash;
+ if (n.startsWith('eip155:10')) return 'https://optimistic.etherscan.io/tx/' + txHash;
+ if (n.startsWith('eip155:56')) return 'https://bscscan.com/tx/' + txHash;
+ if (n.startsWith('solana:')) return 'https://solscan.io/tx/' + txHash;
+ return null;
+ }
+
+ // ── Storage helpers ───────────────────────────────────────────────────
+
+ function storageKey(endpoint) {
+ return STORAGE_PREFIX + btoa(endpoint).replace(/=/g, '');
+ }
+
+ function hasAccess(endpoint) {
+ try {
+ var data = localStorage.getItem(storageKey(endpoint));
+ if (!data) return false;
+ var parsed = JSON.parse(data);
+ if (parsed.expiresAt && Date.now() > parsed.expiresAt) {
+ localStorage.removeItem(storageKey(endpoint));
+ return false;
+ }
+ return true;
+ } catch (_) {
+ return false;
+ }
+ }
+
+ function grantAccess(endpoint, meta) {
+ try {
+ localStorage.setItem(storageKey(endpoint), JSON.stringify({
+ grantedAt: Date.now(),
+ expiresAt: null,
+ ...meta,
+ }));
+ } catch (_) {}
+ }
+
+ // ── Fetch 402 requirements ────────────────────────────────────────────
+
+ function fetchRequirements(endpoint) {
+ return fetch(endpoint, {
+ method: 'GET',
+ headers: { 'Accept': 'application/json' },
+ }).then(function (res) {
+ if (res.status === 402) return res.json();
+ if (res.ok) return null;
+ throw new Error('Unexpected status ' + res.status);
+ });
+ }
+
+ // ── Render overlay ────────────────────────────────────────────────────
+
+ function buildOverlay(endpoint, data) {
+ var overlay = document.createElement('div');
+ overlay.className = 'x402-pw-overlay';
+
+ var accepts = data && data.accepts;
+ if (!accepts || !accepts.length) {
+ overlay.innerHTML =
+ '<div class="x402-pw-badge"><span class="x402-pw-badge-dot"></span>Premium</div>' +
+ '<div class="x402-pw-price">Locked</div>' +
+ '<div class="x402-pw-desc">Payment required to access this content.</div>';
+ return overlay;
+ }
+
+ // Find cheapest non-zero, non-auth-hint accept
+ var paid = accepts.filter(function (a) { return Number(a.amount || 0) > 0; });
+ var cheapest = paid.length ? paid.reduce(function (a, b) {
+ return Number(b.amount || 0) < Number(a.amount || 0) ? b : a;
+ }, paid[0]) : accepts[0];
+
+ var decimals = (cheapest.extra && cheapest.extra.decimals) || 6;
+ var price = formatAmount(cheapest.amount, decimals);
+ var assetName = (cheapest.extra && cheapest.extra.name) || 'USDC';
+
+ var networks = [];
+ var seen = {};
+ paid.forEach(function (a) {
+ var label = networkLabel(a.network);
+ if (!seen[label]) {
+ seen[label] = true;
+ networks.push(label);
+ }
+ });
+
+ var hasSiwx = data.extensions && data.extensions['sign-in-with-x'];
+ var description = '';
+ if (data.resource && data.resource.description) {
+ description = data.resource.description;
+ } else if (data.description) {
+ description = data.description;
+ }
+ if (description.length > 120) {
+ description = description.slice(0, 117) + '...';
+ }
+
+ var html =
+ '<div class="x402-pw-badge"><span class="x402-pw-badge-dot"></span>Premium Content</div>' +
+ '<div class="x402-pw-price">' + escHtml(price) + '</div>' +
+ '<div class="x402-pw-desc">' + escHtml(description || 'Unlock this content with a single micropayment.') + '</div>' +
+ '<button class="x402-pw-unlock" data-x402-pw-action="pay">' +
+ '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>' +
+ 'Unlock with ' + escHtml(assetName) +
+ '</button>';
+
+ if (hasSiwx) {
+ html +=
+ '<button class="x402-pw-siwx" data-x402-pw-action="siwx">' +
+ 'Already paid? Sign in with wallet' +
+ '</button>';
+ }
+
+ html +=
+ '<div class="x402-pw-network">Available on ' + escHtml(networks.join(', ')) + '</div>' +
+ '<div class="x402-pw-error" style="display:none" data-x402-pw-error></div>' +
+ '<div class="x402-pw-footer">Powered by <a href="https://x402.org" target="_blank" rel="noopener">x402</a></div>';
+
+ overlay.innerHTML = html;
+ return overlay;
+ }
+
+ function escHtml(str) {
+ return String(str)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+ }
+
+ // ── Unlock animation ──────────────────────────────────────────────────
+
+ function unlockElement(el, overlay, txHash, network) {
+ overlay.classList.add('x402-pw-unlocking');
+ setTimeout(function () {
+ if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
+ el.classList.add('x402-pw-unlocked');
+ }, 350);
+ }
+
+ // ── Initialize one paywall element ────────────────────────────────────
+
+ function initElement(el, opts) {
+ var endpoint = el.getAttribute('data-x402-paywall');
+ if (!endpoint) return;
+
+ // Already unlocked from localStorage
+ if (hasAccess(endpoint)) {
+ el.classList.add('x402-pw-unlocked');
+ if (opts && opts.onUnlock) opts.onUnlock(el, { cached: true });
+ return;
+ }
+
+ // Fetch requirements
+ var overlay = document.createElement('div');
+ overlay.className = 'x402-pw-overlay';
+ overlay.innerHTML = '<div class="x402-pw-badge"><span class="x402-pw-badge-dot"></span>Loading...</div>';
+ el.appendChild(overlay);
+
+ fetchRequirements(endpoint).then(function (data) {
+ if (!data) {
+ // Not a 402 — content is free
+ el.classList.add('x402-pw-unlocked');
+ if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
+ if (opts && opts.onUnlock) opts.onUnlock(el, { free: true });
+ return;
+ }
+
+ // Replace loading overlay with real content
+ if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
+ var realOverlay = buildOverlay(endpoint, data);
+ el.appendChild(realOverlay);
+
+ // Wire pay button
+ realOverlay.addEventListener('click', function (e) {
+ var btn = e.target.closest('[data-x402-pw-action]');
+ if (!btn) return;
+ var action = btn.getAttribute('data-x402-pw-action');
+
+ if (action === 'pay') {
+ handlePay(el, realOverlay, endpoint, data, opts);
+ } else if (action === 'siwx') {
+ handleSiwx(el, realOverlay, endpoint, opts);
+ }
+ });
+ }).catch(function (err) {
+ // Network error — show generic paywall
+ if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
+ var errorOverlay = buildOverlay(endpoint, null);
+ el.appendChild(errorOverlay);
+ });
+ }
+
+ function handlePay(el, overlay, endpoint, data, opts) {
+ var btn = overlay.querySelector('[data-x402-pw-action="pay"]');
+ var errorEl = overlay.querySelector('[data-x402-pw-error]');
+ if (btn) {
+ btn.disabled = true;
+ btn.textContent = 'Connecting wallet...';
+ }
+ if (errorEl) errorEl.style.display = 'none';
+
+ // Check for window.X402
+ if (!window.X402 || typeof window.X402.pay !== 'function') {
+ showError(overlay, 'Payment SDK not loaded. Include x402.js on this page.');
+ if (btn) {
+ btn.disabled = false;
+ btn.textContent = 'Unlock with USDC';
+ }
+ return;
+ }
+
+ var serviceName = '';
+ if (data && data.resource && data.resource.description) {
+ serviceName = data.resource.description.split(' ').slice(0, 4).join(' ');
+ }
+
+ window.X402.pay({
+ endpoint: endpoint,
+ merchant: 'three.ws',
+ action: serviceName || 'Unlock Content',
+ }).then(function (result) {
+ var txHash = result && result.payment && result.payment.transaction;
+ var network = result && result.payment && result.payment.network;
+
+ grantAccess(endpoint, {
+ txHash: txHash,
+ network: network,
+ payer: result && result.payment && result.payment.payer,
+ });
+
+ unlockElement(el, overlay, txHash, network);
+
+ if (opts && opts.onUnlock) {
+ opts.onUnlock(el, { result: result, cached: false });
+ }
+ }).catch(function (err) {
+ showError(overlay, err.message || 'Payment failed. Please try again.');
+ if (btn) {
+ btn.disabled = false;
+ btn.textContent = 'Unlock with USDC';
+ }
+ });
+ }
+
+ function handleSiwx(el, overlay, endpoint, opts) {
+ var siwxBtn = overlay.querySelector('[data-x402-pw-action="siwx"]');
+ var errorEl = overlay.querySelector('[data-x402-pw-error]');
+ if (siwxBtn) {
+ siwxBtn.disabled = true;
+ siwxBtn.textContent = 'Connecting...';
+ }
+ if (errorEl) errorEl.style.display = 'none';
+
+ if (!window.X402 || typeof window.X402.siwx !== 'function') {
+ // Fallback: try pay flow which may handle SIWX internally
+ if (window.X402 && typeof window.X402.pay === 'function') {
+ handlePay(el, overlay, endpoint, null, opts);
+ return;
+ }
+ showError(overlay, 'SIWX not available. Include x402.js on this page.');
+ if (siwxBtn) {
+ siwxBtn.disabled = false;
+ siwxBtn.textContent = 'Already paid? Sign in with wallet';
+ }
+ return;
+ }
+
+ window.X402.siwx({ endpoint: endpoint }).then(function (result) {
+ grantAccess(endpoint, {
+ siwx: true,
+ address: result && result.address,
+ });
+ unlockElement(el, overlay);
+ if (opts && opts.onUnlock) opts.onUnlock(el, { siwx: true, cached: false });
+ }).catch(function (err) {
+ showError(overlay, err.message || 'Wallet sign-in failed.');
+ if (siwxBtn) {
+ siwxBtn.disabled = false;
+ siwxBtn.textContent = 'Already paid? Sign in with wallet';
+ }
+ });
+ }
+
+ function showError(overlay, message) {
+ var el = overlay.querySelector('[data-x402-pw-error]');
+ if (el) {
+ el.textContent = message;
+ el.style.display = 'block';
+ }
+ }
+
+ // ── Public API ────────────────────────────────────────────────────────
+
+ function init(opts) {
+ opts = opts || {};
+ injectStyles();
+ var selector = opts.selector || '[data-x402-paywall]';
+ var elements = document.querySelectorAll(selector);
+ for (var i = 0; i < elements.length; i++) {
+ initElement(elements[i], opts);
+ }
+ }
+
+ // ── Auto-init on DOMContentLoaded ─────────────────────────────────────
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', function () { init(); });
+ } else {
+ // DOM already loaded (script loaded async/deferred)
+ setTimeout(function () { init(); }, 0);
+ }
+
+ // ── Export ─────────────────────────────────────────────────────────────
+
+ window.X402Paywall = {
+ init: init,
+ hasAccess: hasAccess,
+ grantAccess: grantAccess,
+ clearAccess: function (endpoint) {
+ try { localStorage.removeItem(storageKey(endpoint)); } catch (_) {}
+ },
+ };
+})();
diff --git a/src/club.js b/src/club.js
index 4d2d1282a..7a92ac4a5 100644
--- a/src/club.js
+++ b/src/club.js
@@ -330,10 +330,11 @@ let activeProfile = PROFILES[detectProfile()];
if (typeof window !== 'undefined') window.__clubProfile = activeProfile;
// ── Renderer / scene ──────────────────────────────────────────────────────
-const renderer = new WebGLRenderer({ canvas, antialias: activeProfile.tier !== 'low', alpha: false });
+const renderer = new WebGLRenderer({ canvas, antialias: false, alpha: false });
renderer.setPixelRatio(activeProfile.pixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputColorSpace = SRGBColorSpace;
+renderer.toneMapping = NoToneMapping;
renderer.shadowMap.enabled = activeProfile.shadows;
const scene = new Scene();
@@ -357,6 +358,26 @@ const camera = new PerspectiveCamera(46, window.innerWidth / window.innerHeight,
camera.position.set(0, 1.8, 6.0);
camera.lookAt(0, 1.4, -1.5);
+// ── Postprocessing pipeline ─────────────────────────────────────────────
+// pmndrs EffectComposer replaces direct renderer.render(). Bloom makes the
+// neon elements glow, tone mapping gives cinematic colour, vignette darkens
+// the edges, and SMAA handles anti-aliasing at the compositing stage (so
+// we disable the renderer's built-in MSAA above).
+const bloomEffect = new BloomEffect({
+ intensity: 1.2,
+ luminanceThreshold: 0.3,
+ luminanceSmoothing: 0.08,
+ mipmapBlur: true,
+});
+const toneMappingEffect = new ToneMappingEffect({ mode: ToneMappingMode.ACES_FILMIC });
+const vignetteEffect = new VignetteEffect({ darkness: 0.45, offset: 0.35 });
+const smaaEffect = new SMAAEffect();
+
+const composer = new EffectComposer(renderer);
+composer.addPass(new RenderPass(scene, camera));
+composer.addPass(new EffectPass(camera, bloomEffect, toneMappingEffect, vignetteEffect));
+composer.addPass(new EffectPass(camera, smaaEffect));
+
const clubCam = new ClubCamera(camera, {
onModeChange: (mode) => {
updateFreeCamChip(mode);
@@ -1121,6 +1142,8 @@ function ensureFreeCamChip() {
function updateFreeCamChip(mode) {
const chip = ensureFreeCamChip();
chip.hidden = (mode === 'free');
+ if (mode === 'auto') chip.textContent = '↩ Free cam (auto-orbiting)';
+ else chip.textContent = '↩ Free cam';
}
// ── Auto-follow tips toggle (persisted) ──────────────────────────────────
@@ -1309,11 +1332,20 @@ function renderPoles() {
}
// ── Resize ────────────────────────────────────────────────────────────────
-window.addEventListener('resize', () => {
- renderer.setSize(window.innerWidth, window.innerHeight, false);
- camera.aspect = window.innerWidth / window.innerHeight;
+function handleResize() {
+ const w = window.innerWidth;
+ const h = window.innerHeight;
+ renderer.setSize(w, h, false);
+ composer.setSize(w, h);
+ camera.aspect = w / h;
camera.updateProjectionMatrix();
-});
+
+ // On mobile low-perf, cap pixel ratio to 1 to save GPU budget.
+ if (isMobileLayout() && activeProfile.tier === 'low') {
+ renderer.setPixelRatio(1);
+ }
+}
+window.addEventListener('resize', handleResize);
// ── Keyboard shortcuts ───────────────────────────────────────────────────
// 0 → overhead house cam
@@ -1406,7 +1438,11 @@ function animate() {
// Camera state machine — orbit / VIP / house / auto.
clubCam.tick(dt);
- renderer.render(scene, camera);
+ // Audio-reactive bloom — pulse intensity with the beat.
+ const peak = audio.getPeak();
+ bloomEffect.intensity = 1.0 + peak * 1.5;
+
+ composer.render(dt);
rafId = requestAnimationFrame(animate);
}
diff --git a/src/dashboard-next/pages/analytics.js b/src/dashboard-next/pages/analytics.js
index cafc5e297..17334c9f0 100644
--- a/src/dashboard-next/pages/analytics.js
+++ b/src/dashboard-next/pages/analytics.js
@@ -2,6 +2,7 @@
//
// Revenue charts, per-agent performance, skill breakdown, conversion funnel.
// All data from real /api/billing/revenue, /api/agents, /api/widgets/:id/stats.
+// Charts drawn with Canvas 2D API directly — no chart libraries.
import { mountShell } from '../shell.js';
import { requireUser, get, esc, relTime, formatUsdc, ApiError } from '../api.js';
@@ -42,7 +43,7 @@ function renderSkeletons(root) {
root.innerHTML = `
<div class="ana-range-bar">${RANGES.map(r => `<button class="ana-range-btn${r.key === range.key ? ' is-active' : ''}">${r.label}</button>`).join('')}</div>
<div class="ana-kpi-row">${Array.from({ length: 4 }, () => `<div class="dn-panel ana-kpi"><div class="dn-skeleton" style="height:12px;width:80px;margin-bottom:8px"></div><div class="dn-skeleton" style="height:28px;width:100px"></div></div>`).join('')}</div>
- <div class="dn-panel" style="min-height:280px"><div class="dn-skeleton" style="height:12px;width:120px;margin-bottom:16px"></div><div class="dn-skeleton" style="height:200px;width:100%"></div></div>
+ <div class="dn-panel" style="min-height:280px"><div class="dn-skeleton" style="height:12px;width:120px;margin-bottom:16px"></div><div class="dn-skeleton" style="height:220px;width:100%"></div></div>
<div class="ana-two-col">
<div class="dn-panel" style="min-height:200px"><div class="dn-skeleton" style="height:12px;width:100px;margin-bottom:12px"></div><div class="dn-skeleton" style="height:150px;width:100%"></div></div>
<div class="dn-panel" style="min-height:200px"><div class="dn-skeleton" style="height:12px;width:100px;margin-bottom:12px"></div><div class="dn-skeleton" style="height:150px;width:100%"></div></div>
@@ -54,11 +55,12 @@ async function loadAndRender(root) {
const from = new Date(Date.now() - range.days * 86400_000).toISOString();
const to = new Date().toISOString();
- const [revenue, agents, widgets, summary] = await Promise.all([
+ const [revenue, agents, widgets, summary, monRevenue] = await Promise.all([
safe(() => get(`/api/billing/revenue?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}&granularity=${range.granularity}`)),
safe(() => get('/api/agents?limit=50')),
safe(() => get('/api/widgets')),
safe(() => get('/api/billing/summary')),
+ safe(() => get(`/api/monetization/revenue?period=${range.key}`)),
]);
const agentList = agents?.agents ?? [];
@@ -86,16 +88,31 @@ async function loadAndRender(root) {
const timeseries = revenue?.timeseries ?? [];
const bySkill = revenue?.by_skill ?? [];
+ // Fetch per-agent payments for the activity table
+ const recentPayments = await fetchRecentActivity(agentList);
+
+ // Get top agent by revenue
+ const topAgent = agentList.length > 0
+ ? agentList.reduce((best, a) => {
+ const rev = Number(a.total_revenue ?? a.revenue ?? 0);
+ return rev > (best.rev || 0) ? { name: a.name, rev } : best;
+ }, { name: agentList[0].name, rev: 0 })
+ : null;
+
root.innerHTML = '';
root.appendChild(renderRangeBar(root));
- root.appendChild(renderKpis({ revTotal, revPayments, totalViews, totalChats, recentViews, recentChats, agentList, widgetList }));
+ root.appendChild(renderKpis({
+ revTotal, revPayments, totalViews, totalChats,
+ recentViews, recentChats, agentList, widgetList,
+ topAgent,
+ }));
root.appendChild(renderRevenueChart(timeseries));
root.appendChild(renderTwoCol(
renderSkillBreakdown(bySkill),
renderAgentTable(agentList, widgetList, widgetStats)
));
- root.appendChild(renderFunnel({ totalViews: recentViews, totalChats: recentChats, revPayments }));
+ root.appendChild(renderActivityTable(recentPayments));
root.querySelector('.ana-range-bar')?.addEventListener('click', e => {
const btn = e.target.closest('.ana-range-btn');
@@ -111,25 +128,35 @@ async function loadAndRender(root) {
function safe(fn) { return fn().catch(() => null); }
-// ── KPIs ──────────────────────────────────────────────────────────────────
+// -- KPIs --
-function renderKpis({ revTotal, revPayments, recentViews, recentChats, agentList, widgetList }) {
+function renderKpis({ revTotal, revPayments, recentViews, recentChats, agentList, widgetList, topAgent }) {
const el = document.createElement('div');
el.className = 'ana-kpi-row';
+
+ const avgPrice = revPayments > 0 ? (revTotal / 1_000_000) / revPayments : 0;
+ const avgPriceStr = avgPrice > 0
+ ? '$' + avgPrice.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 6 })
+ : '$0.00';
+
el.innerHTML = [
- kpiCard('Revenue', formatUsdc(revTotal), `${revPayments} payment${revPayments !== 1 ? 's' : ''}`),
- kpiCard('Widget Views', recentViews.toLocaleString(), `${range.label}`),
- kpiCard('Conversations', recentChats.toLocaleString(), `${range.label}`),
- kpiCard('Active Agents', agentList.length.toLocaleString(), `${widgetList.length} widget${widgetList.length !== 1 ? 's' : ''}`),
+ kpiCard('Total Revenue', formatUsdc(revTotal), `${revPayments} payment${revPayments !== 1 ? 's' : ''}`, 'var(--nxt-success)'),
+ kpiCard('Total Callers', recentChats.toLocaleString(), `${recentViews.toLocaleString()} views`, 'var(--nxt-accent)'),
+ kpiCard('Avg Price/Call', avgPriceStr, `${range.label}`, 'var(--nxt-warn)'),
+ kpiCard('Top Agent', topAgent?.name || '--', topAgent?.rev > 0 ? formatUsdc(topAgent.rev) : `${agentList.length} agent${agentList.length !== 1 ? 's' : ''}`, 'var(--nxt-accent)'),
].join('');
return el;
}
-function kpiCard(label, value, sub) {
- return `<div class="dn-panel ana-kpi"><div class="ana-kpi-label">${esc(label)}</div><div class="ana-kpi-value">${esc(value)}</div><div class="ana-kpi-sub">${esc(sub)}</div></div>`;
+function kpiCard(label, value, sub, accentColor) {
+ return `<div class="dn-panel ana-kpi">
+ <div class="ana-kpi-label">${esc(label)}</div>
+ <div class="ana-kpi-value" style="color:${accentColor || 'var(--nxt-ink)'}">${esc(value)}</div>
+ <div class="ana-kpi-sub">${esc(sub)}</div>
+ </div>`;
}
-// ── Revenue chart (SVG bar chart) ─────────────────────────────────────────
+// -- Revenue chart (Canvas 2D) --
function renderRevenueChart(timeseries) {
const panel = document.createElement('div');
@@ -140,47 +167,151 @@ function renderRevenueChart(timeseries) {
return panel;
}
+ panel.innerHTML = `
+ <div class="dn-panel-title">Revenue Over Time</div>
+ <div data-slot="chart" style="position:relative;width:100%;height:220px;margin-top:12px"></div>
+ `;
+
+ const chartHost = panel.querySelector('[data-slot="chart"]');
+ requestAnimationFrame(() => paintCanvasLineChart(chartHost, timeseries));
+
+ return panel;
+}
+
+function paintCanvasLineChart(host, timeseries) {
+ host.innerHTML = '';
+ const canvas = document.createElement('canvas');
+ canvas.style.cssText = 'width:100%;height:100%;display:block';
+ host.appendChild(canvas);
+
+ const dpr = window.devicePixelRatio || 1;
+ const rect = host.getBoundingClientRect();
+ canvas.width = Math.round(rect.width * dpr);
+ canvas.height = Math.round(rect.height * dpr);
+ const ctx = canvas.getContext('2d');
+ ctx.scale(dpr, dpr);
+
+ const W = rect.width;
+ const H = rect.height;
+ const PAD = { top: 16, right: 16, bottom: 32, left: 52 };
+ const innerW = W - PAD.left - PAD.right;
+ const innerH = H - PAD.top - PAD.bottom;
+
const data = timeseries.map(p => ({
label: formatPeriod(p.period),
- value: Number(p.net_total) / 1_000_000,
+ value: Number(p.net_total ?? 0) / 1_000_000,
count: Number(p.count ?? 0),
+ raw: p,
+ }));
+
+ const max = Math.max(0.01, ...data.map(d => d.value));
+
+ const points = data.map((d, i) => ({
+ x: PAD.left + (data.length === 1 ? innerW / 2 : (i / (data.length - 1)) * innerW),
+ y: PAD.top + innerH - (d.value / max) * innerH,
}));
- const max = Math.max(1, ...data.map(d => d.value));
- const W = 800, H = 200, pad = 40, barGap = 4;
- const barW = Math.max(4, (W - pad * 2) / data.length - barGap);
- const chartH = H - pad;
-
- let bars = '';
- let labels = '';
- const showEvery = Math.max(1, Math.ceil(data.length / 12));
-
- data.forEach((d, i) => {
- const x = pad + i * (barW + barGap);
- const h = Math.max(1, (d.value / max) * chartH);
- const y = H - h;
- const usd = d.value.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
- bars += `<rect x="${x}" y="${y}" width="${barW}" height="${h}" rx="2" fill="var(--nxt-accent, #6c8aff)" opacity="0.8"><title>${d.label}: ${usd} (${d.count} payments)</title></rect>`;
- if (i % showEvery === 0) {
- labels += `<text x="${x + barW / 2}" y="${H + 14}" text-anchor="middle" font-size="10" fill="var(--nxt-ink-dim, #8b8d98)">${d.label}</text>`;
+ let progress = 0;
+ const duration = 600;
+ const startTime = performance.now();
+
+ function draw(now) {
+ progress = Math.min(1, (now - startTime) / duration);
+ const eased = 1 - Math.pow(1 - progress, 3);
+ const visibleCount = Math.max(1, Math.ceil(eased * points.length));
+
+ ctx.clearRect(0, 0, W, H);
+
+ // Grid
+ ctx.strokeStyle = 'rgba(255,255,255,0.05)';
+ ctx.lineWidth = 0.5;
+ for (let i = 0; i <= 4; i++) {
+ const y = PAD.top + (i / 4) * innerH;
+ ctx.beginPath();
+ ctx.moveTo(PAD.left, y);
+ ctx.lineTo(W - PAD.right, y);
+ ctx.stroke();
+
+ const val = ((4 - i) / 4) * max;
+ ctx.fillStyle = 'rgba(255,255,255,0.3)';
+ ctx.font = '10px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'right';
+ ctx.fillText('$' + (val >= 100 ? val.toFixed(0) : val.toFixed(2)), PAD.left - 8, y + 4);
}
- });
- const gridLines = Array.from({ length: 5 }, (_, i) => {
- const y = Math.round(H - (i / 4) * chartH);
- const val = ((i / 4) * max).toLocaleString('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 });
- return `<line x1="${pad}" x2="${W}" y1="${y}" y2="${y}" stroke="var(--nxt-border, rgba(255,255,255,0.06))" stroke-width="0.5"/><text x="${pad - 6}" y="${y + 3}" text-anchor="end" font-size="10" fill="var(--nxt-ink-dim, #8b8d98)">${val}</text>`;
- }).join('');
+ // X labels
+ const showEvery = Math.max(1, Math.ceil(data.length / 10));
+ ctx.fillStyle = 'rgba(255,255,255,0.3)';
+ ctx.font = '10px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'center';
+ data.forEach((d, i) => {
+ if (i % showEvery === 0 && i < visibleCount) {
+ ctx.fillText(d.label, points[i].x, H - 6);
+ }
+ });
+
+ const visible = points.slice(0, visibleCount);
+ if (visible.length >= 2) {
+ // Gradient fill
+ const gradient = ctx.createLinearGradient(0, PAD.top, 0, PAD.top + innerH);
+ gradient.addColorStop(0, 'rgba(74, 222, 128, 0.2)');
+ gradient.addColorStop(1, 'rgba(74, 222, 128, 0)');
+
+ ctx.beginPath();
+ ctx.moveTo(visible[0].x, PAD.top + innerH);
+ visible.forEach(p => ctx.lineTo(p.x, p.y));
+ ctx.lineTo(visible[visible.length - 1].x, PAD.top + innerH);
+ ctx.closePath();
+ ctx.fillStyle = gradient;
+ ctx.fill();
+
+ // Smooth line
+ ctx.beginPath();
+ ctx.moveTo(visible[0].x, visible[0].y);
+ for (let i = 1; i < visible.length; i++) {
+ const prev = visible[i - 1];
+ const cur = visible[i];
+ const cpx = (prev.x + cur.x) / 2;
+ ctx.bezierCurveTo(cpx, prev.y, cpx, cur.y, cur.x, cur.y);
+ }
+ ctx.strokeStyle = '#4ade80';
+ ctx.lineWidth = 2;
+ ctx.stroke();
+
+ // End dot
+ const last = visible[visible.length - 1];
+ ctx.beginPath();
+ ctx.arc(last.x, last.y, 4, 0, Math.PI * 2);
+ ctx.fillStyle = '#4ade80';
+ ctx.fill();
+ ctx.strokeStyle = 'rgba(0,0,0,0.3)';
+ ctx.lineWidth = 1;
+ ctx.stroke();
+ } else if (visible.length === 1) {
+ ctx.beginPath();
+ ctx.arc(visible[0].x, visible[0].y, 5, 0, Math.PI * 2);
+ ctx.fillStyle = '#4ade80';
+ ctx.fill();
+ }
- panel.innerHTML = `
- <div class="dn-panel-title">Revenue Over Time</div>
- <svg viewBox="0 0 ${W} ${H + 24}" preserveAspectRatio="xMidYMid meet" class="ana-chart-svg">
- ${gridLines}
- ${bars}
- ${labels}
- </svg>
- `;
- return panel;
+ if (progress < 1) requestAnimationFrame(draw);
+ }
+
+ requestAnimationFrame(draw);
+
+ // Tooltip
+ canvas.addEventListener('mousemove', (e) => {
+ const br = canvas.getBoundingClientRect();
+ const mx = e.clientX - br.left;
+ let closest = 0;
+ let closestDist = Infinity;
+ points.forEach((p, i) => {
+ const d = Math.abs(p.x - mx);
+ if (d < closestDist) { closestDist = d; closest = i; }
+ });
+ const d = data[closest];
+ canvas.title = `${d.label}: $${d.value.toFixed(4)} (${d.count} payments)`;
+ });
}
function formatPeriod(p) {
@@ -189,7 +320,7 @@ function formatPeriod(p) {
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}
-// ── Skill breakdown ───────────────────────────────────────────────────────
+// -- Skill breakdown (horizontal bar chart with Canvas) --
function renderSkillBreakdown(bySkill) {
const panel = document.createElement('div');
@@ -200,33 +331,88 @@ function renderSkillBreakdown(bySkill) {
return panel;
}
- const sorted = [...bySkill].sort((a, b) => Number(b.net_total) - Number(a.net_total)).slice(0, 10);
- const max = Math.max(1, Number(sorted[0]?.net_total ?? 0));
- const colors = ['#6c8aff', '#34d399', '#fbbf24', '#f472b6', '#a78bfa', '#fb923c', '#22d3ee', '#94a3b8'];
-
panel.innerHTML = `
<div class="dn-panel-title">Revenue by Skill</div>
- <div class="ana-skill-list">
- ${sorted.map((s, i) => {
- const pct = Math.round((Number(s.net_total) / max) * 100);
- const color = colors[i % colors.length];
- return `
- <div class="ana-skill-row">
- <div class="ana-skill-name">${esc(s.skill)}</div>
- <div class="ana-skill-bar-wrap">
- <div class="ana-skill-bar" style="width:${pct}%;background:${color}"></div>
- </div>
- <div class="ana-skill-val">${formatUsdc(s.net_total)}</div>
- <div class="ana-skill-count">${Number(s.count).toLocaleString()} tx</div>
- </div>
- `;
- }).join('')}
- </div>
+ <div data-slot="bars" style="position:relative;width:100%;height:200px;margin-top:12px"></div>
`;
+
+ const host = panel.querySelector('[data-slot="bars"]');
+ requestAnimationFrame(() => paintHorizontalBarChart(host, bySkill));
+
return panel;
}
-// ── Agent table ───────────────────────────────────────────────────────────
+function paintHorizontalBarChart(host, bySkill) {
+ host.innerHTML = '';
+ const canvas = document.createElement('canvas');
+ canvas.style.cssText = 'width:100%;height:100%;display:block';
+ host.appendChild(canvas);
+
+ const dpr = window.devicePixelRatio || 1;
+ const rect = host.getBoundingClientRect();
+ canvas.width = Math.round(rect.width * dpr);
+ canvas.height = Math.round(rect.height * dpr);
+ const ctx = canvas.getContext('2d');
+ ctx.scale(dpr, dpr);
+
+ const W = rect.width;
+ const H = rect.height;
+
+ const sorted = [...bySkill].sort((a, b) => Number(b.net_total) - Number(a.net_total)).slice(0, 8);
+ const max = Math.max(1, Number(sorted[0]?.net_total ?? 0));
+ const colors = ['#4ade80', '#fbbf24', '#60a5fa', '#f472b6', '#a78bfa', '#fb923c', '#22d3ee', '#94a3b8'];
+
+ const labelW = 100;
+ const valueW = 70;
+ const barPad = 8;
+ const barAreaW = W - labelW - valueW - barPad * 2;
+ const rowH = Math.min(28, (H - 8) / sorted.length);
+ const gap = 4;
+
+ let progress = 0;
+ const duration = 600;
+ const startTime = performance.now();
+
+ function draw(now) {
+ progress = Math.min(1, (now - startTime) / duration);
+ const eased = 1 - Math.pow(1 - progress, 3);
+
+ ctx.clearRect(0, 0, W, H);
+
+ sorted.forEach((s, i) => {
+ const y = i * (rowH + gap) + 4;
+ const val = Number(s.net_total);
+ const pct = val / max;
+ const barW = Math.max(2, pct * barAreaW * eased);
+ const color = colors[i % colors.length];
+
+ // Label
+ ctx.fillStyle = 'rgba(255,255,255,0.7)';
+ ctx.font = '12px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'left';
+ const label = (s.skill || 'Other').replace(/_/g, ' ');
+ ctx.fillText(label.length > 14 ? label.slice(0, 13) + '...' : label, 0, y + rowH / 2 + 4);
+
+ // Bar
+ ctx.fillStyle = color;
+ ctx.beginPath();
+ ctx.roundRect(labelW + barPad, y, barW, rowH, 4);
+ ctx.fill();
+
+ // Value
+ ctx.fillStyle = 'rgba(255,255,255,0.5)';
+ ctx.font = '11px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'left';
+ ctx.fillText(formatUsdc(val), labelW + barPad + barW + 8, y + rowH / 2 + 4);
+ });
+
+ if (progress < 1) requestAnimationFrame(draw);
+ }
+
+ requestAnimationFrame(draw);
+}
+
+// -- Agent table --
function renderAgentTable(agents, widgets, widgetStats) {
const panel = document.createElement('div');
@@ -253,13 +439,13 @@ function renderAgentTable(agents, widgets, widgetStats) {
const rows = agents.slice(0, 10).map(a => {
const wStats = widgetMap.get(a.avatar_id) || widgetMap.get(a.id) || { views: 0, chats: 0 };
- const convRate = wStats.views > 0 ? ((wStats.chats / wStats.views) * 100).toFixed(1) : '—';
+ const convRate = wStats.views > 0 ? ((wStats.chats / wStats.views) * 100).toFixed(1) : '--';
return `
<tr>
<td class="ana-tbl-name">${esc(a.name || a.slug || 'Unnamed')}</td>
<td>${wStats.views.toLocaleString()}</td>
<td>${wStats.chats.toLocaleString()}</td>
- <td>${convRate}${convRate !== '—' ? '%' : ''}</td>
+ <td>${convRate}${convRate !== '--' ? '%' : ''}</td>
</tr>
`;
});
@@ -276,16 +462,86 @@ function renderAgentTable(agents, widgets, widgetStats) {
return panel;
}
-// ── Funnel ────────────────────────────────────────────────────────────────
+// -- Recent activity table --
+
+async function fetchRecentActivity(agents) {
+ if (!agents.length) return [];
+ const top = agents.slice(0, 5);
+ const lists = await Promise.all(
+ top.map(a =>
+ get(`/api/agents/${encodeURIComponent(a.id)}/payments?direction=received&limit=5`)
+ .then(r => (r?.payments || []).map(p => ({ ...p, _agent: a })))
+ .catch(() => [])
+ )
+ );
+ const merged = lists.flat();
+ merged.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
+ return merged.slice(0, 20);
+}
+
+function renderActivityTable(payments) {
+ const panel = document.createElement('div');
+ panel.className = 'dn-panel';
+
+ if (!payments.length) {
+ panel.innerHTML = `
+ <div class="dn-panel-title">Recent Activity</div>
+ <div class="ana-chart-empty">No revenue events yet. Earnings will appear here as callers use your agents' skills.</div>
+ `;
+ return panel;
+ }
+
+ panel.innerHTML = `
+ <div class="dn-panel-title">Recent Activity</div>
+ <div class="dn-panel-sub" style="margin:2px 0 14px">Latest revenue events from skill calls and API usage.</div>
+ <div style="overflow-x:auto">
+ <table class="ana-tbl" style="min-width:560px">
+ <thead>
+ <tr>
+ <th>Time</th>
+ <th>Skill</th>
+ <th style="text-align:right">Amount</th>
+ <th>Agent</th>
+ <th>Status</th>
+ </tr>
+ </thead>
+ <tbody>
+ ${payments.map(p => {
+ const amount = p.amount ? formatUsdc(p.amount) : '--';
+ const skill = p.skill_name || p.memo?.slice(0, 40) || 'API call';
+ const agent = p._agent?.name || 'Agent';
+ const status = (p.status || 'pending').toLowerCase();
+ const tag = status === 'confirmed' || status === 'completed' || status === 'settled'
+ ? '<span class="dn-tag success">Settled</span>'
+ : status === 'failed'
+ ? '<span class="dn-tag danger">Failed</span>'
+ : '<span class="dn-tag warn">Pending</span>';
+ return `
+ <tr>
+ <td style="color:var(--nxt-ink-dim);white-space:nowrap">${esc(relTime(p.created_at))}</td>
+ <td style="font-weight:500">${esc(skill)}</td>
+ <td style="text-align:right;font-variant-numeric:tabular-nums;color:var(--nxt-success)">${esc(amount)}</td>
+ <td style="color:var(--nxt-ink-dim)">${esc(agent)}</td>
+ <td>${tag}</td>
+ </tr>`;
+ }).join('')}
+ </tbody>
+ </table>
+ </div>
+ `;
+ return panel;
+}
+
+// -- Funnel --
function renderFunnel({ totalViews, totalChats, revPayments }) {
const panel = document.createElement('div');
panel.className = 'dn-panel ana-funnel-panel';
const steps = [
- { label: 'Widget Views', value: totalViews, color: '#6c8aff' },
+ { label: 'Widget Views', value: totalViews, color: '#60a5fa' },
{ label: 'Conversations', value: totalChats, color: '#a78bfa' },
- { label: 'Payments', value: revPayments, color: '#34d399' },
+ { label: 'Payments', value: revPayments, color: '#4ade80' },
];
const max = Math.max(1, steps[0].value);
@@ -314,7 +570,7 @@ function renderFunnel({ totalViews, totalChats, revPayments }) {
return panel;
}
-// ── Range bar ─────────────────────────────────────────────────────────────
+// -- Range bar --
function renderRangeBar(root) {
const bar = document.createElement('div');
@@ -325,7 +581,7 @@ function renderRangeBar(root) {
return bar;
}
-// ── Helpers ───────────────────────────────────────────────────────────────
+// -- Helpers --
function renderTwoCol(left, right) {
const wrap = document.createElement('div');
@@ -335,7 +591,7 @@ function renderTwoCol(left, right) {
return wrap;
}
-// ── Styles ────────────────────────────────────────────────────────────────
+// -- Styles --
function injectStyles() {
if (document.getElementById('ana-styles')) return;
@@ -345,52 +601,41 @@ function injectStyles() {
.ana-root { display: flex; flex-direction: column; gap: 18px; }
.ana-range-bar { display: flex; gap: 6px; margin-bottom: 2px; }
-.ana-range-btn { padding: 6px 16px; border: 1px solid var(--nxt-border, rgba(255,255,255,0.07)); border-radius: 8px; background: none; color: var(--nxt-ink-dim, #8b8d98); font: inherit; font-size: 12px; font-weight: 500; cursor: pointer; transition: background 0.12s, color 0.12s, border-color 0.12s; }
-.ana-range-btn:hover { background: var(--nxt-bg-2, #1a1b22); color: var(--nxt-ink, #e4e5ea); }
-.ana-range-btn.is-active { background: rgba(108,138,255,0.12); color: #6c8aff; border-color: rgba(108,138,255,0.3); }
+.ana-range-btn { padding: 6px 16px; border: 1px solid var(--nxt-stroke); border-radius: 8px; background: none; color: var(--nxt-ink-dim); font: inherit; font-size: 12px; font-weight: 500; cursor: pointer; transition: background 0.12s, color 0.12s, border-color 0.12s; }
+.ana-range-btn:hover { background: rgba(255,255,255,0.04); color: var(--nxt-ink); }
+.ana-range-btn.is-active { background: rgba(74,222,128,0.12); color: #4ade80; border-color: rgba(74,222,128,0.3); }
.ana-kpi-row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; }
.ana-kpi { padding: 18px 20px; }
-.ana-kpi-label { font-size: 12px; color: var(--nxt-ink-dim, #8b8d98); margin-bottom: 4px; }
-.ana-kpi-value { font-size: 26px; font-weight: 700; letter-spacing: -0.02em; }
-.ana-kpi-sub { font-size: 12px; color: var(--nxt-ink-faint, #5a5c68); margin-top: 2px; }
+.ana-kpi-label { font-size: 12px; color: var(--nxt-ink-dim); margin-bottom: 4px; text-transform: uppercase; letter-spacing: 0.04em; font-weight: 500; }
+.ana-kpi-value { font-size: 26px; font-weight: 700; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
+.ana-kpi-sub { font-size: 12px; color: var(--nxt-ink-fade); margin-top: 2px; }
.ana-chart-panel { padding: 20px; }
-.ana-chart-svg { width: 100%; height: auto; margin-top: 12px; }
-.ana-chart-empty { padding: 40px 0; text-align: center; color: var(--nxt-ink-dim, #8b8d98); font-size: 13px; }
-.ana-chart-empty a { color: #6c8aff; }
+.ana-chart-empty { padding: 40px 0; text-align: center; color: var(--nxt-ink-dim); font-size: 13px; }
+.ana-chart-empty a { color: var(--nxt-success); }
.ana-two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
-.ana-skill-list { display: flex; flex-direction: column; gap: 8px; margin-top: 12px; }
-.ana-skill-row { display: grid; grid-template-columns: 120px 1fr 70px 60px; gap: 10px; align-items: center; font-size: 13px; }
-.ana-skill-name { font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.ana-skill-bar-wrap { height: 8px; background: var(--nxt-bg-2, #1a1b22); border-radius: 4px; overflow: hidden; }
-.ana-skill-bar { height: 100%; border-radius: 4px; transition: width 0.3s ease; }
-.ana-skill-val { text-align: right; font-weight: 600; }
-.ana-skill-count { text-align: right; color: var(--nxt-ink-dim, #8b8d98); font-size: 12px; }
-
.ana-tbl-wrap { overflow-x: auto; margin-top: 12px; }
.ana-tbl { width: 100%; border-collapse: collapse; font-size: 13px; }
-.ana-tbl th { text-align: left; font-weight: 500; color: var(--nxt-ink-dim, #8b8d98); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; padding: 8px 10px; border-bottom: 1px solid var(--nxt-border, rgba(255,255,255,0.07)); }
-.ana-tbl td { padding: 10px; border-bottom: 1px solid var(--nxt-border, rgba(255,255,255,0.04)); }
+.ana-tbl th { text-align: left; font-weight: 500; color: var(--nxt-ink-dim); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; padding: 8px 10px; border-bottom: 1px solid var(--nxt-stroke); }
+.ana-tbl td { padding: 10px; border-bottom: 1px solid rgba(255,255,255,0.04); }
.ana-tbl-name { font-weight: 500; max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-.ana-tbl tbody tr:hover { background: var(--nxt-bg-2, rgba(255,255,255,0.02)); }
+.ana-tbl tbody tr:hover { background: rgba(255,255,255,0.02); }
.ana-funnel-panel { padding: 20px; }
.ana-funnel { display: flex; flex-direction: column; gap: 14px; margin-top: 16px; }
.ana-funnel-step { display: grid; grid-template-columns: 120px 1fr 70px 80px; gap: 10px; align-items: center; }
.ana-funnel-label { font-size: 13px; font-weight: 500; }
-.ana-funnel-bar-wrap { height: 24px; background: var(--nxt-bg-2, #1a1b22); border-radius: 6px; overflow: hidden; }
+.ana-funnel-bar-wrap { height: 24px; background: rgba(255,255,255,0.03); border-radius: 6px; overflow: hidden; }
.ana-funnel-bar { height: 100%; border-radius: 6px; transition: width 0.4s ease; }
.ana-funnel-val { text-align: right; font-weight: 600; font-size: 15px; }
-.ana-funnel-drop { font-size: 11px; color: rgba(244,114,182,0.8); text-align: right; }
+.ana-funnel-drop { font-size: 11px; color: rgba(248,113,113,0.8); text-align: right; }
@media (max-width: 900px) {
.ana-kpi-row { grid-template-columns: repeat(2, 1fr); }
.ana-two-col { grid-template-columns: 1fr; }
- .ana-skill-row { grid-template-columns: 100px 1fr 60px; }
- .ana-skill-count { display: none; }
.ana-funnel-step { grid-template-columns: 100px 1fr 60px; }
.ana-funnel-drop { display: none; }
}
diff --git a/src/dashboard-next/pages/developers.js b/src/dashboard-next/pages/developers.js
index eaa8428d1..2300530e0 100644
--- a/src/dashboard-next/pages/developers.js
+++ b/src/dashboard-next/pages/developers.js
@@ -846,6 +846,390 @@ curl -X POST -H "Content-Type: application/json" \\
root.appendChild(el);
}
+// ── Usage Tab ──────────────────────────────────────────────────────────
+
+function renderUsageTab(root) {
+ const el = document.createElement('div');
+ el.className = 'dev-usage-tab';
+
+ const d = usageData || {};
+ const req = d.requests || {};
+ const keys = d.api_keys || {};
+ const wh = d.webhooks || {};
+ const x402 = d.x402 || {};
+ const timeseries = d.timeseries || [];
+ const topActions = d.top_actions || [];
+
+ const successRate = req.total > 0 ? (100 - (req.error_rate || 0)).toFixed(1) : '100.0';
+ const whSuccessRate = wh.total_deliveries > 0
+ ? ((wh.succeeded / wh.total_deliveries) * 100).toFixed(1)
+ : '100.0';
+
+ el.innerHTML = `
+ <div class="dev-usage-header">
+ <div>
+ <h2 class="dev-section-title">Usage & Metrics</h2>
+ <p class="dev-section-desc">Platform activity, API usage, and delivery stats across your integrations.</p>
+ </div>
+ <div class="dev-usage-range">
+ ${[7, 30, 90].map(n => `<button class="dev-usage-range-btn${n === usageDays ? ' is-active' : ''}" data-days="${n}">${n}d</button>`).join('')}
+ </div>
+ </div>
+
+ <div class="dev-usage-kpis">
+ <div class="dn-panel dev-usage-kpi">
+ <div class="dev-usage-kpi-icon" style="background:rgba(108,138,255,0.12);color:#6c8aff">
+ <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M3 17V7l4 3 3-6 4 4 3-3v12H3z"/></svg>
+ </div>
+ <div class="dev-usage-kpi-body">
+ <div class="dev-usage-kpi-value">${(req.total || 0).toLocaleString()}</div>
+ <div class="dev-usage-kpi-label">API Requests</div>
+ </div>
+ </div>
+ <div class="dn-panel dev-usage-kpi">
+ <div class="dev-usage-kpi-icon" style="background:rgba(52,211,153,0.12);color:#34d399">
+ <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M5 10l3 3 7-7"/></svg>
+ </div>
+ <div class="dev-usage-kpi-body">
+ <div class="dev-usage-kpi-value">${successRate}%</div>
+ <div class="dev-usage-kpi-label">Success Rate</div>
+ </div>
+ </div>
+ <div class="dn-panel dev-usage-kpi">
+ <div class="dev-usage-kpi-icon" style="background:rgba(167,139,250,0.12);color:#a78bfa">
+ <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6"><rect x="5" y="2" width="10" height="10" rx="2"/><circle cx="8" cy="6.5" r="1"/><circle cx="12" cy="6.5" r="1"/><path d="M3 14l2-2h10l2 2v3a1 1 0 01-1 1H4a1 1 0 01-1-1v-3z"/></svg>
+ </div>
+ <div class="dev-usage-kpi-body">
+ <div class="dev-usage-kpi-value">${keys.active_keys || 0}</div>
+ <div class="dev-usage-kpi-label">Active API Keys</div>
+ </div>
+ </div>
+ <div class="dn-panel dev-usage-kpi">
+ <div class="dev-usage-kpi-icon" style="background:rgba(251,191,36,0.12);color:#fbbf24">
+ <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="10" cy="10" r="6.5"/><path d="M10 6v8M7.5 8h4a1.5 1.5 0 010 3H8.5a1.5 1.5 0 000 3h4"/></svg>
+ </div>
+ <div class="dev-usage-kpi-body">
+ <div class="dev-usage-kpi-value">${x402.payments || 0}</div>
+ <div class="dev-usage-kpi-label">x402 Payments</div>
+ </div>
+ </div>
+ </div>
+
+ <div class="dn-panel dev-usage-chart-panel">
+ <div class="dev-panel-title">Request Volume</div>
+ <p class="dev-panel-desc">API requests per day over the last ${usageDays} days</p>
+ <div class="dev-usage-chart" id="usage-chart"></div>
+ </div>
+
+ <div class="dev-usage-two-col">
+ <div class="dn-panel dev-usage-actions-panel">
+ <div class="dev-panel-title">Top Actions</div>
+ <p class="dev-panel-desc">Most-called API actions this period</p>
+ <div id="usage-actions"></div>
+ </div>
+ <div class="dn-panel dev-usage-delivery-panel">
+ <div class="dev-panel-title">Webhook Health</div>
+ <p class="dev-panel-desc">Delivery success rate for your webhooks</p>
+ <div class="dev-usage-delivery-stats">
+ <div class="dev-usage-delivery-ring" id="delivery-ring"></div>
+ <div class="dev-usage-delivery-breakdown">
+ <div class="dev-usage-delivery-row">
+ <span class="dev-usage-dot" style="background:#34d399"></span>
+ <span>Succeeded</span>
+ <strong>${(wh.succeeded || 0).toLocaleString()}</strong>
+ </div>
+ <div class="dev-usage-delivery-row">
+ <span class="dev-usage-dot" style="background:#f87171"></span>
+ <span>Failed</span>
+ <strong>${(wh.failed || 0).toLocaleString()}</strong>
+ </div>
+ <div class="dev-usage-delivery-row">
+ <span class="dev-usage-dot" style="background:var(--nxt-ink-dim)"></span>
+ <span>Total</span>
+ <strong>${(wh.total_deliveries || 0).toLocaleString()}</strong>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ `;
+
+ root.appendChild(el);
+
+ renderUsageChart(el.querySelector('#usage-chart'), timeseries);
+ renderTopActions(el.querySelector('#usage-actions'), topActions);
+ renderDeliveryRing(el.querySelector('#delivery-ring'), wh);
+
+ el.querySelector('.dev-usage-range').addEventListener('click', async (e) => {
+ const btn = e.target.closest('.dev-usage-range-btn');
+ if (!btn) return;
+ usageDays = Number(btn.dataset.days);
+ el.querySelector('.dev-usage-range').querySelectorAll('.dev-usage-range-btn').forEach(b =>
+ b.classList.toggle('is-active', Number(b.dataset.days) === usageDays)
+ );
+ try {
+ usageData = await get(`/api/developer/usage?days=${usageDays}`);
+ } catch { /* keep stale data */ }
+ const content = document.querySelector('[data-slot="content"]');
+ renderActiveTab(content);
+ });
+}
+
+function renderUsageChart(container, timeseries) {
+ if (!timeseries.length) {
+ container.innerHTML = `<div class="dev-usage-chart-empty">
+ <svg width="40" height="40" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.2" opacity="0.25"><path d="M3 17V7l4 3 3-6 4 4 3-3v12H3z"/></svg>
+ <span>No API activity in this period. <a href="/dashboard/api">Get your API key</a> to start building.</span>
+ </div>`;
+ return;
+ }
+
+ const data = timeseries.map(p => ({
+ label: new Date(p.day).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
+ value: p.requests,
+ }));
+
+ const max = Math.max(1, ...data.map(d => d.value));
+ const W = 780, H = 180, pad = 48, barGap = 3;
+ const barW = Math.max(4, (W - pad * 2) / data.length - barGap);
+ const chartH = H - 20;
+
+ let bars = '';
+ let labels = '';
+ const showEvery = Math.max(1, Math.ceil(data.length / 10));
+
+ data.forEach((d, i) => {
+ const x = pad + i * (barW + barGap);
+ const h = Math.max(1, (d.value / max) * chartH);
+ const y = H - h;
+ bars += `<rect x="${x}" y="${y}" width="${barW}" height="${h}" rx="2" fill="var(--nxt-accent,#6c8aff)" opacity="0.75"><title>${d.label}: ${d.value.toLocaleString()} requests</title></rect>`;
+ if (i % showEvery === 0) {
+ labels += `<text x="${x + barW / 2}" y="${H + 14}" text-anchor="middle" font-size="10" fill="var(--nxt-ink-dim,#8b8d98)">${d.label}</text>`;
+ }
+ });
+
+ const gridLines = Array.from({ length: 5 }, (_, i) => {
+ const y = Math.round(H - (i / 4) * chartH);
+ const val = Math.round((i / 4) * max).toLocaleString();
+ return `<line x1="${pad}" x2="${W}" y1="${y}" y2="${y}" stroke="var(--nxt-border,rgba(255,255,255,0.06))" stroke-width="0.5"/><text x="${pad - 6}" y="${y + 3}" text-anchor="end" font-size="10" fill="var(--nxt-ink-dim,#8b8d98)">${val}</text>`;
+ }).join('');
+
+ container.innerHTML = `<svg viewBox="0 0 ${W} ${H + 24}" preserveAspectRatio="xMidYMid meet" style="width:100%;height:auto">${gridLines}${bars}${labels}</svg>`;
+}
+
+function renderTopActions(container, actions) {
+ if (!actions.length) {
+ container.innerHTML = `<div class="dev-usage-chart-empty" style="padding:24px 0"><span>No actions recorded yet</span></div>`;
+ return;
+ }
+
+ const max = Math.max(1, actions[0].count);
+ const colors = ['#6c8aff', '#34d399', '#fbbf24', '#f472b6', '#a78bfa', '#fb923c', '#22d3ee', '#94a3b8', '#818cf8', '#4ade80'];
+
+ container.innerHTML = `<div class="dev-usage-actions-list">
+ ${actions.map((a, i) => {
+ const pct = Math.round((a.count / max) * 100);
+ const color = colors[i % colors.length];
+ return `<div class="dev-usage-action-row">
+ <div class="dev-usage-action-name">${esc(a.action)}</div>
+ <div class="dev-usage-action-bar-wrap">
+ <div class="dev-usage-action-bar" style="width:${pct}%;background:${color}"></div>
+ </div>
+ <div class="dev-usage-action-count">${a.count.toLocaleString()}</div>
+ </div>`;
+ }).join('')}
+ </div>`;
+}
+
+function renderDeliveryRing(container, wh) {
+ const total = wh.total_deliveries || 0;
+ const succeeded = wh.succeeded || 0;
+ const pct = total > 0 ? (succeeded / total) : 1;
+ const radius = 54;
+ const circ = 2 * Math.PI * radius;
+ const offset = circ * (1 - pct);
+
+ const color = pct >= 0.95 ? '#34d399' : pct >= 0.8 ? '#fbbf24' : '#f87171';
+ const label = total > 0 ? `${(pct * 100).toFixed(1)}%` : '—';
+
+ container.innerHTML = `
+ <svg width="130" height="130" viewBox="0 0 130 130">
+ <circle cx="65" cy="65" r="${radius}" fill="none" stroke="var(--nxt-bg-1,#111)" stroke-width="10"/>
+ <circle cx="65" cy="65" r="${radius}" fill="none" stroke="${color}" stroke-width="10"
+ stroke-dasharray="${circ}" stroke-dashoffset="${offset}"
+ stroke-linecap="round" transform="rotate(-90 65 65)"
+ style="transition:stroke-dashoffset 0.6s ease"/>
+ <text x="65" y="62" text-anchor="middle" font-size="22" font-weight="700" fill="var(--nxt-ink,#e4e5ea)">${label}</text>
+ <text x="65" y="80" text-anchor="middle" font-size="11" fill="var(--nxt-ink-dim,#8b8d98)">success</text>
+ </svg>
+ `;
+}
+
+// ── Changelog Tab ──────────────────────────────────────────────────────────
+
+const CHANGELOG = [
+ {
+ date: '2026-05-27',
+ version: '1.5.1',
+ category: 'api',
+ title: 'Developer Hub & Webhook API',
+ description: 'New Developer Hub with interactive Render API playground, webhook management, delivery logs with retry tracking, and cross-platform SDK guides. Standard Webhooks signature format (HMAC-SHA256).',
+ tags: ['Render API', 'Webhooks', 'SDKs'],
+ },
+ {
+ date: '2026-05-25',
+ version: '1.5.0',
+ category: 'platform',
+ title: 'Avatar Render API',
+ description: 'Public API to render any avatar as PNG/JPEG/WebP with scene presets (full-body, upper-body, portrait, headshot), custom backgrounds, and CDN caching. Up to 2048px resolution.',
+ tags: ['API', 'Avatars', 'CDN'],
+ },
+ {
+ date: '2026-05-22',
+ version: '1.4.9',
+ category: 'dashboard',
+ title: 'Analytics & Conversion Funnel',
+ description: 'Revenue charts, per-agent performance tables, skill breakdown, and conversion funnel (views → conversations → payments) with configurable time ranges.',
+ tags: ['Analytics', 'Revenue', 'Dashboard'],
+ },
+ {
+ date: '2026-05-19',
+ version: '1.4.8',
+ category: 'platform',
+ title: 'x402 Payment Receipts & SKU Catalog',
+ description: 'Stripe-style checkout with x402 USDC micropayments. Receipt ledger, SKU catalog management, and pay-by-name resolution (@username, *.sol, base58).',
+ tags: ['x402', 'Payments', 'USDC'],
+ },
+ {
+ date: '2026-05-15',
+ version: '1.4.7',
+ category: 'sdk',
+ title: 'Web Component Embed Update',
+ description: 'Updated <agent-3d> web component with 5 widget variants: turntable, animation gallery, talking agent, ERC-8004 passport, and hotspot tour. Widget Studio for WYSIWYG configuration.',
+ tags: ['Web Component', 'Embed', 'Studio'],
+ },
+ {
+ date: '2026-05-10',
+ version: '1.4.6',
+ category: 'platform',
+ title: 'Agent Marketplace Enhancements',
+ description: 'Infinite scroll with intersection observers, category filtering, search, and rating-based sorting. IndexedDB poster caching for instant thumbnails on repeat visits.',
+ tags: ['Marketplace', 'Performance', 'UX'],
+ },
+ {
+ date: '2026-05-05',
+ version: '1.4.5',
+ category: 'infrastructure',
+ title: 'On-Chain Identity (ERC-8004)',
+ description: 'Multi-chain agent identity with IdentityRegistry, ReputationRegistry, and ValidationRegistry on Solana. EIP-712 delegated signer wallets, signed action history with cryptographic proof.',
+ tags: ['ERC-8004', 'Solana', 'Identity'],
+ },
+ {
+ date: '2026-04-28',
+ version: '1.4.4',
+ category: 'api',
+ title: 'Agent Runtime & Tool Loop',
+ description: 'Sophisticated tool-loop architecture with up to 8 iterations per turn, signal aborts, and structured streaming. Claude (Anthropic) integration with ElevenLabs TTS and Web Speech STT.',
+ tags: ['Agent Runtime', 'LLM', 'Voice'],
+ },
+ {
+ date: '2026-04-20',
+ version: '1.4.3',
+ category: 'dashboard',
+ title: 'Portfolio & Token Management',
+ description: 'Crypto portfolio with real-time balances, token launch via Pump.fun, and DCA strategy configuration. Live price feeds from Solana RPC.',
+ tags: ['Portfolio', 'Tokens', 'DeFi'],
+ },
+ {
+ date: '2026-04-12',
+ version: '1.4.2',
+ category: 'sdk',
+ title: 'Character Studio & Pose System',
+ description: 'In-browser 3D character builder (MIT fork of m3-org/CharacterStudio) with Pose Studio for authoring exportable avatar poses. GLB export with animations and morph targets.',
+ tags: ['Character Studio', 'Poses', 'GLB'],
+ },
+];
+
+const CATEGORY_META = {
+ api: { label: 'API', color: '#6c8aff' },
+ platform: { label: 'Platform', color: '#34d399' },
+ dashboard: { label: 'Dashboard', color: '#a78bfa' },
+ sdk: { label: 'SDK', color: '#fbbf24' },
+ infrastructure: { label: 'Infrastructure', color: '#f472b6' },
+};
+
+function renderChangelogTab(root) {
+ const el = document.createElement('div');
+ el.className = 'dev-changelog-tab';
+
+ el.innerHTML = `
+ <div class="dev-changelog-header">
+ <div>
+ <h2 class="dev-section-title">Changelog</h2>
+ <p class="dev-section-desc">Recent platform updates, API changes, and new features. Follow our development velocity.</p>
+ </div>
+ <div class="dev-changelog-filters" id="changelog-filters">
+ <button class="dev-changelog-filter is-active" data-filter="all">All</button>
+ ${Object.entries(CATEGORY_META).map(([key, meta]) =>
+ `<button class="dev-changelog-filter" data-filter="${key}"><span class="dev-usage-dot" style="background:${meta.color}"></span>${meta.label}</button>`
+ ).join('')}
+ </div>
+ </div>
+ <div class="dev-changelog-timeline" id="changelog-timeline"></div>
+ `;
+
+ root.appendChild(el);
+
+ let filter = 'all';
+ renderChangelogTimeline(el.querySelector('#changelog-timeline'), filter);
+
+ el.querySelector('#changelog-filters').addEventListener('click', (e) => {
+ const btn = e.target.closest('.dev-changelog-filter');
+ if (!btn) return;
+ filter = btn.dataset.filter;
+ el.querySelectorAll('.dev-changelog-filter').forEach(b => b.classList.toggle('is-active', b === btn));
+ renderChangelogTimeline(el.querySelector('#changelog-timeline'), filter);
+ });
+}
+
+function renderChangelogTimeline(container, filter) {
+ const entries = filter === 'all' ? CHANGELOG : CHANGELOG.filter(e => e.category === filter);
+
+ if (!entries.length) {
+ container.innerHTML = `<div class="dn-panel dev-changelog-empty">
+ <span>No updates in this category yet.</span>
+ </div>`;
+ return;
+ }
+
+ container.innerHTML = entries.map((entry, i) => {
+ const meta = CATEGORY_META[entry.category] || CATEGORY_META.platform;
+ const dateStr = new Date(entry.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
+ return `
+ <div class="dev-changelog-entry${i === 0 ? ' is-latest' : ''}" style="--entry-delay:${i * 40}ms">
+ <div class="dev-changelog-line">
+ <div class="dev-changelog-dot" style="background:${meta.color}"></div>
+ </div>
+ <div class="dn-panel dev-changelog-card">
+ <div class="dev-changelog-card-header">
+ <div class="dev-changelog-card-meta">
+ <span class="dn-tag" style="background:${meta.color}20;color:${meta.color};border-color:${meta.color}40">${meta.label}</span>
+ <span class="dev-changelog-version">v${esc(entry.version)}</span>
+ <span class="dev-changelog-date">${dateStr}</span>
+ </div>
+ ${i === 0 ? '<span class="dn-tag success" style="font-size:10px">Latest</span>' : ''}
+ </div>
+ <h3 class="dev-changelog-title">${esc(entry.title)}</h3>
+ <p class="dev-changelog-desc">${esc(entry.description)}</p>
+ <div class="dev-changelog-tags">
+ ${entry.tags.map(t => `<span class="dev-badge">${esc(t)}</span>`).join('')}
+ </div>
+ </div>
+ </div>
+ `;
+ }).join('');
+}
+
// ── Utilities ───────────────────────────────────────────────────────────────
function copyText(text, btn) {
@@ -1200,6 +1584,183 @@ function injectStyles() {
.dn-btn.ghost.danger:hover {
background:rgba(248,113,113,0.1);
}
+
+/* ── Usage Tab ───────────────────────────────────────────── */
+.dev-usage-header {
+ display:flex; align-items:flex-start; justify-content:space-between;
+ gap:16px; flex-wrap:wrap; margin-bottom:20px;
+}
+.dev-usage-range {
+ display:flex; gap:4px; background:var(--nxt-bg-2); border-radius:8px; padding:3px;
+}
+.dev-usage-range-btn {
+ padding:6px 16px; border:none; background:none;
+ color:var(--nxt-ink-dim); font:inherit; font-size:12px; font-weight:600;
+ border-radius:6px; cursor:pointer; transition:all 0.15s;
+}
+.dev-usage-range-btn:hover { color:var(--nxt-ink); }
+.dev-usage-range-btn.is-active {
+ background:rgba(108,138,255,0.15); color:#6c8aff;
+}
+
+.dev-usage-kpis {
+ display:grid; grid-template-columns:repeat(4,1fr); gap:14px; margin-bottom:20px;
+}
+@media (max-width:900px) { .dev-usage-kpis { grid-template-columns:repeat(2,1fr); } }
+@media (max-width:500px) { .dev-usage-kpis { grid-template-columns:1fr; } }
+
+.dev-usage-kpi {
+ padding:20px; display:flex; align-items:center; gap:16px;
+}
+.dev-usage-kpi-icon {
+ width:44px; height:44px; border-radius:12px;
+ display:flex; align-items:center; justify-content:center; flex-shrink:0;
+}
+.dev-usage-kpi-value {
+ font-size:26px; font-weight:700; letter-spacing:-0.02em;
+}
+.dev-usage-kpi-label {
+ font-size:12px; color:var(--nxt-ink-dim); margin-top:2px;
+}
+
+.dev-usage-chart-panel { padding:24px; margin-bottom:20px; }
+.dev-usage-chart-empty {
+ display:flex; flex-direction:column; align-items:center; gap:12px;
+ padding:40px 20px; text-align:center; color:var(--nxt-ink-dim); font-size:13px;
+}
+.dev-usage-chart-empty a { color:#6c8aff; }
+
+.dev-usage-two-col {
+ display:grid; grid-template-columns:1fr 1fr; gap:14px;
+}
+@media (max-width:900px) { .dev-usage-two-col { grid-template-columns:1fr; } }
+
+.dev-usage-actions-panel { padding:20px; }
+.dev-usage-actions-list { display:flex; flex-direction:column; gap:8px; margin-top:12px; }
+.dev-usage-action-row {
+ display:grid; grid-template-columns:130px 1fr 60px; gap:10px;
+ align-items:center; font-size:13px;
+}
+.dev-usage-action-name {
+ font-weight:500; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
+ font-family:ui-monospace,'SF Mono',monospace; font-size:12px;
+}
+.dev-usage-action-bar-wrap {
+ height:8px; background:var(--nxt-bg-2); border-radius:4px; overflow:hidden;
+}
+.dev-usage-action-bar { height:100%; border-radius:4px; transition:width 0.3s ease; }
+.dev-usage-action-count { text-align:right; font-weight:600; font-size:13px; }
+
+.dev-usage-delivery-panel { padding:20px; }
+.dev-usage-delivery-stats {
+ display:flex; align-items:center; gap:24px; margin-top:16px;
+}
+.dev-usage-delivery-breakdown { display:flex; flex-direction:column; gap:10px; }
+.dev-usage-delivery-row {
+ display:flex; align-items:center; gap:8px; font-size:13px;
+}
+.dev-usage-delivery-row strong { margin-left:auto; }
+.dev-usage-dot {
+ width:8px; height:8px; border-radius:50%; flex-shrink:0;
+}
+
+/* ── Webhook Delivery Drill-down ─────────────────────────── */
+.dev-wh-deliveries { margin-top:12px; }
+.dev-wh-view-btn {
+ font-size:12px; padding:4px 12px; border:1px solid var(--nxt-stroke);
+ background:none; color:var(--nxt-ink-dim); border-radius:6px;
+ cursor:pointer; transition:all 0.15s; font:inherit;
+}
+.dev-wh-view-btn:hover { color:var(--nxt-ink); border-color:var(--nxt-stroke-strong); }
+.dev-wh-delivery-list { margin-top:8px; }
+.dev-wh-delivery-item {
+ display:grid; grid-template-columns:80px 1fr 60px 100px; gap:10px;
+ padding:8px 12px; font-size:12px; align-items:center;
+ border-bottom:1px solid var(--nxt-border,rgba(255,255,255,0.04));
+}
+.dev-wh-delivery-item:first-child { border-top:1px solid var(--nxt-border,rgba(255,255,255,0.04)); }
+.dev-wh-delivery-event {
+ font-family:ui-monospace,'SF Mono',monospace; font-size:11px;
+ white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
+}
+.dev-wh-delivery-status {
+ display:inline-flex; align-items:center; gap:4px; font-weight:600;
+}
+.dev-wh-delivery-status.ok { color:#34d399; }
+.dev-wh-delivery-status.fail { color:#f87171; }
+.dev-wh-delivery-status.pending { color:#fbbf24; }
+
+/* ── Changelog Tab ───────────────────────────────────────── */
+.dev-changelog-header {
+ display:flex; align-items:flex-start; justify-content:space-between;
+ gap:16px; flex-wrap:wrap; margin-bottom:24px;
+}
+.dev-changelog-filters {
+ display:flex; gap:4px; flex-wrap:wrap;
+}
+.dev-changelog-filter {
+ display:inline-flex; align-items:center; gap:6px;
+ padding:6px 14px; border:1px solid var(--nxt-border,rgba(255,255,255,0.07));
+ border-radius:8px; background:none; color:var(--nxt-ink-dim);
+ font:inherit; font-size:12px; font-weight:500; cursor:pointer;
+ transition:all 0.15s;
+}
+.dev-changelog-filter:hover { color:var(--nxt-ink); background:var(--nxt-bg-2); }
+.dev-changelog-filter.is-active {
+ background:rgba(108,138,255,0.12); color:#6c8aff;
+ border-color:rgba(108,138,255,0.3);
+}
+
+.dev-changelog-timeline { position:relative; }
+.dev-changelog-entry {
+ display:grid; grid-template-columns:20px 1fr; gap:16px;
+ animation:dev-fadeIn 0.3s ease backwards;
+ animation-delay:var(--entry-delay,0ms);
+}
+.dev-changelog-line {
+ display:flex; flex-direction:column; align-items:center; position:relative;
+}
+.dev-changelog-line::after {
+ content:''; position:absolute; top:16px; bottom:0;
+ width:2px; background:var(--nxt-border,rgba(255,255,255,0.07));
+}
+.dev-changelog-entry:last-child .dev-changelog-line::after { display:none; }
+.dev-changelog-dot {
+ width:12px; height:12px; border-radius:50%; flex-shrink:0;
+ margin-top:20px; z-index:1;
+ box-shadow:0 0 0 3px var(--nxt-bg-base,#0e0f14);
+}
+
+.dev-changelog-card {
+ padding:20px 24px; margin-bottom:16px;
+}
+.dev-changelog-card-header {
+ display:flex; align-items:center; justify-content:space-between; gap:8px;
+ margin-bottom:8px;
+}
+.dev-changelog-card-meta {
+ display:flex; align-items:center; gap:8px; flex-wrap:wrap;
+}
+.dev-changelog-version {
+ font-size:12px; font-weight:600; color:var(--nxt-ink-dim);
+ font-family:ui-monospace,'SF Mono',monospace;
+}
+.dev-changelog-date {
+ font-size:12px; color:var(--nxt-ink-faint,#5a5c68);
+}
+.dev-changelog-title {
+ font-size:16px; font-weight:600; margin:0 0 6px; letter-spacing:-0.01em;
+}
+.dev-changelog-desc {
+ font-size:13px; color:var(--nxt-ink-dim); line-height:1.6; margin:0 0 12px;
+ max-width:640px;
+}
+.dev-changelog-tags { display:flex; flex-wrap:wrap; gap:6px; }
+
+.dev-changelog-empty {
+ display:flex; align-items:center; justify-content:center;
+ padding:40px; color:var(--nxt-ink-dim); font-size:13px;
+}
`;
document.head.appendChild(style);
}
diff --git a/src/dashboard-next/pages/three-token.js b/src/dashboard-next/pages/three-token.js
index 3ce677fca..89c3053ae 100644
--- a/src/dashboard-next/pages/three-token.js
+++ b/src/dashboard-next/pages/three-token.js
@@ -527,8 +527,8 @@ function renderActivityFeed(activityData) {
events.slice(0, 15).forEach((evt) => {
const row = document.createElement('div');
- const srcColor = sourceColors[evt.type] || 'var(--nxt-ink-dim)';
- const srcLabel = sourceLabels[evt.type] || evt.type || 'Payment';
+ const srcColor = sourceColors[evt.type] || '#4ade80';
+ const srcLabel = evt.type || 'payment';
row.style.cssText = `display:flex;align-items:center;gap:12px;padding:10px 14px;background:rgba(255,255,255,0.015);transition:background .12s;`;
row.innerHTML = `
<div style="width:8px;height:8px;border-radius:50%;background:${srcColor};flex-shrink:0;opacity:0.8"></div>
@@ -540,7 +540,7 @@ function renderActivityFeed(activityData) {
</div>
</div>
<div style="font-size:13px;font-weight:600;font-family:${MONO};flex-shrink:0">
- ${evt.amount_cents ? fmtUsd(evt.amount_cents / 100) : '—'}
+ ${evt.gross_usd != null ? fmtUsd(evt.gross_usd) : '—'}
</div>
<div style="font-size:11.5px;color:var(--nxt-ink-fade);flex-shrink:0;min-width:60px;text-align:right">
${evt.created_at ? relTime(evt.created_at) : ''}
diff --git a/src/marketplace.js b/src/marketplace.js
index 49c19aef2..1e1b04cf8 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -2695,6 +2695,7 @@ function renderCard(a) {
const buyers24h = a.buyers_24h ?? 0;
const paid = a.has_paid_skills || Object.keys(a.skill_prices || {}).length > 0;
const priceBadge = priceBadgeHtml(a.price);
+ const skillPriceBadge = skillPriceBadgeHtml(a.skill_prices);
const ratingAvg = Number(a.rating_avg || 0);
const ratingCount = Number(a.rating_count || 0);
const avatarBlock = a.thumbnail_url
@@ -2726,7 +2727,8 @@ function renderCard(a) {
${skillsCount ? `<span class="stat-pill">▤ ${skillsCount}</span>` : ''}
${ratingCount > 0 ? `<span class="rating" title="${ratingAvg.toFixed(2)} avg from ${ratingCount} review${ratingCount === 1 ? '' : 's'}">★ ${ratingAvg.toFixed(1)} <span class="count">(${fmtNumber(ratingCount)})</span></span>` : ''}
${buyers > 0 ? `<span class="stat-pill" title="${buyers} confirmed purchase${buyers === 1 ? '' : 's'}${buyers24h ? `, ${buyers24h} in last 24h` : ''}">$ ${fmtNumber(buyers)}${buyers24h > 0 ? ` <em>(+${buyers24h}/24h)</em>` : ''}</span>` : ''}
- ${paid ? `<span class="stat-pill paid-badge">$ Paid</span>` : ''}
+ ${skillPriceBadge}
+ ${!skillPriceBadge && paid ? `<span class="stat-pill paid-badge">$ Paid</span>` : ''}
</div>
<div class="footer">
<span>${date}</span>
@@ -4083,6 +4085,21 @@ function hasActivePrice(price) {
return !!(price && Number(price.amount) > 0);
}
+/**
+ * Build a "From $X/call" badge when the agent has priced skills.
+ * Returns empty string when there are no skill prices.
+ */
+function skillPriceBadgeHtml(skillPrices) {
+ if (!skillPrices || typeof skillPrices !== 'object') return '';
+ const entries = Object.values(skillPrices).filter(p => p && Number(p.amount) > 0);
+ if (!entries.length) return '';
+ const minAmount = Math.min(...entries.map(p => Number(p.amount)));
+ const decimals = Number(entries[0]?.mint_decimals ?? 6);
+ const minUsd = minAmount / Math.pow(10, decimals);
+ const formatted = minUsd >= 1 ? minUsd.toFixed(2) : minUsd >= 0.01 ? minUsd.toFixed(3) : minUsd.toFixed(6).replace(/0+$/, '');
+ return `<span class="stat-pill skill-price-badge" title="Skill pricing starts at $${formatted}/call">From $${escapeHtml(formatted)}/call</span>`;
+}
+
// ── Purchase Flow ─────────────────────────────────────────────────────────
//
// One-shot Solana Pay purchase: server mints a unique reference Pubkey, the
diff --git a/src/viewer.js b/src/viewer.js
index cb05086f8..94bd89eb6 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -909,6 +909,14 @@ export class Viewer {
object.rotation.y = Math.PI;
this.content = object;
+ // Build BVH acceleration structures for every mesh geometry so raycasting
+ // (hover / click interactions) is O(log n) instead of O(n) on triangle count.
+ object.traverse((node) => {
+ if (node.isMesh && node.geometry) {
+ node.geometry.computeBoundsTree();
+ }
+ });
+
this.state.punctualLights = true;
this.content.traverse((node) => {
if (node.isLight) {
@@ -1722,6 +1730,13 @@ export class Viewer {
this.scene.remove(this.content);
+ // dispose BVH acceleration structures before geometry
+ this.content.traverse((node) => {
+ if (node.isMesh && node.geometry?.boundsTree) {
+ node.geometry.disposeBoundsTree();
+ }
+ });
+
// dispose geometry
this.content.traverse((node) => {
if (!node.geometry) return;