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: inline payment chip, topbar notifications, GMGN nav + fixes
nirholasd9c73f3180cc
diff --git a/api/embed/resolve.js b/api/embed/resolve.jsnew file mode 100644index 000000000..bb842cccf--- /dev/null+++ b/api/embed/resolve.js@@ -0,0 +1,125 @@+/**+ * GET /api/embed/resolve?id=<spec>+ *+ * Resolves a flexible ID spec to the minimal payload an embed needs to render+ * an agent: { glbUrl, name, poster, kind, ...minimal metadata }.+ *+ * Supported ID specs (kept tiny on purpose):+ * - "<chainId>:<agentId>" → on-chain ERC-8004 agent e.g. "8453:42"+ * - "eip155:<chainId>:<agentId>" → same, namespaced form e.g. "eip155:8453:42"+ * - "avatar:<uuid>" → public avatar e.g. "avatar:8e3...c1"+ *+ * Cross-origin by design (Access-Control-Allow-Origin: *). Cached aggressively+ * at the edge so an embed loading in 10k pages doesn't hammer the DB.+ */++import { sql } from '../_lib/db.js';+import { cors, method, wrap, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { CHAIN_BY_ID } from '../_lib/erc8004-chains.js';+import { publicUrl } from '../_lib/r2.js';+import { DEMO_AVATARS } from '../_lib/demo-avatars.js';++const ONCHAIN_RE = /^(?:eip155:)?(\d{1,9})[:/](\d{1,12})$/;+const AVATAR_RE = /^avatar:([a-zA-Z0-9_-]{3,64})$/;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const url = new URL(req.url, 'http://x');+ const id = (url.searchParams.get('id') || '').trim();+ if (!id) return error(res, 400, 'validation_error', 'id is required');++ const onchain = id.match(ONCHAIN_RE);+ if (onchain) {+ const chainId = parseInt(onchain[1], 10);+ const agentId = parseInt(onchain[2], 10);+ const rows = await sql`+ SELECT chain_id, agent_id, name, description, image, glb_url, has_3d, x402_support+ FROM erc8004_agents_index+ WHERE active = true AND chain_id = ${chainId} AND agent_id = ${agentId}+ LIMIT 1+ `;+ if (!rows.length) return error(res, 404, 'not_found', 'agent not found');++ const r = rows[0];+ const chain = CHAIN_BY_ID[r.chain_id];+ return embedJson(res, {+ kind: 'onchain',+ id: `${r.chain_id}:${r.agent_id}`,+ chainId: r.chain_id,+ chainName: chain?.name || `Chain ${r.chain_id}`,+ agentId: r.agent_id,+ name: r.name || `Agent #${r.agent_id}`,+ description: r.description || '',+ glbUrl: r.glb_url || null,+ poster: r.image || null,+ has3d: !!r.has_3d,+ x402: !!r.x402_support,+ passportUrl: `/discover/a/${r.chain_id}/${r.agent_id}`,+ });+ }++ const avatar = id.match(AVATAR_RE);+ if (avatar) {+ const avatarId = avatar[1];+ const demo = DEMO_AVATARS.find((a) => String(a.avatarId) === String(avatarId));+ if (demo) {+ return embedJson(res, {+ kind: 'avatar',+ id: `avatar:${demo.avatarId}`,+ name: demo.name,+ description: demo.description || '',+ glbUrl: demo.glbUrl || null,+ poster: demo.image || null,+ has3d: true,+ x402: false,+ passportUrl: `/discover/avatar/${demo.avatarId}`,+ });+ }++ const rows = await sql`+ SELECT id, name, description, storage_key, thumbnail_key+ FROM avatars+ WHERE deleted_at IS NULL AND visibility = 'public' AND id = ${avatarId}+ LIMIT 1+ `;+ if (!rows.length) return error(res, 404, 'not_found', 'avatar not found');++ const r = rows[0];+ return embedJson(res, {+ kind: 'avatar',+ id: `avatar:${r.id}`,+ name: r.name,+ description: r.description || '',+ glbUrl: publicUrl(r.storage_key),+ poster: r.thumbnail_key ? publicUrl(r.thumbnail_key) : null,+ has3d: true,+ x402: false,+ passportUrl: `/discover/avatar/${r.id}`,+ });+ }++ return error(+ res,+ 400,+ 'validation_error',+ 'id must be "<chainId>:<agentId>", "eip155:<chainId>:<agentId>", or "avatar:<uuid>"',+ );+});++function embedJson(res, payload) {+ res.statusCode = 200;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('access-control-allow-origin', '*');+ res.setHeader('cross-origin-resource-policy', 'cross-origin');+ res.setHeader(+ 'cache-control',+ 'public, max-age=60, s-maxage=300, stale-while-revalidate=86400',+ );+ res.end(JSON.stringify(payload));+}diff --git a/public/dashboard-next/shell.css b/public/dashboard-next/shell.cssindex 0b09c2bae..8c2712cff 100644--- a/public/dashboard-next/shell.css+++ b/public/dashboard-next/shell.css@@ -142,6 +142,14 @@ button { font: inherit; }[data-rail-collapsed='true'] .dn-rail-item-text { display: none; }[data-rail-collapsed='true'] .dn-rail-item { justify-content: center; padding: 10px; }+.dn-rail-item-ext {+ display: inline-flex;+ align-items: center;+ margin-left: 4px;+ opacity: 0.5;+ vertical-align: middle;+}+.dn-rail-foot {padding: 12px 10px;border-top: 1px solid var(--nxt-stroke);diff --git a/public/embed/v1.js b/public/embed/v1.jsnew file mode 100644index 000000000..54b55750f--- /dev/null+++ b/public/embed/v1.js@@ -0,0 +1,410 @@+/**+ * three.ws — embed v1+ *+ * The 3D layer of the internet, in one script tag.+ *+ * <script src="https://three.ws/embed/v1.js" async></script>+ * <three-d agent="8453:42"></three-d>+ *+ * Or fully drop-in (no markup needed):+ *+ * <script src="https://three.ws/embed/v1.js" data-agent="8453:42" async></script>+ *+ * Or programmatic:+ *+ * Three.mount('#root', { agent: '8453:42', interactive: true });+ *+ * Registers three element aliases — <three-d>, <three-agent>, <three-ws> —+ * that all behave identically. Lives entirely alongside the legacy embed.js+ * widget loader; nothing existing is touched.+ *+ * Renderer: model-viewer 4.0.0 (Apache 2.0), lazy-loaded from Google's CDN on+ * first instance. Loader script itself is ~6KB minified.+ *+ * Performance contract:+ * - First contentful paint within 200ms of script load (poster image only)+ * - WebGL boot deferred until element scrolls into viewport (IntersectionObserver)+ * - prefers-reduced-motion respected (auto-rotate disabled)+ * - WebGL failures degrade to poster + caption, never a black box+ */++(function () {+ 'use strict';++ if (window.__threeWsEmbedV1) return; // idempotent — multiple includes are safe+ window.__threeWsEmbedV1 = true;++ var ORIGIN = (function () {+ try {+ return new URL(document.currentScript.src).origin;+ } catch (_) {+ return 'https://three.ws';+ }+ })();++ var MV_CDN = 'https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js';++ // model-viewer is loaded once, lazily, on first <three-d> instance.+ // All instances share the same Promise so we never fetch it twice.+ var modelViewerReady = null;+ function ensureModelViewer() {+ if (modelViewerReady) return modelViewerReady;+ modelViewerReady = new Promise(function (resolve, reject) {+ if (window.customElements && customElements.get('model-viewer')) return resolve();+ var s = document.createElement('script');+ s.type = 'module';+ s.src = MV_CDN;+ s.onload = function () { resolve(); };+ s.onerror = function () { reject(new Error('model-viewer failed to load')); };+ document.head.appendChild(s);+ });+ return modelViewerReady;+ }++ // Resolver cache — embeds for the same agent on a single page share one+ // fetch. Cleared on navigation, never persisted.+ var resolverCache = Object.create(null);+ function resolve(id) {+ if (resolverCache[id]) return resolverCache[id];+ resolverCache[id] = fetch(+ ORIGIN + '/api/embed/resolve?id=' + encodeURIComponent(id),+ { credentials: 'omit' },+ ).then(function (r) {+ if (!r.ok) throw new Error('resolve failed: ' + r.status);+ return r.json();+ }).catch(function (err) {+ delete resolverCache[id]; // allow retry+ throw err;+ });+ return resolverCache[id];+ }++ var REDUCED_MOTION = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;++ // Tracks which instances are visible so we only boot WebGL for ones that+ // matter. One shared observer for the whole page.+ var visibilityObserver = null;+ function observeVisibility(el) {+ if (!('IntersectionObserver' in window)) {+ el.__threeVisible = true;+ el.__bootIfReady && el.__bootIfReady();+ return;+ }+ if (!visibilityObserver) {+ visibilityObserver = new IntersectionObserver(function (entries) {+ entries.forEach(function (entry) {+ if (entry.isIntersecting) {+ entry.target.__threeVisible = true;+ entry.target.__bootIfReady && entry.target.__bootIfReady();+ visibilityObserver.unobserve(entry.target);+ }+ });+ }, { rootMargin: '200px' });+ }+ visibilityObserver.observe(el);+ }++ // -------- The element -------------------------------------------------++ var STYLE = ''+ + ':host{display:inline-block;position:relative;width:100%;max-width:100%;'+ + 'background:#0a0a0c;border-radius:14px;overflow:hidden;'+ + 'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,sans-serif;'+ + 'color:#fff;line-height:1.4;contain:layout style;}'+ + ':host([theme="light"]){background:#f7f7f8;color:#111;}'+ + ':host([theme="transparent"]){background:transparent;}'+ + '.stage{position:relative;width:100%;height:100%;min-height:280px;display:block;}'+ + ':host([height]) .stage{min-height:0;}'+ + 'model-viewer{width:100%;height:100%;display:block;background:transparent;'+ + '--poster-color:transparent;--progress-bar-color:rgba(255,255,255,.5);--progress-bar-height:2px;}'+ + '.poster{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;'+ + 'background:linear-gradient(135deg,#111 0%,#1c1c22 100%);transition:opacity .35s;}'+ + '.poster--gone{opacity:0;pointer-events:none;}'+ + '.chrome{position:absolute;left:10px;right:10px;bottom:10px;display:flex;'+ + 'align-items:center;gap:8px;pointer-events:none;}'+ + '.chrome a{pointer-events:auto;}'+ + '.name{font-size:13px;font-weight:600;letter-spacing:.01em;'+ + 'background:rgba(0,0,0,.55);backdrop-filter:blur(8px);'+ + '-webkit-backdrop-filter:blur(8px);padding:6px 10px;border-radius:999px;'+ + 'color:#fff;text-decoration:none;display:inline-flex;align-items:center;gap:6px;'+ + 'border:1px solid rgba(255,255,255,.08);transition:background .15s,border-color .15s;}'+ + '.name:hover{background:rgba(0,0,0,.75);border-color:rgba(255,255,255,.2);}'+ + '.badge{font-size:9px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;'+ + 'padding:2px 6px;border-radius:6px;background:rgba(255,255,255,.08);'+ + 'border:1px solid rgba(255,255,255,.18);color:rgba(255,255,255,.85);}'+ + '.brand{margin-left:auto;font-size:10px;letter-spacing:.06em;'+ + 'color:rgba(255,255,255,.6);text-decoration:none;font-weight:500;'+ + 'background:rgba(0,0,0,.45);padding:5px 8px;border-radius:999px;'+ + 'border:1px solid rgba(255,255,255,.06);}'+ + '.brand:hover{color:#fff;border-color:rgba(255,255,255,.18);}'+ + ':host([hide-chrome]) .chrome{display:none;}'+ + ':host([theme="light"]) .name{background:rgba(255,255,255,.85);color:#111;'+ + 'border-color:rgba(0,0,0,.08);}'+ + ':host([theme="light"]) .name:hover{background:#fff;border-color:rgba(0,0,0,.2);}'+ + ':host([theme="light"]) .brand{background:rgba(255,255,255,.7);color:rgba(0,0,0,.6);'+ + 'border-color:rgba(0,0,0,.06);}'+ + ':host([theme="light"]) .brand:hover{color:#000;border-color:rgba(0,0,0,.2);}'+ + '.fail{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;'+ + 'font-size:13px;color:rgba(255,255,255,.6);padding:24px;text-align:center;}'+ + '@media (prefers-reduced-motion: reduce){model-viewer{--progress-bar-height:0;}}'+ + '';++ function ThreeWsAgentElement() {+ return Reflect.construct(HTMLElement, [], this.constructor);+ }+ ThreeWsAgentElement.prototype = Object.create(HTMLElement.prototype);+ ThreeWsAgentElement.prototype.constructor = ThreeWsAgentElement;+ Object.setPrototypeOf(ThreeWsAgentElement, HTMLElement);++ ThreeWsAgentElement.observedAttributes = ['agent', 'src', 'poster', 'name', 'theme', 'height', 'width', 'autoplay', 'interactive', 'hide-chrome'];++ ThreeWsAgentElement.prototype.connectedCallback = function () {+ if (this.__threeMounted) return;+ this.__threeMounted = true;++ var shadow = this.attachShadow({ mode: 'open' });+ var style = document.createElement('style');+ style.textContent = STYLE;+ shadow.appendChild(style);++ var stage = document.createElement('div');+ stage.className = 'stage';+ shadow.appendChild(stage);+ this.__stage = stage;++ // Apply explicit sizing if provided+ var h = this.getAttribute('height');+ var w = this.getAttribute('width');+ if (h) this.style.height = isFinite(+h) ? +h + 'px' : h;+ if (w) this.style.width = isFinite(+w) ? +w + 'px' : w;++ // Poster first — visible in <200ms regardless of WebGL state+ var posterAttr = this.getAttribute('poster');+ if (posterAttr) {+ var img = document.createElement('img');+ img.className = 'poster';+ img.alt = this.getAttribute('name') || '';+ img.src = posterAttr;+ img.loading = 'eager';+ stage.appendChild(img);+ this.__posterEl = img;+ }++ var self = this;+ this.__bootIfReady = function () {+ if (!self.__threeVisible || self.__booted) return;+ self.__booted = true;+ self.__boot().catch(function (err) {+ self.__fail(err);+ });+ };++ observeVisibility(this);+ this.setAttribute('role', 'img');+ if (this.getAttribute('name') && !this.hasAttribute('aria-label')) {+ this.setAttribute('aria-label', this.getAttribute('name'));+ }+ };++ ThreeWsAgentElement.prototype.attributeChangedCallback = function (name) {+ if (!this.__booted) return;+ // Re-render on attribute change after initial boot (rare; mostly for SPA-driven swaps)+ if (name === 'agent' || name === 'src') {+ this.__booted = false;+ this.__stage.querySelectorAll('model-viewer').forEach(function (n) { n.remove(); });+ this.__bootIfReady && this.__bootIfReady();+ }+ };++ ThreeWsAgentElement.prototype.__boot = async function () {+ var agentSpec = this.getAttribute('agent');+ var src = this.getAttribute('src');+ var nameAttr = this.getAttribute('name');+ var posterAttr = this.getAttribute('poster');+ var passportUrl = null;+ var chainName = null;+ var resolved = null;++ if (!src && agentSpec) {+ try {+ resolved = await resolve(agentSpec);+ } catch (e) {+ throw new Error('Could not resolve agent "' + agentSpec + '"');+ }+ src = resolved.glbUrl;+ nameAttr = nameAttr || resolved.name;+ posterAttr = posterAttr || resolved.poster;+ passportUrl = resolved.passportUrl;+ chainName = resolved.chainName;+ if (posterAttr && !this.__posterEl) {+ var img = document.createElement('img');+ img.className = 'poster';+ img.alt = nameAttr || '';+ img.src = posterAttr;+ this.__stage.insertBefore(img, this.__stage.firstChild);+ this.__posterEl = img;+ }+ if (nameAttr && !this.hasAttribute('aria-label')) {+ this.setAttribute('aria-label', nameAttr);+ }+ }++ if (!src) throw new Error('Missing "agent" or "src" attribute');++ await ensureModelViewer();++ var mv = document.createElement('model-viewer');+ mv.src = src;+ mv.alt = nameAttr || 'three.ws agent';+ mv.loading = 'eager';+ mv.reveal = 'auto';+ mv.setAttribute('environment-image', 'neutral');+ mv.setAttribute('shadow-intensity', '0');+ mv.setAttribute('exposure', '1');+ mv.setAttribute('camera-orbit', '0deg 90deg auto');+ mv.setAttribute('disable-pan', '');+ mv.setAttribute('interaction-prompt', 'none');++ var interactive = this.hasAttribute('interactive');+ var autoplay = this.hasAttribute('autoplay') || !interactive;+ if (!interactive) {+ mv.setAttribute('disable-zoom', '');+ mv.setAttribute('disable-tap', '');+ // camera-controls intentionally omitted — pointer events pass through to host+ } else {+ mv.setAttribute('camera-controls', '');+ mv.setAttribute('touch-action', 'pan-y');+ }+ if (autoplay && !REDUCED_MOTION) {+ mv.setAttribute('auto-rotate', '');+ mv.setAttribute('rotation-per-second', '18deg');+ mv.setAttribute('auto-rotate-delay', '0');+ }++ mv.addEventListener('load', function () {+ if (self.__posterEl) self.__posterEl.classList.add('poster--gone');+ });+ mv.addEventListener('error', function (e) {+ self.__fail(e && e.detail ? e.detail : new Error('model failed to load'));+ });++ var self = this;+ this.__stage.appendChild(mv);+ this.__mv = mv;++ // Chrome overlay (name pill + brand link)+ if (!this.hasAttribute('hide-chrome')) {+ var chrome = document.createElement('div');+ chrome.className = 'chrome';+ var nameEl = document.createElement('a');+ nameEl.className = 'name';+ nameEl.textContent = nameAttr || 'Agent';+ nameEl.href = passportUrl ? ORIGIN + passportUrl : ORIGIN + '/discover';+ nameEl.target = '_blank';+ nameEl.rel = 'noopener';+ if (chainName) {+ var b = document.createElement('span');+ b.className = 'badge';+ b.textContent = chainName;+ nameEl.appendChild(b);+ }+ chrome.appendChild(nameEl);+ var brand = document.createElement('a');+ brand.className = 'brand';+ brand.textContent = 'three.ws';+ brand.href = ORIGIN + '/';+ brand.target = '_blank';+ brand.rel = 'noopener';+ chrome.appendChild(brand);+ this.__stage.appendChild(chrome);+ }+ };++ ThreeWsAgentElement.prototype.__fail = function (err) {+ // Replace stage with a graceful caption; never leave a black box.+ var name = this.getAttribute('name') || (this.getAttribute('agent') ? 'Agent ' + this.getAttribute('agent') : '3D agent');+ if (this.__posterEl) {+ this.__posterEl.classList.remove('poster--gone');+ } else {+ var d = document.createElement('div');+ d.className = 'fail';+ d.textContent = 'Could not load ' + name;+ this.__stage.appendChild(d);+ }+ this.dispatchEvent(new CustomEvent('three-error', { detail: err, bubbles: true }));+ };++ ThreeWsAgentElement.prototype.disconnectedCallback = function () {+ if (visibilityObserver) visibilityObserver.unobserve(this);+ };++ // Register all three aliases on the same class+ ['three-d', 'three-agent', 'three-ws'].forEach(function (tag) {+ if (!customElements.get(tag)) customElements.define(tag, class extends ThreeWsAgentElement {});+ });++ // -------- Public JS API (window.Three) --------------------------------++ function mount(target, opts) {+ opts = opts || {};+ var host = typeof target === 'string' ? document.querySelector(target) : target;+ if (!host) throw new Error('Three.mount: target not found (' + target + ')');+ var el = document.createElement('three-d');+ ['agent', 'src', 'poster', 'name', 'theme', 'height', 'width'].forEach(function (k) {+ if (opts[k] != null) el.setAttribute(k, String(opts[k]));+ });+ ['interactive', 'autoplay', 'hideChrome', 'hide-chrome'].forEach(function (k) {+ if (opts[k] || opts[k.replace(/[A-Z]/g, function (c) { return '-' + c.toLowerCase(); })]) {+ el.setAttribute(k === 'hideChrome' ? 'hide-chrome' : k, '');+ }+ });+ host.appendChild(el);+ return el;+ }++ var api = {+ version: '1.0.0',+ mount: mount,+ resolve: resolve,+ origin: ORIGIN,+ };++ // Expose globally — non-destructive merge with any existing Three (e.g., Three.js)+ if (window.Three && typeof window.Three === 'object' && !window.Three.mount) {+ Object.keys(api).forEach(function (k) {+ if (window.Three[k] == null) window.Three[k] = api[k];+ });+ } else if (!window.Three) {+ window.Three = api;+ } else if (!window.Three.mount) {+ // Three.js is on the page — namespace ours under Three.ws to avoid collision+ window.Three.ws = api;+ }+ // Always reachable namespace, regardless of collisions+ window.ThreeWs = api;++ // -------- Script-tag auto-mount ---------------------------------------+ // Lets non-technical users embed without writing markup:+ // <script src="https://three.ws/embed/v1.js" data-agent="8453:42" async></script>++ (function autoMount() {+ var s = document.currentScript;+ if (!s) return;+ var agentSpec = s.getAttribute('data-agent') || s.getAttribute('data-src');+ if (!agentSpec) return;+ var el = document.createElement('three-d');+ if (s.getAttribute('data-agent')) el.setAttribute('agent', s.getAttribute('data-agent'));+ if (s.getAttribute('data-src')) el.setAttribute('src', s.getAttribute('data-src'));+ ['poster', 'name', 'theme', 'height', 'width'].forEach(function (k) {+ var v = s.getAttribute('data-' + k);+ if (v) el.setAttribute(k, v);+ });+ ['interactive', 'autoplay', 'hide-chrome'].forEach(function (k) {+ if (s.hasAttribute('data-' + k)) el.setAttribute(k, '');+ });+ var target = s.getAttribute('data-target');+ var host = target ? document.querySelector(target) : null;+ if (host) host.appendChild(el);+ else s.parentNode.insertBefore(el, s);+ })();+})();diff --git a/public/gmgn.html b/public/gmgn.htmlindex 159b41d4b..d7effbeaf 100644--- a/public/gmgn.html+++ b/public/gmgn.html@@ -4,6 +4,17 @@<meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1" /><title>GMGN Smart Money · three.ws</title>+ <meta name="description" content="Live smart money signals narrated by a 3D AI agent. Powered by GMGN.ai — tracks which wallets are loading on Solana, Ethereum, Base, and BNB Chain in real time." />+ <meta property="og:title" content="GMGN Smart Money · three.ws" />+ <meta property="og:description" content="Live smart money signals narrated by a 3D AI agent. Powered by GMGN.ai." />+ <meta property="og:image" content="https://three.ws/og/gmgn.png" />+ <meta property="og:url" content="https://three.ws/gmgn" />+ <meta property="og:type" content="website" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="GMGN Smart Money · three.ws" />+ <meta name="twitter:description" content="Live smart money signals narrated by a 3D AI agent. Powered by GMGN.ai." />+ <meta name="twitter:image" content="https://three.ws/og/gmgn.png" /><link rel="icon" href="/favicon.ico" /><link rel="stylesheet" href="/style.css" /><link rel="stylesheet" href="/home.css" />@@ -212,6 +223,13 @@<div class="stat-item"><span class="lbl">Tokens tracked</span><span class="val" id="stat-tracked">—</span></div><div class="stat-item"><span class="lbl">Last poll</span><span class="val" id="stat-polled">—</span></div><div class="stat-item"><span class="lbl">Source</span><span class="val">GMGN.ai</span></div>+ <div class="stat-item" style="margin-left:auto">+ <span class="lbl">$THREE on GMGN</span>+ <span class="val" id="three-gmgn-status" style="display:inline-flex;align-items:center;gap:6px">+ <a href="https://gmgn.ai/sol/token/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" target="_blank" rel="noopener" style="color:var(--gmgn);font-size:11px;text-decoration:none" id="three-gmgn-link">Watch ↗</a>+ <span id="three-smart-count" style="font-size:11px;color:var(--muted)">—</span>+ </span>+ </div></div><!-- Avatar picker modal -->@@ -527,6 +545,12 @@statusText.textContent = text;}+ let _reconnectTimer = null;+ function scheduleReconnect(ms) {+ if (_reconnectTimer) return; // already scheduled — don't double-fire+ _reconnectTimer = setTimeout(() => { _reconnectTimer = null; connect(); }, ms);+ }+function connect() {if (es) { es.close(); es = null; }setStatus('connecting', 'Connecting…');@@ -546,6 +570,7 @@es.addEventListener('smart_entry', (msg) => {const ev = JSON.parse(msg.data);handleEvent(ev, ev.replay || false);+ if ($('ctl-chain').value === 'sol') checkThreeToken(ev);});es.addEventListener('status', (msg) => {@@ -562,16 +587,18 @@es.addEventListener('ping', () => {});es.addEventListener('close', () => {- setStatus('down', 'Disconnected — reconnecting…');+ // Server sends event: close then closes stream. onerror will also fire+ // immediately after — scheduleReconnect deduplicates both.+ setStatus('down', 'Session ended — reconnecting…');es = null;- setTimeout(connect, 4000);+ scheduleReconnect(4000);});es.onerror = () => {setStatus('down', 'Error — retrying…');es?.close();es = null;- setTimeout(connect, 5000);+ scheduleReconnect(5000);};}@@ -762,6 +789,18 @@return `$${Number(n).toFixed(2)}`;}+ // ── $THREE spotlight ─────────────────────────────────────────────────────+ const THREE_CA = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++ function checkThreeToken(ev) {+ if (ev.address !== THREE_CA) return;+ const el = $('three-smart-count');+ const link = $('three-gmgn-link');+ el.textContent = `🧠 ${ev.smart_buy_24h} wallets${ev.smart_buy_delta > 0 ? ` (+${ev.smart_buy_delta})` : ''}`;+ el.style.color = ev.smart_buy_delta > 0 ? 'var(--gmgn)' : 'var(--muted)';+ link.textContent = '$THREE live ↗';+ }+// ── Go ───────────────────────────────────────────────────────────────────connect();</script>diff --git a/public/nav.html b/public/nav.htmlindex 5efc2df94..6e7f44f49 100644--- a/public/nav.html+++ b/public/nav.html@@ -195,6 +195,12 @@><span class="nav-mi-sub">Give your AI a body</span></a></li>+ <li role="none">+ <a href="/gmgn" role="menuitem"+ ><span class="nav-mi-title">GMGN Smart Money<span class="nav-pill" aria-hidden="true">NEW</span></span+ ><span class="nav-mi-sub">3D agent narrates smart wallet signals live</span></a+ >+ </li><li role="none"><a href="/pumpfun" role="menuitem"><span class="nav-mi-title">Pump.fun stream</spandiff --git a/src/dashboard-next/components/topbar.js b/src/dashboard-next/components/topbar.jsindex 128cd88d3..61fb6fed1 100644--- a/src/dashboard-next/components/topbar.js+++ b/src/dashboard-next/components/topbar.js@@ -1,7 +1,9 @@-// dashboard-next — topbar (breadcrumb + search + drawer toggle + user).+// dashboard-next — topbar (breadcrumb + search + notifications + user menu).//// The search button is the click-handle for the command palette (⌘K).// The drawer toggle controls the right-hand activity rail.+// The notification bell shows unread count and opens a dropdown.+// The user chip opens a popover with wallet address, email, quick links.import { currentRoute } from '../nav.js';import { esc, getMe, initialsOf } from '../api.js';@@ -26,20 +28,28 @@ export function renderTopbar(pathname) {</span><kbd>⌘K</kbd></button>+ <button type="button" class="dn-topbar-btn" data-action="toggle-notifs" aria-label="Notifications" style="position:relative">+ <svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2a6 6 0 016 6v3l1.5 2.5H2.5L4 11V8a6 6 0 016-6z"/><path d="M8 17a2 2 0 004 0"/></svg>+ <span data-slot="notif-badge" style="+ display:none;position:absolute;top:2px;right:2px;+ min-width:16px;height:16px;border-radius:8px;padding:0 4px;+ background:var(--nxt-danger,#e55);color:#fff;+ font-size:10px;font-weight:700;line-height:16px;text-align:center;+ "></span>+ </button><button type="button" class="dn-topbar-btn" data-action="toggle-drawer" aria-label="Toggle activity drawer" aria-pressed="false"><svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="3"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.2 3.2l1.4 1.4M11.4 11.4l1.4 1.4M3.2 12.8l1.4-1.4M11.4 4.6l1.4-1.4"/></svg></button>- <div class="dn-topbar-user" data-action="open-user-menu" data-component="topbar-user" aria-haspopup="true">+ <div class="dn-topbar-user" data-action="toggle-user-menu" data-component="topbar-user" aria-haspopup="true"><div class="dn-topbar-user-avatar" data-slot="initials">··</div><span data-slot="label">Loading…</span>+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><path d="M2 4l4 4 4-4"/></svg></div></header>`;}-/** Wire drawer toggle, palette opener, and fill the user chip. */+/** Wire drawer toggle, palette opener, notifications, and user menu. */export function mountTopbarBehavior(shellEl) {- // Restore drawer state. Default closed on first visit to avoid a heavy- // first-paint while the activity feed mounts.const drawerOpen = (() => {try { return localStorage.getItem(DRAWER_KEY) === '1'; }catch { return false; }@@ -47,27 +57,29 @@ export function mountTopbarBehavior(shellEl) {setDrawerOpen(shellEl, drawerOpen);shellEl.addEventListener('click', (e) => {- const palette = e.target.closest?.('[data-action="open-palette"]');- if (palette) {+ if (e.target.closest?.('[data-action="open-palette"]')) {window.dispatchEvent(new CustomEvent('dn:palette:open'));return;}- const drawer = e.target.closest?.('[data-action="toggle-drawer"]');- if (drawer) {+ if (e.target.closest?.('[data-action="toggle-drawer"]')) {const next = shellEl.getAttribute('data-drawer-open') !== 'true';setDrawerOpen(shellEl, next);try { localStorage.setItem(DRAWER_KEY, next ? '1' : '0'); }- catch { /* private mode — ignore */ }+ catch { /* private mode */ }return;}- const user = e.target.closest?.('[data-action="open-user-menu"]');- if (user) {- // Minimal: jump to account page. Could be a popover later.- location.href = '/dashboard-next/account';+ if (e.target.closest?.('[data-action="toggle-notifs"]')) {+ const btn = e.target.closest('[data-action="toggle-notifs"]');+ toggleNotifsDropdown(btn);+ return;+ }+ if (e.target.closest?.('[data-action="toggle-user-menu"]')) {+ const chip = e.target.closest('[data-action="toggle-user-menu"]');+ toggleUserMenu(chip);+ return;}});- // Keyboard: ⌘K / Ctrl+K opens palette globally.window.addEventListener('keydown', (e) => {if ((e.metaKey || e.ctrlKey) && (e.key === 'k' || e.key === 'K')) {e.preventDefault();@@ -75,7 +87,7 @@ export function mountTopbarBehavior(shellEl) {}});- // Fill the user chip from /api/auth/me.+ // Fill the user chip and load notification count from /api/auth/me.getMe().then((me) => {const chip = shellEl.querySelector('[data-component="topbar-user"]');if (!chip) return;@@ -92,9 +104,28 @@ export function mountTopbarBehavior(shellEl) {chip.querySelector('[data-slot="initials"]').textContent = initialsOf(me);const label = me.display_name || me.handle || me.email || 'Account';chip.querySelector('[data-slot="label"]').textContent = String(label).slice(0, 18);- }).catch(() => {- /* network blip — chip stays "Loading…" rather than ever showing wrong identity */- });+ chip.dataset.me = JSON.stringify({+ display_name: me.display_name,+ handle: me.handle,+ email: me.email,+ wallet: me.wallet_address || me.solana_address || '',+ plan: me.plan || 'free',+ });+ }).catch(() => { /* network blip — chip stays "Loading…" */ });++ // Load unread notification count in background.+ fetch('/api/notifications?limit=1', { credentials: 'include' })+ .then((r) => r.ok ? r.json() : null)+ .then((data) => {+ const unread = data?.unread ?? 0;+ const badge = shellEl.querySelector('[data-slot="notif-badge"]');+ if (!badge) return;+ if (unread > 0) {+ badge.style.display = 'block';+ badge.textContent = unread > 9 ? '9+' : String(unread);+ }+ })+ .catch(() => { /* notifications unavailable */ });}function setDrawerOpen(shellEl, open) {@@ -103,3 +134,159 @@ function setDrawerOpen(shellEl, open) {if (btn) btn.setAttribute('aria-pressed', open ? 'true' : 'false');window.dispatchEvent(new CustomEvent('dn:drawer:toggled', { detail: { open } }));}++// ── Notifications dropdown ─────────────────────────────────────────────────++function toggleNotifsDropdown(btn) {+ const existing = document.querySelector('[data-topbar-notifs]');+ if (existing) { existing.remove(); return; }++ const rect = btn.getBoundingClientRect();+ const drop = document.createElement('div');+ drop.setAttribute('data-topbar-notifs', '');+ drop.style.cssText = `+ position:fixed;top:${rect.bottom + 8}px;right:${window.innerWidth - rect.right}px;+ width:320px;max-height:420px;overflow-y:auto;+ background:rgba(18,20,28,0.97);border:1px solid var(--nxt-stroke-strong);+ border-radius:12px;box-shadow:0 16px 48px rgba(0,0,0,0.6);+ backdrop-filter:blur(20px);z-index:2000;+ `;+ drop.innerHTML = `+ <div style="padding:12px 16px;border-bottom:1px solid var(--nxt-stroke);display:flex;align-items:center;justify-content:space-between">+ <span style="font-size:13.5px;font-weight:600">Notifications</span>+ <a href="/dashboard-next/settings" style="font-size:12px;color:var(--nxt-accent)">Settings →</a>+ </div>+ <div data-slot="notif-items" style="padding:8px 0">+ <div style="padding:14px 16px;color:var(--nxt-ink-dim);font-size:13px">Loading…</div>+ </div>+ `;+ document.body.appendChild(drop);++ const closeOnOutside = (e) => {+ if (!drop.contains(e.target) && e.target !== btn) {+ drop.remove();+ document.removeEventListener('click', closeOnOutside, true);+ }+ };+ setTimeout(() => document.addEventListener('click', closeOnOutside, true), 0);++ fetch('/api/notifications?limit=10', { credentials: 'include' })+ .then((r) => r.ok ? r.json() : null)+ .then((data) => {+ const items = data?.notifications || [];+ const host = drop.querySelector('[data-slot="notif-items"]');+ if (!items.length) {+ host.innerHTML = `<div style="padding:24px 16px;text-align:center;color:var(--nxt-ink-dim);font-size:13px">No notifications</div>`;+ return;+ }+ host.innerHTML = items.map((n) => `+ <div style="padding:10px 16px;border-bottom:1px solid var(--nxt-stroke);opacity:${n.read_at ? '0.6' : '1'}">+ <div style="font-size:13px;font-weight:${n.read_at ? '400' : '500'};color:var(--nxt-ink)">${esc(n.title || n.message || 'Notification')}</div>+ ${n.body ? `<div style="font-size:12px;color:var(--nxt-ink-dim);margin-top:2px">${esc(n.body.slice(0, 100))}</div>` : ''}+ <div style="font-size:11.5px;color:var(--nxt-ink-fade);margin-top:3px">${n.created_at ? timeAgo(n.created_at) : ''}</div>+ </div>+ `).join('');+ })+ .catch(() => {+ const host = drop.querySelector('[data-slot="notif-items"]');+ host.innerHTML = `<div style="padding:14px 16px;color:var(--nxt-ink-dim);font-size:13px">Couldn't load notifications.</div>`;+ });+}++// ── User menu popover ──────────────────────────────────────────────────────++function toggleUserMenu(chip) {+ const existing = document.querySelector('[data-topbar-user-menu]');+ if (existing) { existing.remove(); return; }++ const rect = chip.getBoundingClientRect();+ const rawMe = chip.dataset.me ? JSON.parse(chip.dataset.me) : {};++ const menu = document.createElement('div');+ menu.setAttribute('data-topbar-user-menu', '');+ menu.style.cssText = `+ position:fixed;top:${rect.bottom + 8}px;right:${window.innerWidth - rect.right}px;+ min-width:240px;+ background:rgba(18,20,28,0.97);border:1px solid var(--nxt-stroke-strong);+ border-radius:12px;box-shadow:0 16px 48px rgba(0,0,0,0.6);+ backdrop-filter:blur(20px);z-index:2000;overflow:hidden;+ `;++ const wallet = rawMe.wallet || '';+ const email = rawMe.email || '';+ const name = rawMe.display_name || rawMe.handle || email || 'Account';+ const plan = rawMe.plan || 'free';++ menu.innerHTML = `+ <div style="padding:14px 16px;border-bottom:1px solid var(--nxt-stroke)">+ <div style="font-size:14px;font-weight:600;color:var(--nxt-ink);margin-bottom:2px">${esc(name)}</div>+ ${email ? `<div style="font-size:12px;color:var(--nxt-ink-dim)">${esc(email)}</div>` : ''}+ ${wallet ? `<div style="font-family:'JetBrains Mono',monospace;font-size:11.5px;color:var(--nxt-ink-fade);margin-top:3px">${esc(wallet.slice(0, 8))}…${esc(wallet.slice(-6))}</div>` : ''}+ <div style="margin-top:6px"><span class="dn-tag" style="font-size:11px;text-transform:capitalize">${esc(plan)}</span></div>+ </div>+ <div style="padding:6px 0">+ <a href="/dashboard-next/portfolio" class="dn-user-menu-item">Portfolio & NFTs</a>+ <a href="/dashboard-next/account" class="dn-user-menu-item">Account</a>+ <a href="/dashboard-next/settings" class="dn-user-menu-item">Settings</a>+ ${wallet ? `<button class="dn-user-menu-item" data-action="copy-wallet" style="width:100%;text-align:left;background:none;border:none;cursor:pointer;color:inherit">Copy wallet address</button>` : ''}+ ${email ? `<button class="dn-user-menu-item" data-action="copy-email" style="width:100%;text-align:left;background:none;border:none;cursor:pointer;color:inherit">Copy email</button>` : ''}+ </div>+ <div style="padding:6px 0;border-top:1px solid var(--nxt-stroke)">+ <button class="dn-user-menu-item danger" data-action="sign-out" style="width:100%;text-align:left;background:none;border:none;cursor:pointer">Sign out</button>+ </div>+ `;++ injectMenuStyles();+ document.body.appendChild(menu);++ menu.querySelector('[data-action="copy-wallet"]')?.addEventListener('click', async () => {+ try { await navigator.clipboard.writeText(wallet); } catch { /* ignore */ }+ menu.remove();+ });+ menu.querySelector('[data-action="copy-email"]')?.addEventListener('click', async () => {+ try { await navigator.clipboard.writeText(email); } catch { /* ignore */ }+ menu.remove();+ });+ menu.querySelector('[data-action="sign-out"]')?.addEventListener('click', async () => {+ menu.remove();+ try { await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }); }+ catch { /* best effort */ }+ location.href = '/';+ });++ const closeOnOutside = (e) => {+ if (!menu.contains(e.target) && !chip.contains(e.target)) {+ menu.remove();+ document.removeEventListener('click', closeOnOutside, true);+ }+ };+ setTimeout(() => document.addEventListener('click', closeOnOutside, true), 0);+}++// ── Helpers ────────────────────────────────────────────────────────────────++function timeAgo(iso) {+ const diff = Date.now() - new Date(iso).getTime();+ const m = Math.floor(diff / 60_000);+ if (m < 1) return 'just now';+ if (m < 60) return `${m}m ago`;+ const h = Math.floor(m / 60);+ if (h < 24) return `${h}h ago`;+ return `${Math.floor(h / 24)}d ago`;+}++let _menuStylesInjected = false;+function injectMenuStyles() {+ if (_menuStylesInjected) return;+ _menuStylesInjected = true;+ const style = document.createElement('style');+ style.textContent = `+ .dn-user-menu-item {+ display:block;padding:9px 16px;font-size:13px;color:var(--nxt-ink);+ text-decoration:none;transition:background 0.12s;font-family:inherit;+ }+ .dn-user-menu-item:hover { background:rgba(255,255,255,0.06); }+ .dn-user-menu-item.danger { color:var(--nxt-danger,#e55); }+ `;+ document.head.appendChild(style);+}diff --git a/src/dashboard-next/pages/widgets.js b/src/dashboard-next/pages/widgets.jsindex c89942b70..e806545a8 100644--- a/src/dashboard-next/pages/widgets.js+++ b/src/dashboard-next/pages/widgets.js@@ -228,7 +228,8 @@ function openMenu(anchor, card, widget) {<button role="menuitem" data-act="studio">Open studio</button><button role="menuitem" data-act="embed">Copy embed snippet</button><button role="menuitem" data-act="duplicate">Duplicate</button>- <button role="menuitem" data-act="transcripts">Open transcripts</button>+ <button role="menuitem" data-act="transcripts">Transcripts</button>+ <button role="menuitem" data-act="knowledge">Knowledge base</button><div class="dn-wx-menu-sep"></div><button role="menuitem" data-act="delete" class="danger">Delete</button>`;@@ -282,7 +283,9 @@ function openMenu(anchor, card, widget) {} else if (act === 'duplicate') {await duplicateWidget(card, widget);} else if (act === 'transcripts') {- location.href = `/dashboard?tab=widgets&w=${encodeURIComponent(widget.id)}&pane=transcripts`;+ openTranscriptsModal(widget);+ } else if (act === 'knowledge') {+ openKnowledgeModal(widget);} else if (act === 'delete') {await deleteWidget(card, widget);}diff --git a/src/element.js b/src/element.jsindex e8bec747d..f30a0c2ad 100644--- a/src/element.js+++ b/src/element.js@@ -4,7 +4,7 @@import { Box3 } from 'three';import { Viewer } from './viewer.js';import { Runtime, skillAccessFromAgentDetail } from './runtime/index.js';-import { SkillPaymentModal } from './payment-modal.js';+import { SkillPaymentModal, PaymentChip } from './payment-modal.js';import { SceneController } from './runtime/scene.js';import { SkillRegistry } from './skills/index.js';import { Memory } from './memory/index.js';@@ -1555,25 +1555,49 @@ class Agent3DElement extends HTMLElement {this._mounted = true;- // ── Skill payment modal ────────────────────────────────────────────- // Shows a self-contained purchase UI inside the shadow DOM when the- // runtime blocks a paid skill. On success, refreshes skillAccess so- // the next invocation goes through without re-prompting.+ // ── Skill payment ─────────────────────────────────────────────────+ // When a paid skill is invoked, render an inline payment chip inside+ // the chat thread (no blocking overlay) and narrate before/after via+ // the agent protocol. Falls back to the full modal when there is no+ // chat thread (e.g. avatar-only embed with avatar-chat="off").if (_backendId && this.shadowRoot) {this._paymentModal = new SkillPaymentModal(this.shadowRoot, _backendId);- let _modalOpen = false;+ this._paymentChip = new PaymentChip(_backendId);+ let _paymentInFlight = false;+this._runtime.addEventListener('skill:payment-required', async (e) => {- if (_modalOpen) return;- _modalOpen = true;+ if (_paymentInFlight) return;+ _paymentInFlight = true;++ const { skill = 'skill', price = {} } = e.detail || {};+ const amountUsdc = (Number(price?.amount || 0) / 1e6).toFixed(2);++ // Narrate so the user understands what's happening+ protocol.emit({+ type: ACTION_TYPES.SPEAK,+ payload: {+ text: `To use the ${skill} skill I'll need a quick payment of $${amountUsdc} USDC. I've dropped the approval card in our chat.`,+ sentiment: 0,+ },+ });+let purchased = false;try {- purchased = await this._paymentModal.show(e.detail);+ if (this._chatEl) {+ purchased = await this._paymentChip.show(this._chatEl, e.detail);+ } else {+ purchased = await this._paymentModal.show(e.detail);+ }} finally {- _modalOpen = false;+ _paymentInFlight = false;}+if (purchased) {- // Refresh skillAccess from the updated agent detail so the- // next tool call succeeds without re-prompting.+ protocol.emit({+ type: ACTION_TYPES.SPEAK,+ payload: { text: 'Payment confirmed. Continuing...', sentiment: 0.4 },+ });+ // Refresh skillAccess so next call goes through without re-prompting.try {const base = _scriptOrigin || window.location.origin;const r = await fetch(diff --git a/src/payment-modal.js b/src/payment-modal.jsindex d29c7c01a..864e6c715 100644--- a/src/payment-modal.js+++ b/src/payment-modal.js@@ -23,6 +23,29 @@ async function loadSolana() {}const STYLE = `+.pay-chip {+ background: rgba(167,139,250,.08);+ border: 1px solid rgba(167,139,250,.22);+ border-radius: 12px; padding: 12px 14px; margin: 2px 0;+}+.pay-chip-head { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; }+.pay-chip-label { font-size: 12px; font-weight: 600; color: rgba(255,255,255,.55); text-transform: uppercase; letter-spacing: .06em; }+.pay-chip-skill { font-size: 13px; color: #a78bfa; font-family: monospace; margin-bottom: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.pay-chip-price { font-size: 15px; color: #34d399; font-weight: 700; margin-bottom: 10px; }+.pay-chip-actions { display: flex; gap: 8px; }+.pay-chip-btn {+ flex: 1; padding: 8px 12px; border-radius: 8px; border: none;+ font-size: 13px; font-weight: 600; cursor: pointer;+ background: linear-gradient(135deg, #7c3aed, #6d28d9); color: #fff;+ transition: opacity .15s; letter-spacing: .02em;+}+.pay-chip-btn:hover:not(:disabled) { opacity: .85; }+.pay-chip-btn:disabled { opacity: .4; cursor: default; }+.pay-chip-btn-pay { background: linear-gradient(135deg, #059669, #047857); }+.pay-chip-btn-cancel { flex: 0 0 auto; background: rgba(255,255,255,.08); color: rgba(255,255,255,.45); }+.pay-chip-status { font-size: 12px; color: rgba(255,255,255,.45); margin-top: 7px; min-height: 15px; }+.pay-chip-status.err { color: #f87171; }+.pay-chip-status.ok { color: #34d399; }.skill-pay-overlay {position: fixed; inset: 0; background: rgba(0,0,0,0.72);display: flex; align-items: center; justify-content: center;@@ -335,6 +358,193 @@ export class SkillPaymentModal {}}+/**+ * PaymentChip — compact inline payment card that renders inside the chat thread.+ * Replaces the blocking SkillPaymentModal overlay with a conversational flow.+ * The agent narrates before/after; the chip handles wallet connection + SPL transfer.+ */+export class PaymentChip {+ /** @param {string} agentId seller agent UUID */+ constructor(agentId) {+ this._agentId = agentId;+ this._wallet = null;+ this._connection = null;+ }++ /**+ * Inject a payment chip into chatEl and return a promise that resolves+ * true (purchased) or false (dismissed / failed).+ * @param {Element} chatEl+ * @param {{ skill: string, price?: { amount: string|number, currency_mint: string, chain: string } }} payload+ * @returns {Promise<boolean>}+ */+ show(chatEl, payload) {+ return new Promise((resolve) => {+ const { skill = 'skill', price = {} } = payload;+ const amountUsdc = (Number(price.amount || 0) / 10 ** USDC_DECIMALS).toFixed(2);+ const currency = price.chain === 'solana' ? 'USDC' : (price.currency_mint?.slice(0, 8) || 'USDC');++ const wrapper = document.createElement('div');+ wrapper.className = 'msg';+ wrapper.innerHTML = `+ <div class="role">agent</div>+ <div class="body">+ <div class="pay-chip">+ <div class="pay-chip-head">+ <span class="pay-chip-label">Payment required</span>+ </div>+ <div class="pay-chip-skill">${skill}</div>+ <div class="pay-chip-price">${amountUsdc} ${currency}</div>+ <div class="pay-chip-actions"></div>+ <div class="pay-chip-status"></div>+ </div>+ </div>+ `;++ const setStatus = (msg, kind = '') => {+ const el = wrapper.querySelector('.pay-chip-status');+ el.textContent = msg;+ el.className = 'pay-chip-status' + (kind ? ' ' + kind : '');+ };++ const dismiss = (result) => {+ wrapper.remove();+ resolve(result);+ };++ const updateActions = () => {+ const actions = wrapper.querySelector('.pay-chip-actions');+ const connected = this._wallet?.isConnected || window.solana?.isConnected;+ if (connected) {+ actions.innerHTML = `+ <button class="pay-chip-btn pay-chip-btn-pay">Pay ${amountUsdc} ${currency}</button>+ <button class="pay-chip-btn pay-chip-btn-cancel">Cancel</button>+ `;+ actions.querySelector('.pay-chip-btn-pay').addEventListener('click', () => runPurchase());+ } else {+ actions.innerHTML = `+ <button class="pay-chip-btn pay-chip-btn-connect">Connect Phantom</button>+ <button class="pay-chip-btn pay-chip-btn-cancel">Dismiss</button>+ `;+ actions.querySelector('.pay-chip-btn-connect').addEventListener('click', () => connectWallet());+ }+ actions.querySelector('.pay-chip-btn-cancel').addEventListener('click', () => dismiss(false));+ };++ const connectWallet = async () => {+ setStatus('Connecting…');+ try {+ if (window.solana?.isPhantom || window.solana?.connect) {+ await window.solana.connect();+ this._wallet = window.solana;+ setStatus('');+ updateActions();+ } else {+ setStatus('Phantom not detected. Install Phantom to pay.', 'err');+ }+ } catch (e) {+ setStatus(e.message || 'Connection failed', 'err');+ }+ };++ const runPurchase = async () => {+ const payBtn = wrapper.querySelector('.pay-chip-btn-pay');+ if (payBtn) payBtn.disabled = true;++ setStatus('Creating purchase…');+ let purch;+ try {+ const r = await fetch('/api/marketplace/purchase', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ agent_id: this._agentId, skill }),+ });+ const j = await r.json();+ if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);+ purch = j.data;+ if (purch.already_owned) {+ setStatus('Already purchased.', 'ok');+ await delay(800);+ dismiss(true);+ return;+ }+ } catch (e) {+ setStatus(e.message || 'Failed to start purchase', 'err');+ if (payBtn) payBtn.disabled = false;+ return;+ }++ setStatus('Building transaction…');+ try {+ const { web3, spl } = await loadSolana();+ const { Connection, PublicKey, Transaction } = web3;+ const { getAssociatedTokenAddressSync, createTransferInstruction } = spl;++ if (!this._connection) {+ const rpc = window.__solanaRpc || `${window.location.origin}/api/solana-rpc`;+ this._connection = new Connection(rpc, 'confirmed');+ }++ const payer = this._wallet?.publicKey || window.solana?.publicKey;+ if (!payer) throw new Error('Wallet not connected');++ const payerKey = new PublicKey(payer.toBase58());+ const recipientKey = new PublicKey(purch.recipient);+ const mintKey = new PublicKey(purch.currency_mint);+ const referenceKey = new PublicKey(purch.reference);++ const fromAta = getAssociatedTokenAddressSync(mintKey, payerKey);+ const toAta = getAssociatedTokenAddressSync(mintKey, recipientKey);++ const ix = createTransferInstruction(fromAta, toAta, payerKey, BigInt(purch.amount));+ ix.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });++ const { blockhash } = await this._connection.getLatestBlockhash('confirmed');+ const tx = new Transaction({ feePayer: payerKey, recentBlockhash: blockhash }).add(ix);++ setStatus('Approve in Phantom…');+ const wallet = this._wallet || window.solana;+ const txid = await wallet.sendTransaction(tx, this._connection);++ setStatus('Confirming…');+ await this._connection.confirmTransaction(txid, 'confirmed');++ setStatus('Verifying…');+ const ok = await this._pollConfirm(purch.reference);+ if (!ok) throw new Error('Verification failed — contact support. tx: ' + txid);++ setStatus('Unlocked!', 'ok');+ await delay(900);+ dismiss(true);+ } catch (e) {+ setStatus(e.message || 'Purchase failed', 'err');+ if (payBtn) payBtn.disabled = false;+ }+ };++ updateActions();+ chatEl.appendChild(wrapper);+ chatEl.scrollTop = chatEl.scrollHeight;+ });+ }++ async _pollConfirm(reference, maxMs = 60_000) {+ const deadline = Date.now() + maxMs;+ while (Date.now() < deadline) {+ const r = await fetch(`/api/marketplace/purchase/${reference}/confirm`, {+ method: 'POST',+ credentials: 'include',+ });+ const j = await r.json().catch(() => ({}));+ if (r.ok && j.data?.status === 'confirmed') return true;+ if (r.status === 409) throw new Error(j.error_description || 'Transfer mismatch');+ await delay(2500);+ }+ return false;+ }+}+function delay(ms) {return new Promise((r) => setTimeout(r, ms));}