Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: extend shared modules
nirholas8bb9e1586665
diff --git a/src/shared/add-funds.js b/src/shared/add-funds.jsnew file mode 100644index 000000000..0e62083f3--- /dev/null+++ b/src/shared/add-funds.js@@ -0,0 +1,367 @@+/**+ * add-funds.js — in-product "Add funds / Buy USDC" overlay.+ *+ * Opens a Coinbase Onramp popup (or shows a wallet-address fallback) so a+ * zero-balance user can get USDC without leaving the app. Polls the wallet+ * balance every 5 s and resolves when the balance increases.+ *+ * Usage:+ * const newBalance = await showAddFunds({ walletAddress, requiredUsdc });+ * // newBalance: { usdc: 1.23 } or null if dismissed+ */++const USDC_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const POLL_INTERVAL_MS = 5000;++function esc(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++const OVERLAY_HTML = `+<div class="af-overlay" id="af-overlay" role="dialog" aria-modal="true" aria-labelledby="af-title">+ <div class="af-box">+ <div class="af-head">+ <span class="af-title" id="af-title">Add funds</span>+ <button class="af-close" id="af-close" aria-label="Close">×</button>+ </div>+ <div class="af-body">+ <p class="af-desc">Buy USDC to use skills and pay for services. Funds are deposited directly to your connected wallet.</p>+ <div class="af-amounts" id="af-amounts">+ <button class="af-amt" data-amount="10">$10</button>+ <button class="af-amt" data-amount="25">$25</button>+ <button class="af-amt" data-amount="50">$50</button>+ </div>+ <button class="af-cta" id="af-cta">Buy USDC</button>+ <div class="af-alt" id="af-alt">+ <div class="af-alt-label">Or send USDC directly to your wallet:</div>+ <div class="af-addr-row">+ <code class="af-addr" id="af-addr"></code>+ <button class="af-copy" id="af-copy" title="Copy address">Copy</button>+ </div>+ <div class="af-alt-note">Solana network · USDC only</div>+ </div>+ <div class="af-status" id="af-status" role="status" aria-live="polite"></div>+ <div class="af-poll" id="af-poll" hidden>+ <div class="af-poll-indicator"></div>+ <span>Watching for deposit…</span>+ </div>+ </div>+ </div>+</div>+`;++const OVERLAY_STYLE = `+.af-overlay {+ position: fixed; inset: 0; z-index: 10000;+ background: rgba(0,0,0,0.72);+ display: flex; align-items: center; justify-content: center;+ font-family: system-ui, -apple-system, sans-serif;+ animation: af-fade-in 0.15s ease;+}+.af-overlay[hidden] { display: none; }+@keyframes af-fade-in { from { opacity: 0; } to { opacity: 1; } }++.af-box {+ background: #111827; border: 1px solid rgba(255,255,255,0.1);+ border-radius: 16px; padding: 28px 24px; width: 92%; max-width: 400px;+ color: #f0f0f0; box-shadow: 0 24px 64px rgba(0,0,0,0.7);+ animation: af-slide-up 0.2s cubic-bezier(.22,1,.36,1);+}+@keyframes af-slide-up { from { transform: translateY(16px); opacity: 0; } to { transform: none; opacity: 1; } }++.af-head {+ display: flex; align-items: center; justify-content: space-between;+ margin-bottom: 18px;+}+.af-title { font-size: 18px; font-weight: 700; letter-spacing: .01em; }+.af-close {+ background: none; border: none; color: rgba(255,255,255,0.45);+ font-size: 24px; cursor: pointer; line-height: 1; padding: 0;+ transition: color 0.15s;+}+.af-close:hover { color: #fff; }+.af-close:focus-visible { outline: 2px solid rgba(255,255,255,0.4); border-radius: 4px; }++.af-desc {+ font-size: 13px; color: rgba(255,255,255,0.55);+ margin: 0 0 18px; line-height: 1.5;+}++.af-amounts {+ display: flex; gap: 8px; margin-bottom: 14px;+}+.af-amt {+ flex: 1; padding: 9px 0; border-radius: 8px;+ border: 1px solid rgba(255,255,255,0.15);+ background: rgba(255,255,255,0.06); color: #fff;+ font-size: 15px; font-weight: 600; cursor: pointer;+ transition: background 0.12s, border-color 0.12s;+}+.af-amt:hover { background: rgba(255,255,255,0.12); border-color: rgba(255,255,255,0.3); }+.af-amt.selected { background: rgba(255,255,255,0.10); border-color: rgba(255,255,255,0.30); color: #ffffff; }+.af-amt:focus-visible { outline: 2px solid #6366f1; outline-offset: 2px; }++.af-cta {+ display: block; width: 100%; padding: 13px;+ border-radius: 10px; border: none;+ background: rgba(255,255,255,0.12); color: #fff; border: 1px solid rgba(255,255,255,0.18);+ font-size: 15px; font-weight: 700; cursor: pointer;+ transition: opacity 0.15s; letter-spacing: .02em;+ margin-bottom: 16px;+}+.af-cta:hover:not(:disabled) { opacity: 0.88; }+.af-cta:disabled { opacity: 0.4; cursor: default; }+.af-cta:focus-visible { outline: 2px solid rgba(255,255,255,0.4); outline-offset: 2px; }++.af-alt { padding-top: 14px; border-top: 1px solid rgba(255,255,255,0.07); }+.af-alt-label { font-size: 12px; color: rgba(255,255,255,0.4); margin-bottom: 8px; }+.af-addr-row { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }+.af-addr {+ flex: 1; font-family: ui-monospace, monospace; font-size: 12px;+ color: rgba(255,255,255,0.7); overflow: hidden; text-overflow: ellipsis;+ white-space: nowrap; background: rgba(255,255,255,0.05);+ border-radius: 6px; padding: 5px 8px;+}+.af-copy {+ flex-shrink: 0; font-size: 12px; padding: 5px 10px;+ border-radius: 6px; border: 1px solid rgba(255,255,255,0.2);+ background: transparent; color: rgba(255,255,255,0.5); cursor: pointer;+ transition: background 0.12s, color 0.12s;+}+.af-copy:hover { background: rgba(255,255,255,0.1); color: #fff; }+.af-copy.copied { color: #34d399; border-color: #34d399; }+.af-alt-note { font-size: 11px; color: rgba(255,255,255,0.3); }++.af-status {+ margin-top: 12px; font-size: 13px; min-height: 18px;+ text-align: center; color: rgba(255,255,255,0.55);+}+.af-status.err { color: #f87171; }+.af-status.ok { color: #34d399; font-weight: 600; }++.af-poll {+ display: flex; align-items: center; gap: 8px;+ justify-content: center; margin-top: 12px;+ font-size: 12px; color: rgba(255,255,255,0.35);+}+.af-poll[hidden] { display: none; }+.af-poll-indicator {+ width: 6px; height: 6px; border-radius: 50%;+ background: #4f46e5;+ animation: af-pulse 1.4s ease-in-out infinite;+}+@keyframes af-pulse {+ 0%, 100% { opacity: 1; transform: scale(1); }+ 50% { opacity: 0.4; transform: scale(0.7); }+}+`;++/**+ * Fetch USDC balance for a Solana address via our existing wallet/balances endpoint.+ * Returns the decimal USDC amount (e.g. 1.5 for 1.5 USDC) or null on failure.+ * @param {string} address+ * @returns {Promise<number|null>}+ */+async function fetchUsdcBalance(address) {+ try {+ const r = await fetch('/api/wallet/balances', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ chain: 'solana', address }),+ });+ if (!r.ok) return null;+ const data = await r.json();+ const usdcToken = (data.tokens || []).find(+ (t) => t.mint === USDC_MINT_SOLANA || t.symbol === 'USDC',+ );+ return usdcToken ? Number(usdcToken.amount) || 0 : 0;+ } catch {+ return null;+ }+}++/**+ * Fetch an onramp URL from our server endpoint.+ * Returns { url, mode } or null on failure.+ * @param {string} address Solana wallet address+ * @param {number} [amount] suggested USD amount+ */+async function fetchOnrampLink(address, amount = 25) {+ try {+ const params = new URLSearchParams({ address, amount: String(amount) });+ const r = await fetch(`/api/onramp/link?${params}`, { credentials: 'include' });+ if (!r.ok) return null;+ return await r.json();+ } catch {+ return null;+ }+}++/**+ * Show the "Add funds" overlay.+ *+ * @param {object} opts+ * @param {string} opts.walletAddress the Phantom/Solana wallet to fund+ * @param {number} [opts.requiredUsdc] minimum amount needed (shows as suggestion)+ * @param {Element} [opts.container] defaults to document.body+ * @returns {Promise<{usdc: number}|null>} resolves with new balance or null if dismissed+ */+export function showAddFunds({ walletAddress, requiredUsdc, container } = {}) {+ return new Promise((resolve) => {+ const root = container || document.body;++ // Inject styles once+ if (!document.getElementById('af-styles')) {+ const style = document.createElement('style');+ style.id = 'af-styles';+ style.textContent = OVERLAY_STYLE;+ document.head.appendChild(style);+ }++ const wrapper = document.createElement('div');+ wrapper.innerHTML = OVERLAY_HTML;+ root.appendChild(wrapper);++ const overlay = wrapper.querySelector('#af-overlay');+ const addrEl = wrapper.querySelector('#af-addr');+ const copyBtn = wrapper.querySelector('#af-copy');+ const ctaBtn = wrapper.querySelector('#af-cta');+ const closeBtn = wrapper.querySelector('#af-close');+ const statusEl = wrapper.querySelector('#af-status');+ const pollEl = wrapper.querySelector('#af-poll');+ const amtBtns = wrapper.querySelectorAll('.af-amt');++ let selectedAmount = 25;+ let pollTimer = null;+ let baselineUsdc = null;+ let popupWindow = null;+ let destroyed = false;++ // Mark first preset selected by default+ amtBtns.forEach((btn) => {+ if (Number(btn.dataset.amount) === selectedAmount) btn.classList.add('selected');+ btn.addEventListener('click', () => {+ amtBtns.forEach((b) => b.classList.remove('selected'));+ btn.classList.add('selected');+ selectedAmount = Number(btn.dataset.amount);+ });+ });++ // Show wallet address+ if (walletAddress) {+ addrEl.textContent = `${walletAddress.slice(0, 12)}…${walletAddress.slice(-8)}`;+ addrEl.title = walletAddress;+ }++ // Copy address button+ copyBtn.addEventListener('click', async () => {+ if (!walletAddress) return;+ try {+ await navigator.clipboard.writeText(walletAddress);+ copyBtn.textContent = 'Copied!';+ copyBtn.classList.add('copied');+ setTimeout(() => {+ copyBtn.textContent = 'Copy';+ copyBtn.classList.remove('copied');+ }, 1800);+ } catch {+ copyBtn.textContent = 'Copy';+ }+ });++ function setStatus(msg, kind = '') {+ statusEl.textContent = msg;+ statusEl.className = 'af-status' + (kind ? ` ${kind}` : '');+ }++ function dismiss(result = null) {+ if (destroyed) return;+ destroyed = true;+ clearInterval(pollTimer);+ if (popupWindow && !popupWindow.closed) popupWindow.close();+ overlay.style.animation = 'af-fade-in 0.12s ease reverse forwards';+ setTimeout(() => wrapper.remove(), 130);+ resolve(result);+ }++ // Snapshot the current balance so we can detect an increase+ async function snapshotBalance() {+ if (!walletAddress) return;+ baselineUsdc = await fetchUsdcBalance(walletAddress);+ }++ // Poll for balance increase after popup opens+ async function startPolling() {+ if (!walletAddress) return;+ pollEl.removeAttribute('hidden');+ setStatus('Waiting for your deposit to confirm…');++ pollTimer = setInterval(async () => {+ const current = await fetchUsdcBalance(walletAddress);+ if (current === null) return;+ if (baselineUsdc !== null && current > baselineUsdc) {+ clearInterval(pollTimer);+ pollEl.setAttribute('hidden', '');+ setStatus(+ `✓ Deposit confirmed — ${current.toFixed(2)} USDC added`,+ 'ok',+ );+ setTimeout(() => dismiss({ usdc: current }), 1800);+ }+ }, POLL_INTERVAL_MS);+ }++ // Main CTA: open onramp popup + start polling+ ctaBtn.addEventListener('click', async () => {+ ctaBtn.disabled = true;+ setStatus('Opening Coinbase checkout…');++ await snapshotBalance();++ const onramp = await fetchOnrampLink(walletAddress, selectedAmount);++ if (onramp?.url) {+ popupWindow = window.open(+ onramp.url,+ 'af_coinbase_pay',+ 'width=480,height=720,menubar=no,toolbar=no,location=no,status=no',+ );+ }++ if (!popupWindow || popupWindow.closed) {+ // Popup blocked or no URL — fall back to same-tab link+ if (onramp?.url) {+ setStatus('Popup blocked. Opening in new tab…');+ window.open(onramp.url, '_blank', 'noopener');+ } else {+ setStatus('Copy your address below and send USDC from any exchange.', '');+ }+ } else {+ setStatus('');+ }++ ctaBtn.disabled = false;+ await startPolling();+ });++ // Close handlers+ closeBtn.addEventListener('click', () => dismiss(null));+ overlay.addEventListener('click', (e) => {+ if (e.target === overlay) dismiss(null);+ });++ // Keyboard dismiss+ const keyHandler = (e) => {+ if (e.key === 'Escape') { document.removeEventListener('keydown', keyHandler); dismiss(null); }+ };+ document.addEventListener('keydown', keyHandler);++ // Focus the CTA on open+ requestAnimationFrame(() => ctaBtn.focus());+ });+}diff --git a/src/shared/agent-coin.js b/src/shared/agent-coin.jsindex db8b7f003..6c0515b81 100644--- a/src/shared/agent-coin.js+++ b/src/shared/agent-coin.js@@ -108,6 +108,13 @@ export async function openCoinLaunch(agent) {const id = agent.id || rec.id || agent.agent_id || rec.agent_id;if (!id) return;+ // First-timers crossing the on-chain threshold get the plain-language+ // explainer + wallet setup before the launch modal. Returning/ready users+ // pass straight through (the primer resolves instantly). Loaded lazily so a+ // wall of coin chips never pays for the wizard's deps until one is clicked.+ const { ensureOnchainPrimer } = await import('./onchain-primer.js');+ if (!(await ensureOnchainPrimer({ action: 'launch-token' }))) return;+const onchain = rec.onchain || rec.meta?.onchain || agent.onchain || null;const needsDeploy = !onchain || onchain.family !== 'solana';const name = rec.name || agent.name || 'Agent';diff --git a/src/shared/async-state.js b/src/shared/async-state.jsnew file mode 100644index 000000000..c084aab94--- /dev/null+++ b/src/shared/async-state.js@@ -0,0 +1,146 @@+/**+ * async-state — the one network/render boundary for data-driven surfaces.+ *+ * Wraps the loading → fetch → empty / error / retry lifecycle so every surface+ * fails into a *designed* state instead of a blank container or an unhandled+ * rejection. It is the orchestration layer on top of two existing modules:+ *+ * - state-kit.js → the skeleton / empty / error visual shells+ * - error-messages.js → friendly, redacted copy for known failure causes+ *+ * Usage (the common case — one call wires all four states):+ *+ * import { loadInto } from './shared/async-state.js';+ *+ * loadInto(grid, {+ * load: () => api.listAgents().then((r) => r.agents),+ * render: (agents, el) => { el.innerHTML = agents.map(card).join(''); },+ * empty: { title: 'No agents yet', body: 'Deploy your first agent to see it here.',+ * actions: [{ label: 'Deploy', href: '/deploy', primary: true }] },+ * skeleton: { count: 8, variant: 'card' },+ * context: 'dashboard:agents',+ * });+ *+ * On failure the container shows a retryable error state; clicking Retry re-runs+ * the same load. Technical detail still goes to console (via resolveError), so+ * this never *hides* an error from developers — it only stops users seeing a void.+ */++import {+ skeletonHTML,+ emptyStateHTML,+ errorStateHTML,+ ensureStateKitStyles,+} from './state-kit.js';+import { resolveError } from './error-messages.js';++/**+ * Default emptiness test: treats `null`/`undefined`, empty arrays, and+ * `{ items: [] }` / `{ length: 0 }` shapes as empty. Override via opts.isEmpty+ * for anything else.+ */+function defaultIsEmpty(data) {+ if (data == null) return true;+ if (Array.isArray(data)) return data.length === 0;+ if (typeof data.length === 'number') return data.length === 0;+ return false;+}++function renderSkeleton(container, skeleton) {+ if (skeleton === false) return;+ ensureStateKitStyles();+ if (typeof skeleton === 'string') {+ container.innerHTML = skeleton;+ return;+ }+ const { count = 6, variant = 'card', wrap } = skeleton || {};+ const html = skeletonHTML(count, variant);+ container.innerHTML = typeof wrap === 'function' ? wrap(html) : html;+}++/**+ * Run an async load with designed loading/empty/error/retry states.+ *+ * @param {Element} container Element whose innerHTML hosts each state.+ * @param {object} opts+ * @param {() => Promise<*>} opts.load Async data fetch. Throw to trigger the error state.+ * @param {(data, container) => void} opts.render Render the populated state.+ * @param {(data) => boolean} [opts.isEmpty] Emptiness test (default handles arrays / {items}).+ * @param {object|false} [opts.skeleton] { count, variant, wrap } | HTML string | false.+ * @param {object} [opts.empty] emptyStateHTML opts ({ title, body, actions, icon }).+ * @param {object} [opts.error] errorStateHTML override ({ title, body }).+ * @param {string} [opts.errorScope] data attribute on the retry button.+ * @param {string} [opts.context] Console grouping label for resolveError.+ * @returns {Promise<*|null>} The loaded data, or null if it errored or was empty.+ */+export async function loadInto(container, opts = {}) {+ if (!container) return null;+ const {+ load,+ render,+ isEmpty = defaultIsEmpty,+ skeleton = { count: 6, variant: 'card' },+ empty,+ error,+ errorScope = '',+ context = 'async-state',+ } = opts;++ if (typeof load !== 'function' || typeof render !== 'function') {+ throw new Error('loadInto requires load() and render() functions');+ }++ renderSkeleton(container, skeleton);++ let data;+ try {+ data = await load();+ } catch (err) {+ renderError(container, err, { error, errorScope, context }, () =>+ loadInto(container, opts),+ );+ return null;+ }++ if (isEmpty(data)) {+ if (empty) {+ ensureStateKitStyles();+ container.innerHTML = emptyStateHTML(empty);+ } else {+ render(data, container);+ }+ return null;+ }++ render(data, container);+ return data;+}++/**+ * Render a retryable error state into a container and wire its Retry button.+ * Exposed for surfaces that own their own fetch loop but want the shared shell.+ *+ * @param {Element} container+ * @param {*} err Anything resolveError accepts (Error/string/{status}).+ * @param {object} [opts] { error?: {title,body}, errorScope?, context? }+ * @param {Function} [onRetry] Called when the user clicks Retry.+ */+export function renderError(container, err, opts = {}, onRetry) {+ if (!container) return;+ const { error, errorScope = '', context = 'async-state' } = opts;+ const friendly = resolveError(err, context); // logs technical detail to console+ ensureStateKitStyles();+ container.innerHTML = errorStateHTML({+ title: error?.title || friendly.title,+ body: error?.body || friendly.body,+ scope: errorScope,+ });+ if (typeof onRetry === 'function') {+ // Node is replaced on every render, so the listener dies with it — no leak.+ container.querySelector('[data-sk-retry]')?.addEventListener('click', onRetry);+ }+}++if (typeof window !== 'undefined') {+ window.twsAsyncState = { loadInto, renderError };+}diff --git a/src/shared/error-messages.js b/src/shared/error-messages.jsnew file mode 100644index 000000000..bb2c05bbf--- /dev/null+++ b/src/shared/error-messages.js@@ -0,0 +1,268 @@+/**+ * Shared crypto-error message map for three.ws.+ *+ * Every key maps to { title, body, actions } — plain language, no env-var names,+ * no raw protocol codes surfaced to users.+ *+ * actions: Array<{ label, href?, onClick? }>+ * - href → renders as an anchor (navigation)+ * - onClick → renders as a button+ *+ * Consumers: wire these strings into whatever shell they use (error banner,+ * modal status, feed item, etc.). Technical detail goes to console, not UI.+ */++import { log } from './log.js';++// Internal error codes that must never appear in UI strings+const REDACTED_PATTERNS = [+ /AVATAR_WALLET_SECRET/gi,+ /AGENT_[A-Z_]+/gi,+ /wallet_unconfigured/gi,+ /no_recipient/gi,+ /NO_WALLET/gi,+];++/**+ * Scrub any internal config names from a message before surfacing it.+ * @param {string} msg+ * @returns {string}+ */+export function sanitizeErrorMessage(msg) {+ if (!msg || typeof msg !== 'string') return '';+ let out = msg;+ for (const pattern of REDACTED_PATTERNS) {+ out = out.replace(pattern, '[configuration]');+ }+ return out;+}++/**+ * The error message map.+ * Keys: canonical error codes / causes.+ * Values: { title, body, actions }+ *+ * title — short, human, sentence-case+ * body — 1-2 sentences explaining what happened + why+ * actions — ordered list of actions; first is primary+ */+export const ERROR_MESSAGES = {+ NO_WALLET: {+ title: 'No wallet connected',+ body: 'Connect a Solana wallet to deploy your agent on-chain. If you don\'t have one yet, Phantom takes about a minute to set up.',+ actions: [+ { label: 'Connect wallet', onClick: 'connectWallet' },+ { label: 'Get Phantom', href: 'https://phantom.app/' },+ ],+ },++ NO_WALLET_ETHEREUM: {+ title: 'No wallet detected',+ body: 'A browser wallet extension is needed to sign in. Install MetaMask or Coinbase Wallet, then return here.',+ actions: [+ { label: 'Get MetaMask', href: 'https://metamask.io/' },+ { label: 'Get Coinbase Wallet', href: 'https://www.coinbase.com/wallet' },+ ],+ },++ insufficient_balance: {+ title: 'Not enough funds',+ body: 'Your wallet balance is too low to complete this transaction. A small amount of SOL covers the network fee.',+ actions: [+ { label: 'Add funds', onClick: 'openFundFlow' },+ { label: 'Check balance', onClick: 'checkBalance' },+ ],+ },++ wallet_unconfigured: {+ title: 'Service temporarily unavailable',+ body: 'Something on our end isn\'t quite ready yet. Please try again in a moment.',+ actions: [+ { label: 'Try again', onClick: 'retry' },+ ],+ },++ no_recipient: {+ title: 'Service temporarily unavailable',+ body: 'Something on our end isn\'t quite ready yet. Please try again in a moment.',+ actions: [+ { label: 'Try again', onClick: 'retry' },+ ],+ },++ user_rejected: {+ title: 'Transaction cancelled',+ body: 'You declined the transaction in your wallet. Nothing was sent.',+ actions: [+ { label: 'Try again', onClick: 'retry' },+ ],+ },++ network_error: {+ title: 'Connection problem',+ body: 'We couldn\'t reach the network. Check your connection and try again.',+ actions: [+ { label: 'Try again', onClick: 'retry' },+ ],+ },++ tx_failed: {+ title: 'Transaction didn\'t go through',+ body: 'The network rejected the transaction. This can happen when fees spike — try again in a moment.',+ actions: [+ { label: 'Try again', onClick: 'retry' },+ ],+ },++ verification_failed: {+ title: 'Verification pending',+ body: 'Your payment may have gone through but we couldn\'t confirm it yet. Check your wallet history and contact support if funds were deducted.',+ actions: [+ { label: 'Contact support', href: 'mailto:[email protected]' },+ ],+ },++ phantom_not_detected: {+ title: 'Phantom not found',+ body: 'The Phantom wallet extension isn\'t installed. Install it in a minute and come back.',+ actions: [+ { label: 'Install Phantom', href: 'https://phantom.app/' },+ ],+ },++ sign_in_failed: {+ title: 'Sign-in failed',+ body: 'We couldn\'t complete the sign-in. Try connecting your wallet again.',+ actions: [+ { label: 'Try again', onClick: 'retry' },+ ],+ },++ session_expired: {+ title: 'Session expired',+ body: 'Your session has ended. Sign in again to continue.',+ actions: [+ { label: 'Sign in', onClick: 'connectWallet' },+ ],+ },++ forbidden: {+ title: 'Not authorised',+ body: 'Your account doesn\'t have access to this yet. Make sure your wallet is linked and try again.',+ actions: [+ { label: 'Go to deploy console', href: '/deploy' },+ ],+ },++ generic: {+ title: 'Something went wrong',+ body: 'An unexpected error occurred. Try again — if it keeps happening, contact support.',+ actions: [+ { label: 'Try again', onClick: 'retry' },+ ],+ },+};++/**+ * Resolve an error to a friendly message entry.+ * Logs the raw technical detail to console.+ *+ * @param {string|Error|{code?:string, error?:string, message?:string, status?:number}} err+ * @param {string} [contextLabel] — label for console grouping+ * @returns {{ title: string, body: string, actions: Array<{label:string, href?:string, onClick?:string}> }}+ */+export function resolveError(err, contextLabel = 'crypto-error') {+ // Log technical detail privately+ log.error(`[three.ws] ${contextLabel}`, err);++ const code = typeof err === 'string' ? err+ : (err?.code || err?.error || '');+ const msg = typeof err === 'string' ? err+ : (err?.message || '');+ const status = typeof err === 'object' ? err?.status : undefined;++ // User-cancelled signature (various wallets word this differently)+ if (/reject|denied|cancel|user.*declin/i.test(msg)) {+ return ERROR_MESSAGES.user_rejected;+ }++ // Network / fetch failures+ if (/network|fetch|failed to fetch|econnrefused/i.test(msg)) {+ return ERROR_MESSAGES.network_error;+ }++ // Phantom / wallet not installed+ if (/phantom not detected|phantom not found|no.*solana|solana.*not/i.test(msg)) {+ return ERROR_MESSAGES.phantom_not_detected;+ }++ // HTTP 401+ if (status === 401) {+ return ERROR_MESSAGES.session_expired;+ }++ // HTTP 403+ if (status === 403 || code === 'forbidden') {+ return ERROR_MESSAGES.forbidden;+ }++ // Known code map+ if (code && ERROR_MESSAGES[code]) {+ return ERROR_MESSAGES[code];+ }++ return ERROR_MESSAGES.generic;+}++/**+ * Render a friendly error banner into a container element.+ * Replaces its content with title, body, and action buttons/links.+ *+ * @param {HTMLElement} container+ * @param {ReturnType<typeof resolveError>} entry+ * @param {Record<string, () => void>} handlers — maps onClick strings to real functions+ */+export function renderErrorBanner(container, entry, handlers = {}) {+ container.innerHTML = '';+ container.setAttribute('role', 'alert');+ container.setAttribute('aria-live', 'assertive');++ const titleEl = document.createElement('strong');+ titleEl.className = 'err-title';+ titleEl.textContent = entry.title;++ const bodyEl = document.createElement('p');+ bodyEl.className = 'err-body';+ bodyEl.textContent = entry.body;++ const actionsEl = document.createElement('div');+ actionsEl.className = 'err-actions';++ for (const action of (entry.actions || [])) {+ if (action.href) {+ const a = document.createElement('a');+ a.className = 'err-action err-action-link';+ a.href = action.href;+ if (action.href.startsWith('http')) {+ a.target = '_blank';+ a.rel = 'noopener noreferrer';+ }+ a.textContent = action.label;+ actionsEl.appendChild(a);+ } else if (action.onClick) {+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'err-action err-action-btn';+ btn.textContent = action.label;+ const handler = handlers[action.onClick];+ if (handler) {+ btn.addEventListener('click', handler);+ } else {+ btn.disabled = true;+ }+ actionsEl.appendChild(btn);+ }+ }++ container.append(titleEl, bodyEl, actionsEl);+}diff --git a/src/shared/log.js b/src/shared/log.jsnew file mode 100644index 000000000..19228c18e--- /dev/null+++ b/src/shared/log.js@@ -0,0 +1,76 @@+// ── log.js — tiny gated logger for three.ws ─────────────────────────────────+//+// A production console should be quiet: noise hides real problems and looks+// unprofessional when a developer opens DevTools. This logger keeps verbose+// diagnostics (warn/info/debug/log) out of production consoles while letting+// genuine error reporting through, so operators still see what matters.+//+// Gating:+// - In dev (`import.meta.env.DEV`) every level prints.+// - In production, warn/info/debug/log are silenced UNLESS the developer+// opts in via `?debug` in the URL or `localStorage['tws:debug'] = '1'`.+// - `error` always prints — a real error on a healthy page is a bug to fix,+// not noise to mute. Pair these with a user-facing state (see A04).+//+// Call sites already carry a `[tag]` prefix in the message, so the default+// `log` export is a drop-in for `console` — swap `console.` → `log.`. For new+// code, `createLogger('tag')` prefixes every line for you.++function debugFlagEnabled() {+ if (typeof window === 'undefined') return false;+ try {+ const params = new URLSearchParams(window.location.search);+ if (params.has('debug') && params.get('debug') !== '0') return true;+ if (window.localStorage?.getItem('tws:debug') === '1') return true;+ } catch {+ // Sandboxed iframe / storage disabled — treat as no opt-in.+ }+ return false;+}++// `import.meta.env.DEV` is statically replaced at build time, so in a prod+// bundle `VERBOSE` collapses to the debug-flag check evaluated once at load.+const IS_DEV = Boolean(import.meta.env?.DEV);+const VERBOSE = IS_DEV || debugFlagEnabled();++const noop = () => {};++// Bind directly to console methods so DevTools reports the real call site+// (file:line) instead of pointing every line back into this module.+const bind = (method) =>+ typeof console !== 'undefined' && typeof console[method] === 'function'+ ? console[method].bind(console)+ : noop;++/**+ * The shared logger. `warn` / `info` / `debug` / `log` are gated; `error`+ * always emits.+ */+export const log = {+ error: bind('error'),+ warn: VERBOSE ? bind('warn') : noop,+ info: VERBOSE ? bind('info') : noop,+ debug: VERBOSE ? bind('debug') : noop,+ log: VERBOSE ? bind('log') : noop,+};++/**+ * Create a logger that prefixes every line with `[tag]`.+ * @param {string} tag short module identifier, e.g. 'marketplace'+ */+export function createLogger(tag) {+ const prefix = `[${tag}]`;+ const wrap = (fn) => (...args) => fn(prefix, ...args);+ return {+ error: wrap(bind('error')),+ warn: VERBOSE ? wrap(bind('warn')) : noop,+ info: VERBOSE ? wrap(bind('info')) : noop,+ debug: VERBOSE ? wrap(bind('debug')) : noop,+ log: VERBOSE ? wrap(bind('log')) : noop,+ };+}++/** Whether verbose diagnostics are currently enabled (dev or `?debug`). */+export const isVerbose = VERBOSE;++export default log;diff --git a/src/shared/modal.js b/src/shared/modal.jsnew file mode 100644index 000000000..a786a0f3b--- /dev/null+++ b/src/shared/modal.js@@ -0,0 +1,183 @@+/**+ * Modal — canonical accessible modal primitive for three.ws.+ *+ * Built on native <dialog>/showModal() which gives us for free:+ * - Spec-compliant focus trap (focus cycles inside the dialog)+ * - ESC key to close via the native 'cancel' event+ * - ::backdrop pseudo-element scrim+ * - Top-layer stacking (no z-index battles)+ *+ * API+ * ───+ * const modal = new Modal({ title, body, actions, onClose, dismissible });+ * modal.open(triggerEl?) — opens, locks scroll, saves focus trigger+ * modal.close() — animates close, unlocks scroll, returns focus+ * modal.destroy() — closes + removes element from DOM+ *+ * Modal.show(opts) — one-shot: create, open, return instance+ *+ * Exposed DOM slots (update content after construction):+ * modal.titleEl — <h2 id="…"> (wired to aria-labelledby)+ * modal.bodyEl — <div id="…"> (wired to aria-describedby)+ * modal.actionsEl — <div .tws-modal-actions> (hidden when empty)+ *+ * Options+ * ───────+ * title {string|Node} Modal heading (text or DOM node)+ * body {string|Node} Body content (HTML string or DOM node)+ * actions {string|Node} Action buttons (HTML string or DOM node)+ * onClose {() => void} Called after the modal finishes closing+ * dismissible {boolean=true} ESC + backdrop click close the modal+ */++let _lockDepth = 0;+let _bodyOverflow = '';++function _lockScroll() {+ if (_lockDepth++ === 0) {+ _bodyOverflow = document.body.style.overflow;+ document.body.style.overflow = 'hidden';+ }+}++function _unlockScroll() {+ if (--_lockDepth <= 0) {+ _lockDepth = 0;+ document.body.style.overflow = _bodyOverflow;+ }+}++let _uid = 0;++export class Modal {+ constructor({ title = '', body = '', actions = '', onClose, dismissible = true } = {}) {+ const id = ++_uid;+ this._titleId = `tws-modal-title-${id}`;+ this._bodyId = `tws-modal-body-${id}`;+ this._trigger = null;+ this._onClose = onClose;+ this._dismissible = dismissible;+ this._closing = false;++ const el = document.createElement('dialog');+ el.className = 'tws-modal';+ el.setAttribute('aria-modal', 'true');+ el.setAttribute('aria-labelledby', this._titleId);+ el.setAttribute('aria-describedby', this._bodyId);+ el.innerHTML = `+ <div class="tws-modal-inner">+ <div class="tws-modal-header">+ <h2 class="tws-modal-title" id="${this._titleId}"></h2>+ <button class="tws-modal-close" aria-label="Close dialog" type="button">✕</button>+ </div>+ <div class="tws-modal-body" id="${this._bodyId}"></div>+ <div class="tws-modal-actions"></div>+ </div>+ `;++ this.el = el;+ this.titleEl = el.querySelector('.tws-modal-title');+ this.bodyEl = el.querySelector('.tws-modal-body');+ this.actionsEl = el.querySelector('.tws-modal-actions');+ this._closeBtn = el.querySelector('.tws-modal-close');++ _setSlot(this.titleEl, title, 'text');+ _setSlot(this.bodyEl, body, 'html');+ _setSlot(this.actionsEl, actions, 'html');++ if (!actions) this.actionsEl.hidden = true;++ document.body.appendChild(el);++ this._onCancel = (e) => {+ e.preventDefault();+ if (this._dismissible) this._startClose();+ };++ this._onBackdropClick = (e) => {+ if (!this._dismissible) return;+ // The <dialog> fills only the inner card; clicks outside its bounding rect+ // hit the ::backdrop, registering as a click on the <dialog> itself.+ const rect = el.getBoundingClientRect();+ if (+ e.clientX < rect.left || e.clientX > rect.right ||+ e.clientY < rect.top || e.clientY > rect.bottom+ ) {+ this._startClose();+ }+ };++ el.addEventListener('cancel', this._onCancel);+ el.addEventListener('click', this._onBackdropClick);+ this._closeBtn.addEventListener('click', () => this._startClose());+ }++ /** Opens the modal. Optionally pass the element that triggered it so focus returns on close. */+ open(triggerEl = null) {+ this._trigger = triggerEl instanceof Element ? triggerEl : document.activeElement;+ _lockScroll();+ this.el.showModal();+ // Move focus to first interactive element inside (native focus trap takes over after)+ const firstFocusable = this.el.querySelector(+ 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',+ );+ if (firstFocusable) firstFocusable.focus();+ return this;+ }++ /** Closes the modal with the exit animation, then restores state. */+ close() {+ this._startClose();+ return this;+ }++ _startClose() {+ if (!this.el.open || this._closing) return;+ this._closing = true;+ this.el.classList.add('tws-modal--closing');+ // Wait for CSS transition (200ms) before calling dialog.close()+ setTimeout(() => this._finishClose(), 210);+ }++ _finishClose() {+ if (!this.el.open) return;+ this.el.close();+ this.el.classList.remove('tws-modal--closing');+ this._closing = false;+ _unlockScroll();+ this._trigger?.focus();+ this._trigger = null;+ this._onClose?.();+ }++ /** Removes the modal element from the DOM entirely. */+ destroy() {+ if (this.el.open) {+ // Close immediately without animation so the element can be removed+ this.el.classList.remove('tws-modal--closing');+ this._closing = false;+ if (this.el.open) this.el.close();+ _unlockScroll();+ this._trigger?.focus();+ }+ this.el.removeEventListener('cancel', this._onCancel);+ this.el.removeEventListener('click', this._onBackdropClick);+ this.el.remove();+ }++ /** One-shot: create + open immediately, return the instance. */+ static show(opts) {+ return new Modal(opts).open();+ }+}++function _setSlot(el, value, mode) {+ if (!value) return;+ if (value instanceof Node) {+ el.appendChild(value);+ } else if (mode === 'text') {+ el.textContent = String(value);+ } else {+ el.innerHTML = String(value);+ }+}diff --git a/src/shared/onchain-badge.js b/src/shared/onchain-badge.jsindex 8f1bd1ba4..504ab4e41 100644--- a/src/shared/onchain-badge.js+++ b/src/shared/onchain-badge.js@@ -21,6 +21,15 @@* Returns null when the agent is not deployed on-chain — callers render nothing.*/+// Shared pill class names — the canonical .pill system (B04 / style.css) uses+// the same --badge-onchain-* / --badge-devnet-* tokens, so tws-ocb elements+// double as .pill elements. This keeps the badge in sync with the design system+// without breaking any surface that renders it outside the main style.css scope+// (widgets, embeds, iframes). The isolated injected stylesheet below is the+// authoritative fallback for those out-of-scope contexts.+const PILL_BASE_CLASS = 'pill';+const PILL_ONCHAIN_CLASS = 'pill--onchain';+const PILL_DEVNET_CLASS = 'pill--devnet';const STYLE_ID = 'tws-onchain-badge-styles';// Known EVM chains → display name + explorer base. Solana is handled separately@@ -304,8 +313,10 @@ export function onchainBadgeHTML(agent, opts = {}) {ensureOnchainBadgeStyles();const { size = 'sm', link = true, showChain = true, label = 'On-chain' } = opts;- const classes = ['tws-ocb'];- if (size === 'md') classes.push('tws-ocb--md');+ // tws-ocb — isolated injected styles (works in iframes/embeds/widgets)+ // pill / pill--onchain — canonical B04 .pill system (in scope when style.css is loaded)+ const classes = ['tws-ocb', PILL_BASE_CLASS, status.testnet ? PILL_DEVNET_CLASS : PILL_ONCHAIN_CLASS];+ if (size === 'md') classes.push('tws-ocb--md', 'pill--md');if (status.testnet) classes.push('tws-ocb--devnet');const chainHtml = showChain ? `<span class="tws-ocb-chain">${esc(status.chainShort)}</span>` : '';@@ -318,7 +329,7 @@ export function onchainBadgeHTML(agent, opts = {}) {const title = esc(titleBits.join(' · '));const aria = `Deployed on-chain on ${status.chainLabel}`;- const inner = `<span class="tws-ocb-dot" aria-hidden="true"></span><span class="tws-ocb-label">${esc(label)}</span>${chainHtml}`;+ const inner = `<span class="tws-ocb-dot pill__dot" aria-hidden="true"></span><span class="tws-ocb-label">${esc(label)}</span>${chainHtml}`;if (link && status.explorerUrl) {return `<a class="${classes.join(' ')}" href="${esc(status.explorerUrl)}" target="_blank" rel="noopener noreferrer" title="${title}" aria-label="${esc(aria)} — view on explorer">${inner}</a>`;diff --git a/src/shared/onchain-primer.js b/src/shared/onchain-primer.jsnew file mode 100644index 000000000..c33a06f45--- /dev/null+++ b/src/shared/onchain-primer.js@@ -0,0 +1,426 @@+/**+ * onchain-primer.js — the "before you go on-chain" explainer + setup wizard.+ *+ * three.ws is free to browse, build and preview. The moment a user opts into a+ * *money* action — launching a coin, tipping a dancer, deploying on-chain,+ * withdrawing earnings — they hit terms that mean nothing to a newcomer: wallet,+ * USDC, fees. This module is the ladder over that wall: a plain-language+ * explainer followed by a guided, three-step setup that reuses the flows we+ * already ship (the site sign-in and the Add-funds overlay). It invents no new+ * auth and never touches the free core — it only runs when a caller asks for it.+ *+ * Usage (gate a crypto action):+ *+ * import { ensureOnchainPrimer } from '/src/shared/onchain-primer.js';+ * if (!(await ensureOnchainPrimer({ action: 'launch-token' }))) return;+ * // …proceed with the on-chain action: the user is educated + wallet-ready.+ *+ * Returns a Promise<boolean>: true when the user is ready to transact (already+ * crypto-ready, or they connected a wallet through the wizard), false when they+ * backed out before connecting — in which case the caller should abort cleanly.+ *+ * Returning users who already have a wallet/session are never nagged: the gate+ * resolves true instantly with no modal. The explainer is for first-timers.+ */++import { Modal } from './modal.js';+import { signInWithWallet } from '../wallet-auth.js';+import { getWalletState } from '../erc8004/agent-registry.js';+import { showAddFunds } from './add-funds.js';++const DONE_KEY = 'tws:onchain-primer:done';+const AUTH_HINT_KEY = '3dagent:auth-hint';++// Recommended wallets — free browser extensions. Phantom leads (Solana-native,+// where money lands on three.ws); MetaMask covers EVM users. Both inject a+// provider the site sign-in can use.+const WALLETS = [+ { name: 'Phantom', href: 'https://phantom.app/download', note: 'Solana · recommended' },+ { name: 'MetaMask', href: 'https://metamask.io/download/', note: 'Multi-chain' },+];++// Per-action framing for the opening line. Keeps the explainer honest about why+// it appeared without changing the (universal) lesson that follows.+const ACTIONS = {+ 'launch-token': 'Launching a coin for your agent is an on-chain action.',+ monetize: 'Earning from your agents means money moves on-chain.',+ tip: 'Tipping sends a real micro-payment on-chain.',+ deploy: 'Deploying your agent on-chain registers it on a public network.',+ withdraw: 'Withdrawing your earnings sends them to a wallet you control.',+ default: 'This is an on-chain action — it moves real money.',+};++function escHtml(s) {+ return String(s == null ? '' : s).replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++/**+ * Has the user already crossed the on-chain threshold? Synchronous and cheap so+ * gating a crypto click never adds latency. We treat as ready: anyone who+ * finished this wizard before, anyone signed in via wallet, or anyone with a+ * live injected-wallet connection this session. The action itself still does+ * real auth — this check only decides whether to *teach*.+ */+export function isOnchainReady() {+ try {+ if (localStorage.getItem(DONE_KEY) === '1') return true;+ const raw = localStorage.getItem(AUTH_HINT_KEY);+ if (raw) {+ const hint = JSON.parse(raw);+ if (hint && hint.authed) return true;+ }+ } catch {+ /* localStorage may be unavailable (private mode) — fall through */+ }+ try {+ if (getWalletState().address) return true;+ } catch {+ /* registry not initialized — fall through */+ }+ return false;+}++function markDone() {+ try {+ localStorage.setItem(DONE_KEY, '1');+ } catch {+ /* non-fatal: the in-session connection still gates correctly */+ }+}++/** Clear the "seen it" flag so the explainer shows again. Used for testing/QA. */+export function resetOnchainPrimer() {+ try {+ localStorage.removeItem(DONE_KEY);+ } catch {+ /* ignore */+ }+}++const STYLE_ID = 'tws-onchain-primer-styles';++function ensureStyles() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const style = document.createElement('style');+ style.id = STYLE_ID;+ style.textContent = `+.tws-primer { max-width: 30rem; }+.tws-primer__lead {+ margin: 0 0 var(--space-md); color: var(--ink-dim);+ font-size: var(--text-md); line-height: var(--leading-normal);+}+.tws-primer__lead b { color: var(--ink); font-weight: var(--weight-semibold); }+.tws-primer__cards { display: grid; gap: var(--space-sm); margin: 0 0 var(--space-md); }+.tws-primer__card {+ display: grid; grid-template-columns: 2rem 1fr; gap: var(--space-sm);+ align-items: start; padding: var(--space-sm) var(--space-md);+ background: var(--surface-1); border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+}+.tws-primer__ico { font-size: 1.1rem; line-height: 1.35; text-align: center; }+.tws-primer__ct { min-width: 0; }+.tws-primer__ct h4 {+ margin: 0 0 2px; font-size: var(--text-md); font-weight: var(--weight-semibold);+ color: var(--ink); letter-spacing: .005em;+}+.tws-primer__ct p {+ margin: 0; font-size: var(--text-sm); line-height: var(--leading-normal);+ color: var(--ink-dim);+}+.tws-primer__reassure {+ display: flex; gap: var(--space-xs); align-items: center;+ margin: 0 0 var(--space-xs); padding: var(--space-sm) var(--space-md);+ background: rgba(74, 222, 128, .08); border: 1px solid rgba(74, 222, 128, .22);+ border-radius: var(--radius-md); color: var(--ink);+ font-size: var(--text-sm); line-height: var(--leading-normal);+}+.tws-primer__reassure .tws-primer__ico { color: var(--success); }+.tws-primer__wallets { display: grid; gap: var(--space-xs); margin: var(--space-sm) 0 0; }+.tws-primer__wallet {+ display: flex; align-items: center; justify-content: space-between;+ gap: var(--space-sm); padding: var(--space-sm) var(--space-md);+ background: var(--surface-1); border: 1px solid var(--stroke);+ border-radius: var(--radius-md); color: var(--ink);+ font-size: var(--text-md); font-weight: var(--weight-medium);+ text-decoration: none; transition: background .15s ease, border-color .15s ease;+}+.tws-primer__wallet:hover { background: var(--surface-2); border-color: var(--stroke-strong); }+.tws-primer__wallet:focus-visible { outline: 2px solid var(--accent-soft); outline-offset: 2px; }+.tws-primer__wallet small { color: var(--ink-dim); font-weight: var(--weight-regular); font-size: var(--text-xs); }+.tws-primer__steps {+ display: flex; gap: var(--space-2xs); align-items: center;+ margin: 0 0 var(--space-sm); font-size: var(--text-2xs);+ color: var(--ink-dim); text-transform: uppercase; letter-spacing: .08em;+}+.tws-primer__dot { width: 6px; height: 6px; border-radius: 50%; background: var(--stroke-strong); }+.tws-primer__dot--on { background: var(--accent); }+.tws-primer__status {+ margin: var(--space-sm) 0 0; min-height: 1.1rem; font-size: var(--text-sm);+ line-height: var(--leading-normal); color: var(--ink-dim);+}+.tws-primer__status--err { color: var(--danger); }+.tws-primer__status--ok { color: var(--success); }+.tws-primer__back {+ background: none; border: none; padding: 0; margin: 0;+ color: var(--ink-dim); font: inherit; font-size: var(--text-sm);+ cursor: pointer; text-decoration: underline; text-underline-offset: 2px;+}+.tws-primer__back:hover { color: var(--ink); }+.tws-primer__actions-row { display: flex; gap: var(--space-sm); flex-wrap: wrap; }+`;+ (document.head || document.documentElement).appendChild(style);+}++function stepDots(active) {+ const dots = [1, 2, 3]+ .map((n) => `<span class="tws-primer__dot${n <= active ? ' tws-primer__dot--on' : ''}"></span>`)+ .join('');+ return `<div class="tws-primer__steps" aria-hidden="true"><span>Step ${active} of 3</span>${dots}</div>`;+}++const CARDS = [+ {+ ico: '💼',+ h: 'A wallet is your account',+ p: 'A free app that holds your money and signs you in — no password, no email. You stay in control; nobody else can move your funds.',+ },+ {+ ico: '💵',+ h: 'USDC is digital dollars',+ p: 'Payments use USDC, a coin pegged to exactly $1. Five USDC is five dollars — no prices to watch.',+ },+ {+ ico: '⚡',+ h: 'Fees are a rounding error',+ p: 'three.ws runs on Solana, where a transaction costs a fraction of a cent — not the steep fees crypto is infamous for.',+ },+];++function explainerBody(action) {+ const lead = ACTIONS[action] || ACTIONS.default;+ const cards = CARDS.map(+ (c) => `+ <div class="tws-primer__card">+ <div class="tws-primer__ico" aria-hidden="true">${c.ico}</div>+ <div class="tws-primer__ct"><h4>${escHtml(c.h)}</h4><p>${escHtml(c.p)}</p></div>+ </div>`,+ ).join('');+ return `+ <div class="tws-primer">+ ${stepDots(1)}+ <p class="tws-primer__lead"><b>${escHtml(lead)}</b> Here's everything you need to know — in plain English.</p>+ <div class="tws-primer__cards">${cards}</div>+ <div class="tws-primer__reassure">+ <span class="tws-primer__ico" aria-hidden="true">✓</span>+ <span>Browsing, building and previewing stay free. You only ever pay when you choose to transact — and you'll always see the amount first.</span>+ </div>+ </div>`;+}++function connectBody({ noWallet = false } = {}) {+ const wallets = WALLETS.map(+ (w) => `+ <a class="tws-primer__wallet" href="${escHtml(w.href)}" target="_blank" rel="noopener noreferrer">+ <span>Get ${escHtml(w.name)}</span><small>${escHtml(w.note)} ↗</small>+ </a>`,+ ).join('');+ return `+ <div class="tws-primer">+ ${stepDots(2)}+ <p class="tws-primer__lead">We'll use your wallet to sign you in securely. One signature — no password to remember, nothing to pay.</p>+ ${+ noWallet+ ? `<p class="tws-primer__lead">You don't have a wallet yet. Install one of these free extensions, then come back and connect:</p>+ <div class="tws-primer__wallets">${wallets}</div>`+ : `<details class="tws-primer__lead"><summary style="cursor:pointer">Don't have a wallet?</summary>+ <div class="tws-primer__wallets" style="margin-top:var(--space-sm)">${wallets}</div></details>`+ }+ <div class="tws-primer__status" id="tws-primer-status" role="status" aria-live="polite"></div>+ </div>`;+}++function readyBody() {+ return `+ <div class="tws-primer">+ ${stepDots(3)}+ <div class="tws-primer__reassure" style="background:rgba(74,222,128,.08)">+ <span class="tws-primer__ico" aria-hidden="true">✓</span>+ <span>Your wallet is connected. You're ready to go on-chain.</span>+ </div>+ <p class="tws-primer__lead">Want a head start? Add some USDC now — or skip it and add funds the moment you transact. Either works.</p>+ </div>`;+}++/**+ * Run the explainer + setup wizard, gating a crypto action.+ *+ * @param {object} [opts]+ * @param {'launch-token'|'monetize'|'tip'|'deploy'|'withdraw'} [opts.action]+ * Drives the one-line framing of why the primer appeared.+ * @param {boolean} [opts.force] Show even if the user is already crypto-ready.+ * @returns {Promise<boolean>} true → proceed; false → user backed out.+ */+export function ensureOnchainPrimer({ action = 'default', force = false } = {}) {+ if (!force && isOnchainReady()) return Promise.resolve(true);+ if (typeof document === 'undefined') return Promise.resolve(true);++ ensureStyles();++ return new Promise((resolve) => {+ // Tracks whether the user reached a wallet-ready state. The modal can be+ // dismissed at any time; we resolve with this so closing *after* connecting+ // still lets the action proceed, while bailing *before* aborts it.+ let ready = false;+ let settled = false;++ const modal = new Modal({+ title: 'Before you go on-chain',+ body: explainerBody(action),+ onClose: () => {+ if (settled) return;+ settled = true;+ resolve(ready);+ },+ });++ const finish = (value) => {+ ready = value;+ settled = true;+ resolve(value);+ modal.destroy();+ };++ // ── Step renderers ────────────────────────────────────────────────────+ function renderExplainer() {+ modal.titleEl.textContent = 'Before you go on-chain';+ modal.bodyEl.innerHTML = explainerBody(action);+ modal.actionsEl.hidden = false;+ modal.actionsEl.innerHTML = `+ <button class="btn btn--ghost" data-act="cancel" type="button">Not now</button>+ <button class="btn btn--primary" data-act="setup" type="button">Set up my wallet <span class="arrow">→</span></button>`;+ }++ function renderConnect({ noWallet = false } = {}) {+ modal.titleEl.textContent = 'Connect your wallet';+ modal.bodyEl.innerHTML = connectBody({ noWallet });+ modal.actionsEl.hidden = false;+ modal.actionsEl.innerHTML = `+ <button class="btn btn--ghost" data-act="back" type="button">← Back</button>+ <button class="btn btn--ghost" data-act="email" type="button">Use email instead</button>+ <button class="btn btn--primary" data-act="connect" type="button">Connect wallet</button>`;+ }++ function renderReady() {+ modal.titleEl.textContent = "You're all set";+ modal.bodyEl.innerHTML = readyBody();+ modal.actionsEl.hidden = false;+ modal.actionsEl.innerHTML = `+ <button class="btn btn--secondary" data-act="fund" type="button">Add USDC</button>+ <button class="btn btn--primary" data-act="continue" type="button">Continue <span class="arrow">→</span></button>`;+ }++ // ── Connect handler — reuses the canonical site sign-in ───────────────+ async function doConnect(btn) {+ const statusEl = modal.bodyEl.querySelector('#tws-primer-status');+ // No injected wallet at all → route to the install-a-wallet view.+ if (!window.ethereum && !window.solana) {+ renderConnect({ noWallet: true });+ return;+ }+ btn.setAttribute('aria-busy', 'true');+ btn.disabled = true;+ if (statusEl) {+ statusEl.className = 'tws-primer__status';+ statusEl.textContent = 'Waiting for your wallet…';+ }+ try {+ await signInWithWallet();+ markDone();+ ready = true; // connected — dismissing now still proceeds+ renderReady();+ } catch (err) {+ btn.removeAttribute('aria-busy');+ btn.disabled = false;+ const msg = String(err?.message || err || '');+ const rejected = /reject|denied|cancell?ed|4001/i.test(msg);+ if (statusEl) {+ statusEl.className = 'tws-primer__status tws-primer__status--err';+ statusEl.textContent = rejected+ ? 'Sign-in cancelled. Click Connect when you’re ready.'+ : `Couldn’t connect: ${msg || 'please try again.'}`;+ }+ }+ }++ // ── Fund handler — reuses the Add-funds overlay ───────────────────────+ async function doFund(btn) {+ const address = (() => {+ try {+ return getWalletState().address || '';+ } catch {+ return '';+ }+ })();+ btn.disabled = true;+ // Close our modal so the funding overlay owns the screen, then resolve+ // regardless of the funding outcome — they're already wallet-ready.+ modal.destroy();+ await showAddFunds({ walletAddress: address }).catch(() => null);+ if (!settled) {+ ready = true;+ settled = true;+ resolve(true);+ }+ }++ // ── One delegated click handler for every step ────────────────────────+ modal.actionsEl.addEventListener('click', (e) => {+ const btn = e.target.closest('button[data-act]');+ if (!btn) return;+ switch (btn.dataset.act) {+ case 'cancel':+ finish(false);+ break;+ case 'setup':+ renderConnect();+ break;+ case 'back':+ renderExplainer();+ break;+ case 'connect':+ doConnect(btn);+ break;+ case 'email':+ try {+ sessionStorage.setItem('login_redirect', location.href);+ } catch {+ /* ignore */+ }+ location.href = '/login?from=onchain-primer';+ break;+ case 'fund':+ doFund(btn);+ break;+ case 'continue':+ finish(true);+ break;+ default:+ break;+ }+ });++ renderExplainer();+ modal.open();+ });+}++if (typeof window !== 'undefined') {+ window.twsOnchainPrimer = {+ ensure: ensureOnchainPrimer,+ isReady: isOnchainReady,+ reset: resetOnchainPrimer,+ };+}diff --git a/src/shared/payment-receipt.js b/src/shared/payment-receipt.jsnew file mode 100644index 000000000..05d87f8f0--- /dev/null+++ b/src/shared/payment-receipt.js@@ -0,0 +1,127 @@+/**+ * payment-receipt.js — human-readable receipt line for confirmed payments.+ *+ * Replaces raw tx hash + explorer links with plain text that reads like any+ * payment app: "✓ Paid $0.01 to Luna's creator · 2s · details ↗"+ *+ * All user-supplied strings are HTML-escaped. Explorer URL is validated to+ * be a known safe domain before being injected as an href.+ */++const SAFE_EXPLORER_ORIGINS = new Set([+ 'https://solscan.io',+ 'https://explorer.solana.com',+ 'https://solana.fm',+ 'https://xray.helius.xyz',+ 'https://etherscan.io',+ 'https://basescan.org',+ 'https://arbiscan.io',+]);++function esc(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++function safeExplorerHref(url) {+ try {+ const u = new URL(url);+ const origin = u.origin.replace(/\/$/, '');+ return SAFE_EXPLORER_ORIGINS.has(origin) ? url : null;+ } catch {+ return null;+ }+}++/**+ * Format USDC atomic units (1e6) or a decimal value to a USD-style string.+ * Automatically detects: values >= 1000 are treated as atomic (micro-USDC),+ * smaller values are treated as already-decimal.+ *+ * @param {number} amount+ * @param {boolean} [isAtomic] force atomic interpretation+ * @returns {string} e.g. "$0.01"+ */+export function formatUsdcAmount(amount, isAtomic = false) {+ const n = Number(amount) || 0;+ const decimal = isAtomic || n >= 1000 ? n / 1e6 : n;+ if (decimal < 0.01) return `$${decimal.toFixed(4)}`;+ if (decimal < 1) return `$${decimal.toFixed(3).replace(/0+$/, '').replace(/\.$/, '.00')}`;+ if (decimal < 100) return `$${decimal.toFixed(2)}`;+ return `$${Math.round(decimal).toLocaleString()}`;+}++/**+ * Format elapsed milliseconds to a compact string ("2s", "1m", "just now").+ * @param {number} ms+ * @returns {string}+ */+export function formatElapsed(ms) {+ const s = Math.round((ms || 0) / 1000);+ if (s < 2) return 'just now';+ if (s < 60) return `${s}s`;+ const m = Math.round(s / 60);+ if (m < 60) return `${m}m`;+ return `${Math.round(m / 60)}h`;+}++/**+ * Build a human-readable receipt HTML string.+ *+ * @param {object} params+ * @param {number} [params.usdAmount] already-decimal USD amount (e.g. 0.01)+ * @param {number} [params.usdcAtomic] atomic USDC (1e6 scale) — used if usdAmount not given+ * @param {string} [params.recipientLabel] e.g. "Luna's creator" or a short address+ * @param {number} [params.elapsedMs] ms since tx sent (used for "2s" timing)+ * @param {string} [params.explorerUrl] full Solscan/explorer URL+ * @param {string} [params.signature] raw tx signature (shown truncated in details fallback)+ * @returns {string} Safe HTML for innerHTML insertion+ */+export function buildReceiptHTML({+ usdAmount,+ usdcAtomic,+ recipientLabel,+ elapsedMs,+ explorerUrl,+ signature,+} = {}) {+ const amountStr =+ usdAmount != null+ ? formatUsdcAmount(usdAmount, false)+ : usdcAtomic != null+ ? formatUsdcAmount(usdcAtomic, true)+ : null;++ const toStr = recipientLabel ? ` to ${esc(recipientLabel)}` : '';+ const timeStr = elapsedMs != null ? ` · ${esc(formatElapsed(elapsedMs))}` : '';+ const amountPart = amountStr ? `${esc(amountStr)}` : 'payment';++ const safeHref = explorerUrl ? safeExplorerHref(explorerUrl) : null;+ let detailsPart = '';+ if (safeHref) {+ detailsPart = ` · <a class="receipt-detail" href="${esc(safeHref)}" target="_blank" rel="noopener noreferrer">details ↗</a>`;+ } else if (signature) {+ const short = `${signature.slice(0, 6)}…${signature.slice(-4)}`;+ detailsPart = ` · <span class="receipt-sig">${esc(short)}</span>`;+ }++ return `<span class="receipt-ok">✓ Paid ${amountPart}${toStr}${timeStr}</span>${detailsPart}`;+}++/**+ * Build a compact single-line plain-text receipt (for status bars / toasts).+ */+export function buildReceiptText({ usdAmount, usdcAtomic, recipientLabel, elapsedMs } = {}) {+ const amountStr =+ usdAmount != null+ ? formatUsdcAmount(usdAmount, false)+ : usdcAtomic != null+ ? formatUsdcAmount(usdcAtomic, true)+ : 'payment';+ const toStr = recipientLabel ? ` to ${recipientLabel}` : '';+ const timeStr = elapsedMs != null ? ` · ${formatElapsed(elapsedMs)}` : '';+ return `✓ Paid ${amountStr}${toStr}${timeStr}`;+}diff --git a/src/shared/share.js b/src/shared/share.jsnew file mode 100644index 000000000..cabe58450--- /dev/null+++ b/src/shared/share.js@@ -0,0 +1,224 @@+/**+ * Share panel — one-tap share for agents, forge creations, and scans.+ *+ * Usage:+ * import { showSharePanel } from './shared/share.js';+ * showSharePanel(+ * { kind: 'agent', id, title, description, shareUrl, remixUrl },+ * triggerElement // optional — focus returns here on close+ * );+ *+ * entity shape:+ * kind 'agent' | 'forge' | 'scan'+ * id string+ * title string+ * description string (optional)+ * shareUrl string — canonical URL that has OG meta+ * remixUrl string — deep-link back into the create flow+ */++import { Modal } from './modal.js';++const STYLE_ID = 'tws-share-styles';+const FARCASTER_COMPOSE = 'https://warpcast.com/~/compose';+const X_INTENT = 'https://x.com/intent/tweet';++export function showSharePanel(entity, triggerEl = null) {+ ensureShareStyles();++ const { title = '', description = '', shareUrl, remixUrl } = entity;++ const xText = encodeURIComponent(`${title} on three.ws\n`);+ const xUrl = encodeURIComponent(shareUrl || location.href);+ const xHref = `${X_INTENT}?text=${xText}&url=${xUrl}`;++ const fcText = encodeURIComponent(`${title} on three.ws — `);+ const fcEmbed = encodeURIComponent(shareUrl || location.href);+ const fcHref = `${FARCASTER_COMPOSE}?text=${fcText}&embeds[]=${fcEmbed}`;++ const descHtml = description+ ? `<p class="tws-sp-desc">${esc(description)}</p>`+ : '';++ const remixHtml = remixUrl+ ? `<a class="tws-sp-btn tws-sp-remix" href="${esc(remixUrl)}">+ ${sparkleIcon()}+ Remix in three.ws →+ </a>`+ : '';++ const body = `+ <div class="tws-sp">+ ${descHtml}+ <button class="tws-sp-btn tws-sp-copy" type="button" data-share-copy="${esc(shareUrl || '')}">+ ${linkIcon()}+ <span class="tws-sp-copy-label">Copy link</span>+ </button>+ <a class="tws-sp-btn tws-sp-x" href="${esc(xHref)}" target="_blank" rel="noopener noreferrer">+ ${xIcon()}+ Share on X+ </a>+ <a class="tws-sp-btn tws-sp-fc" href="${esc(fcHref)}" target="_blank" rel="noopener noreferrer">+ ${farcasterIcon()}+ Share on Farcaster+ </a>+ ${remixHtml}+ </div>+ `;++ const modal = Modal.show({+ title: `Share "${esc(title)}"`,+ body,+ dismissible: true,+ }, triggerEl);++ // Wire copy-link button inside the modal body+ modal.bodyEl.addEventListener('click', async (e) => {+ const btn = e.target.closest('[data-share-copy]');+ if (!btn) return;++ const url = btn.dataset.shareCopy;+ const label = btn.querySelector('.tws-sp-copy-label');+ const original = label?.textContent;++ try {+ if (navigator.clipboard?.writeText) {+ await navigator.clipboard.writeText(url);+ } else {+ // Graceful fallback: create a temporary input, select + copy+ const tmp = document.createElement('input');+ tmp.value = url;+ tmp.style.position = 'absolute';+ tmp.style.opacity = '0';+ document.body.appendChild(tmp);+ tmp.select();+ document.execCommand('copy');+ document.body.removeChild(tmp);+ }++ if (label) {+ label.textContent = 'Copied!';+ btn.classList.add('tws-sp-copy--success');+ setTimeout(() => {+ label.textContent = original;+ btn.classList.remove('tws-sp-copy--success');+ }, 2200);+ }+ } catch {+ if (label) {+ label.textContent = 'Could not copy — try manually';+ setTimeout(() => { label.textContent = original; }, 2800);+ }+ }+ });++ return modal;+}++// ── Icon SVGs ──────────────────────────────────────────────────────────────++function linkIcon() {+ return `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`;+}++function xIcon() {+ // X (formerly Twitter) logo+ return `<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.74l7.73-8.835L1.254 2.25H8.08l4.259 5.631zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>`;+}++function farcasterIcon() {+ return `<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M11.927 2C6.428 2 2 6.42 2 11.908s4.428 9.908 9.927 9.908c5.5 0 9.927-4.42 9.927-9.908C21.854 6.42 17.427 2 11.927 2zM8.5 7.5h7l.5 2h-1.5v5.5h-1.5V9.5h-1.5v5.5H10V9.5H8.5L8.5 7.5z"/></svg>`;+}++function sparkleIcon() {+ return `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2l2.4 7.2 7.6 0-6.2 4.4 2.4 7.4-6.2-4.4-6.2 4.4 2.4-7.4-6.2-4.4 7.6 0z"/></svg>`;+}++// ── Helpers ────────────────────────────────────────────────────────────────++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++function ensureShareStyles() {+ if (typeof document === 'undefined') return;+ if (document.getElementById(STYLE_ID)) return;+ const style = document.createElement('style');+ style.id = STYLE_ID;+ style.textContent = SHARE_CSS;+ (document.head || document.documentElement).appendChild(style);+}++const SHARE_CSS = `+/* ── Share panel — tws-sp-* ─────────────────────────────────────────────── */++.tws-sp {+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 4px 0 2px;+}++.tws-sp-desc {+ margin: 0 0 6px;+ font-size: 13px;+ color: var(--ink-dim, #888);+ line-height: 1.5;+}++.tws-sp-btn {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 12px 16px;+ border-radius: var(--radius-control, 10px);+ font: 500 14px/1 var(--font-body, system-ui, sans-serif);+ cursor: pointer;+ text-decoration: none;+ border: 1px solid var(--stroke, rgba(255,255,255,0.08));+ background: var(--surface-2, rgba(255,255,255,0.04));+ color: var(--ink, #e8e8e8);+ transition: background 0.14s ease, border-color 0.14s ease, transform 0.1s ease;+ width: 100%;+ box-sizing: border-box;+}+.tws-sp-btn:hover {+ background: var(--surface-3, rgba(255,255,255,0.09));+ border-color: var(--stroke-strong, rgba(255,255,255,0.15));+}+.tws-sp-btn:active { transform: translateY(1px); }+.tws-sp-btn:focus-visible {+ outline: 2px solid rgba(255,255,255,0.35);+ outline-offset: 2px;+}++/* Copy button */+.tws-sp-copy--success {+ border-color: var(--accent, rgba(255,255,255,0.3)) !important;+ color: var(--ink, #e8e8e8);+}++/* Remix CTA — primary style */+.tws-sp-remix {+ background: var(--btn-primary-bg, rgba(255,255,255,0.9));+ color: var(--btn-primary-fg, #0a0a0f);+ border-color: transparent;+ margin-top: 4px;+ font-weight: 600;+}+.tws-sp-remix:hover {+ background: var(--btn-primary-bg-hover, rgba(255,255,255,0.85));+ color: var(--btn-primary-fg, #0a0a0f);+}+.tws-sp-remix svg { color: inherit; }++@media (max-width: 400px) {+ .tws-sp-btn { padding: 11px 12px; font-size: 13px; }+}+`;++if (typeof window !== 'undefined') {+ window.twsShare = { showSharePanel };+}diff --git a/src/shared/state-kit.js b/src/shared/state-kit.jsnew file mode 100644index 000000000..9d4aaf8a3--- /dev/null+++ b/src/shared/state-kit.js@@ -0,0 +1,484 @@+/**+ * Shared loading / empty / error state components.+ *+ * Exposes token-driven skeleton-loading, empty-state, and error-state shells+ * that every grid or list surface can drop in without hand-rolling its own.+ * The visual shell is owned here; copy (especially crypto-failure messages)+ * is supplied by callers via the title/body props so C07 can swap strings+ * without touching markup or CSS.+ *+ * Pattern mirrors src/shared/onchain-badge.js:+ * import { skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles, attachRetry } from './state-kit.js';+ *+ * CSS is injected once via ensureStateKitStyles(); call it before rendering+ * any HTML string from this module.+ */++const STYLE_ID = 'tws-state-kit-styles';++function esc(s) {+ return String(s == null ? '' : s).replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++// ── CSS injection ──────────────────────────────────────────────────────────++/** Inject the state-kit stylesheet once. Idempotent and SSR-safe. */+export function ensureStateKitStyles() {+ if (typeof document === 'undefined') return;+ if (document.getElementById(STYLE_ID)) return;+ const style = document.createElement('style');+ style.id = STYLE_ID;+ style.textContent = STATE_KIT_CSS;+ (document.head || document.documentElement).appendChild(style);+}++// ── Skeleton ───────────────────────────────────────────────────────────────++/**+ * Skeleton placeholder HTML for a card grid.+ *+ * @param {number} count Number of skeleton cards to render.+ * @param {'card'|'row'|'text'} variant+ * card — square-thumb card (default, matches market/forge grids)+ * row — horizontal list row (dashboard lists)+ * text — text-only block (activity feeds)+ * @returns {string} HTML string; wrap in a grid container before inserting.+ */+export function skeletonHTML(count = 6, variant = 'card') {+ ensureStateKitStyles();+ const items = Array.from({ length: count }, () => {+ if (variant === 'row') {+ return `<div class="tws-sk tws-sk--row" aria-hidden="true">+ <div class="tws-sk-avatar"></div>+ <div class="tws-sk-body">+ <div class="tws-sk-line"></div>+ <div class="tws-sk-line tws-sk-line--short"></div>+ </div>+ </div>`;+ }+ if (variant === 'text') {+ return `<div class="tws-sk tws-sk--text" aria-hidden="true">+ <div class="tws-sk-line"></div>+ <div class="tws-sk-line tws-sk-line--medium"></div>+ <div class="tws-sk-line tws-sk-line--short"></div>+ </div>`;+ }+ // card (default)+ return `<div class="tws-sk tws-sk--card" aria-hidden="true">+ <div class="tws-sk-thumb"></div>+ <div class="tws-sk-line"></div>+ <div class="tws-sk-line tws-sk-line--short"></div>+ </div>`;+ });+ return items.join('');+}++/**+ * Skeleton as a DocumentFragment for DOM-build render sites.+ */+export function skeletonEl(count = 6, variant = 'card') {+ const html = skeletonHTML(count, variant);+ const tpl = document.createElement('template');+ tpl.innerHTML = html;+ return tpl.content;+}++// ── Empty state ────────────────────────────────────────────────────────────++/**+ * Empty-state HTML block.+ *+ * @param {object} opts+ * @param {string} [opts.icon] Emoji or raw SVG string. Omit for the default dot grid;+ * pass an empty string ('') to render no icon at all.+ * @param {string} opts.title Headline — required.+ * @param {string} opts.body Helper copy — required. Pre-escaped HTML ok.+ * @param {Array<{label:string, id?:string, href?:string, primary?:boolean}>} [opts.actions]+ * Mark one action `primary: true` for the main CTA; others render as secondary buttons.+ * @param {boolean} [opts.live] Use aria-live="polite" (for in-place updates); default false → role="status".+ * @param {boolean} [opts.compact] Tighter padding + smaller icon for inline panels, table+ * cells, tickers and side-rail feeds (vs. full-page grids).+ * @param {string} [opts.tip] Optional technical detail tucked behind an info tooltip+ * (keeps the headline copy plain — see three-live).+ * @returns {string} HTML string.+ */+export function emptyStateHTML({ icon, title, body, actions = [], live = false, compact = false, tip } = {}) {+ ensureStateKitStyles();++ const defaultDot = `<div class="tws-es-icon tws-es-icon--dot" aria-hidden="true"><svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="8" cy="8" r="2.5" fill="currentColor" opacity=".25"/><circle cx="20" cy="8" r="2.5" fill="currentColor" opacity=".35"/><circle cx="32" cy="8" r="2.5" fill="currentColor" opacity=".25"/><circle cx="8" cy="20" r="2.5" fill="currentColor" opacity=".35"/><circle cx="20" cy="20" r="3" fill="currentColor" opacity=".6"/><circle cx="32" cy="20" r="2.5" fill="currentColor" opacity=".35"/><circle cx="8" cy="32" r="2.5" fill="currentColor" opacity=".25"/><circle cx="20" cy="32" r="2.5" fill="currentColor" opacity=".35"/><circle cx="32" cy="32" r="2.5" fill="currentColor" opacity=".25"/></svg></div>`;+ const iconHtml = icon === undefined+ ? defaultDot+ : icon+ ? `<div class="tws-es-icon">${icon}</div>`+ : '';++ const ariaAttr = live ? 'aria-live="polite"' : 'role="status"';++ const btns = actions.map((a) => {+ if (a.href) {+ return `<a class="tws-es-btn${a.primary ? ' tws-es-btn--primary' : ''}" href="${esc(a.href)}"${a.id ? ` data-sk-action="${esc(a.id)}"` : ''}>${esc(a.label)}</a>`;+ }+ return `<button type="button" class="tws-es-btn${a.primary ? ' tws-es-btn--primary' : ''}"${a.id ? ` data-sk-action="${esc(a.id)}"` : ''}>${esc(a.label)}</button>`;+ }).join('');++ const tipHtml = tip+ ? `<span class="tws-es-tip" tabindex="0" role="note" aria-label="${esc(tip)}" data-tws-tip="${esc(tip)}"><svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden="true"><circle cx="8" cy="8" r="7" stroke="currentColor" stroke-width="1.3" opacity=".5"/><path d="M8 7v4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><circle cx="8" cy="4.5" r=".9" fill="currentColor"/></svg></span>`+ : '';++ return `<div class="tws-es${compact ? ' tws-es--compact' : ''}" ${ariaAttr}>+ ${iconHtml}+ <h3 class="tws-es-title">${esc(title)}</h3>+ <p class="tws-es-body">${body}${tipHtml}</p>+ ${btns ? `<div class="tws-es-actions">${btns}</div>` : ''}+ </div>`;+}++/** Empty state as a DOM Element. */+export function emptyStateEl(opts = {}) {+ const tpl = document.createElement('template');+ tpl.innerHTML = emptyStateHTML(opts).trim();+ return tpl.content.firstElementChild;+}++// ── Error state ────────────────────────────────────────────────────────────++/**+ * Error-state HTML block.+ *+ * Visual shell only — the caller supplies copy. C07 owns crypto-failure messages.+ *+ * @param {object} opts+ * @param {string} [opts.title] Defaults to "Something went wrong".+ * @param {string} [opts.body] Error description. Pre-escaped HTML ok.+ * @param {string} [opts.scope] Data attribute on retry button for delegation ('agents'|'skills'|...).+ * @param {Array<{label:string, id?:string, primary?:boolean}>} [opts.actions]+ * When omitted, a single "Retry" primary button is rendered automatically.+ * @returns {string} HTML string.+ */+export function errorStateHTML({ title, body, scope = '', actions } = {}) {+ ensureStateKitStyles();++ const heading = title || 'Something went wrong';+ const desc = body || 'Check your connection and try again.';++ let btns;+ if (actions && actions.length) {+ btns = actions.map((a) =>+ `<button type="button" class="tws-es-btn${a.primary ? ' tws-es-btn--primary' : ''}"${a.id ? ` data-sk-action="${esc(a.id)}"` : ''}${scope ? ` data-sk-scope="${esc(scope)}"` : ''}>${esc(a.label)}</button>`+ ).join('');+ } else {+ btns = `<button type="button" class="tws-es-btn tws-es-btn--primary" data-sk-retry${scope ? ` data-sk-scope="${esc(scope)}"` : ''}>Retry</button>`;+ }++ return `<div class="tws-es tws-es--error" role="alert">+ <div class="tws-es-icon tws-es-icon--err" aria-hidden="true"><svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="16" cy="16" r="14" stroke="currentColor" stroke-width="1.5" opacity=".35"/><path d="M16 9v8" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><circle cx="16" cy="22.5" r="1.25" fill="currentColor"/></svg></div>+ <h3 class="tws-es-title">${esc(heading)}</h3>+ <p class="tws-es-body">${desc}</p>+ <div class="tws-es-actions">${btns}</div>+ </div>`;+}++/** Error state as a DOM Element. */+export function errorStateEl(opts = {}) {+ const tpl = document.createElement('template');+ tpl.innerHTML = errorStateHTML(opts).trim();+ return tpl.content.firstElementChild;+}++// ── Retry wiring ───────────────────────────────────────────────────────────++/**+ * Attach a retry handler to all [data-sk-retry] buttons within a container.+ * Uses event delegation so it survives innerHTML re-renders.+ *+ * @param {Element} container The element whose innerHTML may contain retry buttons.+ * @param {function} retryFn Called with no arguments when a retry button is clicked.+ */+export function attachRetry(container, retryFn) {+ if (!container || typeof retryFn !== 'function') return;+ container.addEventListener('click', (e) => {+ if (e.target.closest('[data-sk-retry]')) retryFn();+ });+}++// ── CSS ────────────────────────────────────────────────────────────────────++const STATE_KIT_CSS = `+/* ═══════════════════════════════════════════════════════════════════════════+ three.ws state-kit — skeleton / empty / error shared components+ Source: src/shared/state-kit.js · Namespace: tws-sk-* / tws-es-*+ ═══════════════════════════════════════════════════════════════════════════ */++/* ── Skeleton shimmer keyframe (GPU-composited transform) ── */+@keyframes tws-sk-sweep {+ 0% { transform: translateX(-150%); }+ 100% { transform: translateX(150%); }+}++/* ── Skeleton base ── */+.tws-sk {+ position: relative;+ overflow: hidden;+ border-radius: var(--radius-card, 14px);+ background: var(--surface-2, rgba(255,255,255,0.05));+ border: 1px solid var(--stroke, rgba(255,255,255,0.07));+}++/* Shimmer overlay on all skeleton children with the class */+.tws-sk-thumb,+.tws-sk-line,+.tws-sk-avatar {+ position: relative;+ overflow: hidden;+ background: var(--surface-3, rgba(255,255,255,0.08));+ border-radius: var(--radius-sm, 4px);+}+.tws-sk-thumb::after,+.tws-sk-line::after,+.tws-sk-avatar::after {+ content: '';+ position: absolute;+ inset: 0;+ transform: translateX(-150%);+ background: linear-gradient(+ 90deg,+ transparent 0%,+ rgba(255, 255, 255, 0.06) 50%,+ transparent 100%+ );+ animation: tws-sk-sweep 1.6s ease-in-out infinite;+}++/* Card variant — vertical, square thumb */+.tws-sk--card {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 14px;+ min-height: 240px;+}+.tws-sk--card .tws-sk-thumb {+ flex: 1;+ border-radius: var(--radius-md, 8px);+ min-height: 140px;+}+.tws-sk--card .tws-sk-line {+ height: 12px;+ width: 100%;+}+.tws-sk--card .tws-sk-line.tws-sk-line--short { width: 55%; }+.tws-sk--card .tws-sk-line.tws-sk-line--medium { width: 75%; }++/* Row variant — horizontal, avatar + lines */+.tws-sk--row {+ display: flex;+ align-items: center;+ gap: 14px;+ padding: 14px 16px;+ border-radius: var(--radius-md, 8px);+}+.tws-sk--row .tws-sk-avatar {+ width: 40px;+ height: 40px;+ border-radius: 50%;+ flex-shrink: 0;+}+.tws-sk--row .tws-sk-body {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.tws-sk--row .tws-sk-line {+ height: 11px;+ width: 100%;+}+.tws-sk--row .tws-sk-line.tws-sk-line--short { width: 45%; }++/* Text variant — lines only */+.tws-sk--text {+ display: flex;+ flex-direction: column;+ gap: 9px;+ padding: 16px;+ border-radius: var(--radius-md, 8px);+}+.tws-sk--text .tws-sk-line {+ height: 11px;+ width: 100%;+}+.tws-sk--text .tws-sk-line.tws-sk-line--medium { width: 72%; }+.tws-sk--text .tws-sk-line.tws-sk-line--short { width: 40%; }++/* ── Empty + error state shell ── */+.tws-es {+ display: flex;+ flex-direction: column;+ align-items: center;+ text-align: center;+ gap: 10px;+ padding: 56px 24px 48px;+ /* span full grid width when inside a CSS grid */+ grid-column: 1 / -1;+}++.tws-es-icon {+ font-size: 36px;+ line-height: 1;+ margin-bottom: 4px;+ color: var(--ink-dim, #888);+ opacity: 0.7;+}+.tws-es-icon--dot {+ color: var(--ink-dim, #888);+}+.tws-es-icon--err {+ color: var(--danger, #f87171);+ opacity: 0.85;+}++.tws-es-title {+ margin: 0;+ font-size: 15px;+ font-weight: 600;+ color: var(--ink, #e8e8e8);+ letter-spacing: -.01em;+}++.tws-es-body {+ margin: 0;+ font-size: 13.5px;+ line-height: 1.55;+ color: var(--ink-dim, #888);+ max-width: 340px;+}++.tws-es-actions {+ display: flex;+ gap: 10px;+ flex-wrap: wrap;+ justify-content: center;+ margin-top: 8px;+}++/* Compact modifier — tighter footprint for inline panels, table cells,+ tickers and side-rail feeds (vs. full-page grids). */+.tws-es--compact {+ padding: 22px 16px 20px;+ gap: 7px;+}+.tws-es--compact .tws-es-icon {+ font-size: 26px;+ margin-bottom: 2px;+}+.tws-es--compact .tws-es-icon--dot svg { width: 30px; height: 30px; }+.tws-es--compact .tws-es-title { font-size: 14px; }+.tws-es--compact .tws-es-body { font-size: 12.5px; line-height: 1.5; }+.tws-es--compact .tws-es-actions { margin-top: 4px; }++/* Error modifier — title color shifts to danger */+.tws-es--error .tws-es-title {+ color: var(--danger, #f87171);+}++/* ── Info tooltip (tucks technical detail behind a hover/focus affordance) ── */+.tws-es-tip {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ vertical-align: middle;+ margin-left: 6px;+ width: 16px;+ height: 16px;+ color: var(--ink-dim, #888);+ cursor: help;+ border-radius: 50%;+ position: relative;+ transition: color 0.15s ease;+}+.tws-es-tip:hover,+.tws-es-tip:focus-visible { color: var(--ink, #e8e8e8); }+.tws-es-tip:focus-visible {+ outline: 2px solid rgba(255,255,255,0.4);+ outline-offset: 2px;+}+.tws-es-tip::after {+ content: attr(data-tws-tip);+ position: absolute;+ bottom: calc(100% + 8px);+ left: 50%;+ transform: translateX(-50%) translateY(4px);+ width: max-content;+ max-width: 240px;+ padding: 7px 10px;+ border-radius: var(--radius-sm, 6px);+ background: var(--modal-bg, rgba(10,11,18,0.96));+ border: 1px solid var(--stroke-strong, rgba(255,255,255,0.14));+ box-shadow: var(--shadow-2, 0 4px 24px rgba(0,0,0,0.4));+ color: var(--ink, #e8e8e8);+ font-size: 11.5px;+ font-weight: 500;+ line-height: 1.4;+ text-align: left;+ white-space: normal;+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.15s ease, transform 0.15s ease;+ z-index: 10;+}+.tws-es-tip:hover::after,+.tws-es-tip:focus-visible::after {+ opacity: 1;+ transform: translateX(-50%) translateY(0);+}++/* ── State-kit buttons (CTA + retry) ── */+.tws-es-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 6px;+ padding: var(--btn-pad-y, 0.618rem) var(--btn-pad-x, 1rem);+ border-radius: var(--btn-radius, var(--radius-control, 10px));+ font: 600 var(--btn-text-size, 13px)/1 var(--font-body, system-ui, sans-serif);+ cursor: pointer;+ border: 1px solid var(--btn-secondary-border, rgba(255,255,255,0.1));+ background: var(--btn-secondary-bg, rgba(255,255,255,0.08));+ color: var(--btn-secondary-fg, var(--ink, #e8e8e8));+ text-decoration: none;+ transition: background 0.15s ease, border-color 0.15s ease, transform 0.12s ease;+}+.tws-es-btn:hover {+ background: var(--btn-secondary-bg-hover, rgba(255,255,255,0.12));+ border-color: var(--stroke-strong, rgba(255,255,255,0.18));+}+.tws-es-btn:active { transform: translateY(1px); }+.tws-es-btn:focus-visible {+ outline: 2px solid rgba(255,255,255,0.4);+ outline-offset: 2px;+}+.tws-es-btn--primary {+ background: var(--btn-primary-bg, rgba(255,255,255,0.9));+ color: var(--btn-primary-fg, #0a0a0f);+ border-color: transparent;+}+.tws-es-btn--primary:hover {+ background: var(--btn-primary-bg-hover, rgba(255,255,255,0.88));+}++/* ── Reduced motion ── */+@media (prefers-reduced-motion: reduce) {+ .tws-sk-thumb::after,+ .tws-sk-line::after,+ .tws-sk-avatar::after {+ animation: none;+ }+}+`;++if (typeof window !== 'undefined') {+ window.twsStateKit = { skeletonHTML, skeletonEl, emptyStateHTML, emptyStateEl, errorStateHTML, errorStateEl, ensureStateKitStyles, attachRetry };+}diff --git a/src/shared/usd-price.js b/src/shared/usd-price.jsnew file mode 100644index 000000000..4d85bd8bd--- /dev/null+++ b/src/shared/usd-price.js@@ -0,0 +1,115 @@+/**+ * Client-side SOL/USD price helper — single source of truth for USD equivalents.+ *+ * USDC: treated as exactly $1 (it's a dollar-pegged stablecoin).+ * SOL: fetched from Jupiter Lite API (CoinGecko fallback), cached 60 s.+ *+ * Never hardcodes a SOL rate; degrades silently on feed failure so prices+ * in USDC still show "≈ $X" while SOL amounts just show the raw amount.+ */++const SOL_MINT = 'So11111111111111111111111111111111111111112';+const CACHE_TTL_MS = 60_000;++let _solPrice = 0;+let _solPriceAt = 0;++/** Fetch (and cache) the live SOL/USD price. Throws if the feed is unavailable. */+export async function getSolPriceUsd() {+ if (Date.now() - _solPriceAt < CACHE_TTL_MS && _solPrice > 0) return _solPrice;+ try {+ const r = await fetch(`https://lite-api.jup.ag/price/v3?ids=${SOL_MINT}`);+ if (r.ok) {+ const data = await r.json();+ const p = data?.[SOL_MINT]?.usdPrice ?? data?.[SOL_MINT]?.price ?? 0;+ if (Number(p) > 0) {+ _solPrice = Number(p);+ _solPriceAt = Date.now();+ return _solPrice;+ }+ }+ } catch { /* fall through to CoinGecko */ }+ try {+ const cg = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd');+ if (!cg.ok) throw new Error(`CoinGecko ${cg.status}`);+ const j = await cg.json();+ const p = j?.solana?.usd ?? 0;+ if (Number(p) > 0) {+ _solPrice = Number(p);+ _solPriceAt = Date.now();+ return _solPrice;+ }+ } catch { /* fall through */ }+ throw Object.assign(new Error('SOL price unavailable'), { code: 'price_unavailable' });+}++/** USDC → USD (1:1, pegged stablecoin). */+export function usdcToUsd(amount) {+ return Number(amount);+}++/** SOL → USD using the live feed. Returns null if the feed fails. */+export async function solToUsd(solAmount) {+ try {+ const price = await getSolPriceUsd();+ return Number(solAmount) * price;+ } catch {+ return null;+ }+}++function fmtUsdValue(n) {+ if (!Number.isFinite(n) || n < 0) return '';+ if (n === 0) return '≈ $0.00';+ if (n < 0.0001) return `≈ $${n.toFixed(6).replace(/0+$/, '')}`;+ if (n < 0.01) return `≈ $${n.toFixed(4)}`;+ if (n < 1) return `≈ $${n.toFixed(3)}`;+ if (n < 1000) return `≈ $${n.toFixed(2)}`;+ return `≈ $${Math.round(n).toLocaleString()}`;+}++/** Format a USDC amount as a USD equivalent string (synchronous, no feed needed). */+export function formatUsdcEq(usdcAmount) {+ return fmtUsdValue(usdcToUsd(usdcAmount));+}++/** Format a SOL amount as a USD equivalent string (async, needs live feed). */+export async function formatSolEq(solAmount) {+ const usd = await solToUsd(solAmount);+ return usd !== null ? fmtUsdValue(usd) : '';+}++/**+ * Attach a live USD-equivalent hint to a DOM element.+ *+ * Immediately inserts a `<span class="usd-eq">` next to the element's price+ * text (hidden while loading). Once the price resolves, the span becomes+ * visible with "≈ $X.XX". On feed failure for SOL, the span stays hidden —+ * the original crypto amount is unaffected.+ *+ * @param {Element} el Element that holds or follows the price display+ * @param {number} amount Crypto amount (human units: USDC or SOL)+ * @param {string} currency 'USDC' | 'SOL'+ * @returns {HTMLSpanElement} The injected span (can be discarded)+ */+export function attachUsdEq(el, amount, currency) {+ let span = el.querySelector('.usd-eq');+ if (!span) {+ span = document.createElement('span');+ span.className = 'usd-eq';+ el.appendChild(span);+ }+ span.textContent = '';+ span.hidden = true;++ const cur = (currency || '').toUpperCase();+ if (cur === 'USDC') {+ const eq = formatUsdcEq(amount);+ if (eq) { span.textContent = eq; span.hidden = false; }+ } else if (cur === 'SOL') {+ formatSolEq(amount).then((eq) => {+ if (eq) { span.textContent = eq; span.hidden = false; }+ });+ }+ return span;+}