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
fix(economy): name the seventeen three.ws services the bazaar listed as "Service"
nirholasf9cd61545b85
diff --git a/api/_lib/x402/bazaar-client.js b/api/_lib/x402/bazaar-client.jsindex 99ebaf078..d13ff76eb 100644--- a/api/_lib/x402/bazaar-client.js+++ b/api/_lib/x402/bazaar-client.js@@ -99,17 +99,34 @@ export function normalizeItem(item, facilitator) {const resourceMeta = typeof item.resource === 'object' ? item.resource : {};const serviceMeta = bazaarInfo?.service || {};+ // The v1 ListDiscoveryResourcesResponse carries the human-facing fields on+ // `metadata`, which is where our own facilitator publishes them and where+ // the legacy DiscoveredResource schema puts them. Reading only the bazaar+ // extension left every metadata-carrying listing nameless, tagless and+ // iconless in every consumer of this client: /economy rendered seventeen+ // three.ws services as an anonymous row called "Service".+ const listMeta = item.metadata && typeof item.metadata === 'object' ? item.metadata : {};const description =- item.description || resourceMeta.description || serviceMeta.description || bazaarExt?.description || primary?.description || '';+ item.description ||+ resourceMeta.description ||+ listMeta.description ||+ serviceMeta.description ||+ bazaarExt?.description ||+ primary?.description ||+ '';const serviceName =resourceMeta.serviceName ||resourceMeta.name ||+ listMeta.serviceName ||+ listMeta.name ||serviceMeta.name ||bazaarExt?.name ||'';const iconUrl =resourceMeta.iconUrl ||resourceMeta.icon ||+ listMeta.iconUrl ||+ listMeta.icon ||serviceMeta.icon ||serviceMeta.iconUrl ||bazaarExt?.icon ||@@ -118,10 +135,11 @@ export function normalizeItem(item, facilitator) {const rawTags =(Array.isArray(resourceMeta.tags) && resourceMeta.tags) ||(Array.isArray(item.tags) && item.tags) ||+ (Array.isArray(listMeta.tags) && listMeta.tags) ||(Array.isArray(serviceMeta.tags) && serviceMeta.tags) ||(Array.isArray(bazaarExt?.tags) && bazaarExt.tags) ||[];- const category = bazaarExt?.category || serviceMeta.category || resourceMeta.category;+ const category = bazaarExt?.category || serviceMeta.category || listMeta.category || resourceMeta.category;const tags = category && !rawTags.includes(category) ? [category, ...rawTags] : rawTags;const normalizedAccepts = accepts.map((a) => {@@ -149,6 +167,7 @@ export function normalizeItem(item, facilitator) {const method =item.method ||input?.method ||+ listMeta.method ||primary?.method ||(isMcp ? 'MCP' : '');diff --git a/pages/economy.html b/pages/economy.htmlindex 5fcf18399..8b79998f0 100644--- a/pages/economy.html+++ b/pages/economy.html@@ -30,6 +30,13 @@<link rel="canonical" href="https://three.ws/economy" /><style>.ae-main {+ /* The global stylesheet lays body out as a column flexbox, and a flex+ item defaults to min-width:auto, so this main refused to shrink+ below its content: at 320px it measured 1142px and the html/body+ overflow-x:clip silently cut two thirds of every section off the+ screen. min-width:0 is what lets it shrink to the viewport. */+ min-width: 0;+ width: 100%;max-width: 1180px;margin: 0 auto;padding: var(--space-lg, 24px) clamp(16px, 4vw, 40px) var(--space-2xl, 64px);@@ -142,6 +149,28 @@.ae-tag { font-size: 11px; color: var(--ink-dim); border: 1px solid var(--border, #1a1a1a); border-radius: 999px; padding: 1px 8px; }.ae-svc-price { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; flex: none; }.ae-svc-net { font-size: 11px; }+ /* The endpoint is what a buyer actually pays, and it is what tells two+ similarly named rows apart. Truncate rather than wrap so a long path+ cannot widen the row. */+ .ae-svc-ep {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11.5px; color: var(--ink-dim);+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%;+ }+ /* A row whose endpoint is a path template (or a rejected URL scheme) has+ nothing to open, so it renders as a plain row instead of a dead link. */+ .ae-svc-static { cursor: default; }+ .ae-svc-static:hover { border-color: var(--border, #1a1a1a); background: var(--surface-1, #0a0a0a); }+ .ae-svc:focus-visible { outline: 2px solid var(--text, #fff); outline-offset: 2px; }+ .ae-more {+ display: block; margin: 14px auto 0; font: inherit; font-size: 13px;+ border: 1px solid var(--border-strong, #2a2a2a); background: var(--surface-1, #0a0a0a);+ color: var(--text, #e8e8e8); border-radius: 999px; padding: 9px 20px; cursor: pointer;+ transition: border-color 0.15s, background 0.15s;+ }+ .ae-more:hover { border-color: #444; background: var(--surface-2, #111); }+ .ae-more:active { transform: translateY(1px); }+ .ae-more:focus-visible { outline: 2px solid var(--text, #fff); outline-offset: 2px; }/* States */.ae-skel { border-radius: 14px; background: linear-gradient(90deg, #0e0e16 25%, #16161f 37%, #0e0e16 63%); background-size: 400% 100%; animation: ae-shimmer 1.4s ease infinite; }@@ -150,6 +179,10 @@@keyframes ae-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }.ae-empty, .ae-error { border: 1px dashed var(--border-strong, #2a2a2a); border-radius: 14px; padding: 28px; text-align: center; }.ae-empty-title { font-weight: 600; margin: 0 0 6px; }+ .ae-empty-cta { margin: 14px 0 0; }+ .ae-empty-cta a { color: var(--accent-violet-strong); text-decoration: none; font-size: 13.5px; }+ .ae-empty-cta a:hover { text-decoration: underline; }+ .ae-empty-cta a:focus-visible { outline: 2px solid var(--accent-violet); outline-offset: 3px; border-radius: 4px; }.ae-error p { margin: 0 0 12px; color: #f3b4b4; }.ae-retry { border: 1px solid var(--border-strong, #2a2a2a); background: var(--surface-1, #0a0a0a); color: var(--text, #e8e8e8); border-radius: 10px; padding: 8px 16px; cursor: pointer; font: inherit; }.ae-retry:hover { border-color: #444; }@@ -201,6 +234,21 @@.ae-hire-foot-note { font-size: 12.5px; color: var(--text-muted, #888); margin: 16px 0 0; }.ae-hire-foot-note a { color: var(--accent-violet-strong); text-decoration: none; }.ae-hire-foot-note a:hover { text-decoration: underline; }++ /* Phones: the section head (title + sort + link) and the service row+ (name + price) both run out of room well before 480px, so stack them+ instead of letting the price column squeeze the name to nothing. */+ @media (max-width: 560px) {+ .ae-section-head { flex-direction: column; align-items: flex-start; gap: 10px; }+ .ae-head-tools { flex-wrap: wrap; gap: 10px 14px; }+ .ae-stats { gap: 10px; }+ .ae-stat { flex: 1 1 132px; min-width: 0; padding: 12px 14px; }+ .ae-live { margin-left: 0; align-self: flex-start; }+ .ae-svc { flex-direction: column; align-items: stretch; gap: 10px; }+ .ae-svc-price { flex-direction: row; align-items: center; justify-content: space-between; }+ .ae-grid, .ae-offer-grid { grid-template-columns: 1fr; }+ .ae-offer-foot { flex-wrap: wrap; }+ }</style><meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">@@ -279,14 +327,14 @@<section class="ae-section"><div class="ae-section-head"><h2 data-i18n="economy.live_x402_services">Live x402 services</h2>- <a href="/docs" data-i18n="economy.how_x402_works">How x402 works →</a>+ <a href="/docs/x402" data-i18n="economy.how_x402_works">How x402 works →</a></div><div class="ae-list" id="ae-services"></div>+ <button class="ae-more" type="button" id="ae-services-more" aria-controls="ae-services" aria-expanded="false" hidden>Show all services</button></section></main><div id="footer-container"></div>- <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"The Agent Economy - Live","description":"Agents earning on three.ws and the x402 services they sell, live across the network.","url":"https://three.ws/economy","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script><script src="/nav.js" defer></script><script type="module" src="/src/economy-live.js"></script><script src="/footer.js"></script>diff --git a/public/x402.js b/public/x402.jsindex 49f4af043..96b12cee9 100644--- a/public/x402.js+++ b/public/x402.js@@ -1748,7 +1748,16 @@ class CheckoutModal {buyer: payerAddress,...(tips ? { tips } : {}),});- this.renderProgress('authorize', { text: `Confirm in ${walletName}…` });+ // Normally three.ws sponsors the Solana fee, so the buyer's SOL is+ // untouched and the wallet popup is the whole story. When the sponsor+ // cannot cover it the endpoint hands back a self-pay transaction, and+ // the buyer's own SOL pays the fee. Say that before they approve rather+ // than letting a wallet popup be the first time they find out.+ this.renderProgress('authorize', {+ text: prep.self_pay+ ? `Confirm in ${walletName} — you cover the network fee on this one`+ : `Confirm in ${walletName}…`,+ });const txBytes = base64ToUint8Array(prep.tx_base64);// The wallet returns a fully-signed VersionedTransaction with the buyer's// signature added. The facilitator's fee-payer signature is added bydiff --git a/src/economy-live.js b/src/economy-live.jsindex 48561f82a..0a61157e6 100644--- a/src/economy-live.js+++ b/src/economy-live.js@@ -36,8 +36,27 @@ function esc(s) {return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));}+// Facilitator listings report the network as a CAIP-2 id ("eip155:8453"), which+// the page used to print raw because the old substring test only matched the+// friendly names. Resolve the chain id first, then fall back to the name.+const EVM_CHAIN_NAMES = {+ 1: 'Ethereum',+ 10: 'Optimism',+ 56: 'BNB Chain',+ 137: 'Polygon',+ 8453: 'Base',+ 42161: 'Arbitrum',+ 43114: 'Avalanche',+ 84532: 'Base Sepolia',+ 196: 'X Layer',+};+function chainLabel(chain) {const c = String(chain || '').toLowerCase();+ if (!c) return '';+ const eip155 = c.match(/^eip155:(\d+)$/);+ if (eip155) return EVM_CHAIN_NAMES[Number(eip155[1])] || `EVM chain ${eip155[1]}`;+ if (c.startsWith('solana')) return c.includes('devnet') || c.includes('etwtrabzayq') ? 'Solana devnet' : 'Solana';if (c.includes('sol')) return 'Solana';if (c.includes('base')) return 'Base';if (c.includes('eth')) return 'Ethereum';@@ -61,8 +80,13 @@ function skeleton(host, n, kind) {}}-function emptyState(host, title, hint) {- host.innerHTML = `<div class="ae-empty"><p class="ae-empty-title">${esc(title)}</p><p class="ae-muted">${esc(hint)}</p></div>`;+// An empty feed is a real state, so it says what the visitor can do next rather+// than only that there is nothing here. `action` is an internal path.+function emptyState(host, title, hint, action) {+ const cta = action+ ? `<p class="ae-empty-cta"><a href="${esc(action.href)}">${esc(action.label)}</a></p>`+ : '';+ host.innerHTML = `<div class="ae-empty"><p class="ae-empty-title">${esc(title)}</p><p class="ae-muted">${esc(hint)}</p>${cta}</div>`;}function errorState(host, retryFn) {@@ -110,20 +134,31 @@ function agentCard(a) {</a>`;}+// Changing the sort twice inside one round trip can land the older response+// last and paint a list the select no longer says. Only the newest request may+// write.+let _agentsRequest = 0;+async function loadAgents({ quiet = false } = {}) {const host = $('#ae-agents');if (!host) return;if (!quiet) skeleton(host, 6, 'card');+ const token = ++_agentsRequest;try {const sort = $('#ae-sort')?.value || 'top_rated';const params = new URLSearchParams({ sort, limit: '24' });const r = await fetch(`/api/marketplace/agents?${params}`, { credentials: 'include' });if (!r.ok) throw new Error(`status ${r.status}`);const j = await r.json();+ if (token !== _agentsRequest) return;const items = j?.data?.items || j?.items || [];if (!items.length) {- emptyState(host, 'No published agents yet', 'Be the first — build an agent and price a skill.');+ emptyState(host, 'No published agents yet', 'Nobody has published an agent to the marketplace yet.', {+ href: '/create-agent',+ label: 'Build the first one',+ });setStat('#ae-stat-agents', '0');+ setStat('#ae-stat-earning', '0');return;}host.innerHTML = items.map(agentCard).join('');@@ -131,59 +166,170 @@ async function loadAgents({ quiet = false } = {}) {const earners = items.filter((a) => (Number(a.buyers_total) || 0) > 0).length;setStat('#ae-stat-earning', String(earners));} catch (err) {- errorState(host, loadAgents);+ if (token === _agentsRequest) errorState(host, () => loadAgents());// eslint-disable-next-line no-consoleconsole.error('[economy-live] agents', err);}}-// ── Section: live x402 services ───────────────────────────────────────────────+// ── Section: live x402 services ──────────────────────────────────++// A path segment a facilitator publishes as a placeholder rather than a value:+// "/inboxes/:inbox_id/messages", "/block/{number}". An endpoint carrying one is+// a template, not a fetchable page, so the row never links to it.+function isTemplateSegment(seg) {+ return /^[:{<]/.test(seg) || /^%7B/i.test(seg);+}++function parseEndpoint(resource) {+ try {+ const u = new URL(String(resource || ''));+ return u.protocol === 'https:' || u.protocol === 'http:' ? u : null;+ } catch {+ return null;+ }+}++// "erc20-balance" -> "Erc20 balance", "html-to-json" -> "Html to json".+function humanizeSegment(seg) {+ let out = seg;+ try {+ out = decodeURIComponent(seg);+ } catch {+ out = seg;+ }+ return out+ .replace(/\.[a-z0-9]{1,5}$/i, '')+ .replace(/[-_+]+/g, ' ')+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')+ .trim()+ .replace(/^./, (c) => c.toUpperCase());+}++// Every listing on the live catalog today reaches us with an empty serviceName:+// most facilitators simply do not collect one. Rendering the fallback made the+// whole section ninety identical rows called "Service", so derive a readable+// label from the one field every listing does have, its endpoint URL.+const GENERIC_PATH_SEGMENTS = new Set(['api', 'rest', 'public', 'x402', 'v', 'endpoint', 'endpoints']);++export function deriveServiceLabel(resource) {+ const u = parseEndpoint(resource);+ if (!u) return 'Service';+ const segs = u.pathname+ .split('/')+ .filter(Boolean)+ .filter((seg) => !isTemplateSegment(seg) && !/^v\d+(\.\d+)?$/i.test(seg) && !GENERIC_PATH_SEGMENTS.has(seg.toLowerCase()));+ if (!segs.length) return u.hostname.replace(/^www\./, '');+ const tail = segs.slice(-2).map(humanizeSegment);+ const label = tail.length > 1 && tail[1].length < 14 ? tail.join(' ') : tail[tail.length - 1];+ return label.length > 46 ? `${label.slice(0, 45)}\u2026` : label;+}++// The endpoint itself, shown under the name: it is what a buyer actually pays,+// and it is what tells two rows named "Inboxes messages" apart.+export function endpointText(resource) {+ const u = parseEndpoint(resource);+ if (!u) return '';+ const path = u.pathname === '/' ? '' : u.pathname.replace(/\/$/, '');+ return `${u.host}${path}`;+}++// "0.1 USDC" from the facilitator already carries the symbol; the old row+// appended `price.currency` after it, which is the token CONTRACT ADDRESS, so+// every price read "0.1 USDC 0x833589...". Free is free.+export function servicePriceLabel(price) {+ if (!price) return 'Free';+ if (price.amountAtomic != null && /^0+$/.test(String(price.amountAtomic))) return 'Free';+ const label = String(price.amountLabel || '').trim();+ if (!label) return 'Free';+ return /^0(\.0+)?( |$)/.test(label) ? 'Free' : label;+}function serviceRow(t) {- const price = t.price?.amountLabel- ? `${esc(t.price.amountLabel)}${t.price.currency ? ` ${esc(t.price.currency)}` : ''}`- : 'Free';+ const price = servicePriceLabel(t.price);+ const free = price === 'Free';const net = t.price?.network ? chainLabel(t.price.network) : '';const method = t.method ? `<span class="ae-svc-method">${esc(t.method)}</span>` : '';+ const name = t.serviceName || t.toolName || deriveServiceLabel(t.resource);+ const endpoint = endpointText(t.resource);+ const templated = endpoint.split('/').some(isTemplateSegment);const tags = (t.tags || []).slice(0, 3).map((x) => `<span class="ae-tag">${esc(x)}</span>`).join('');// t.resource is an x402 endpoint URL sourced from third-party facilitator- // discovery listings (PayAI / Coinbase CDP / etc.) — any operator can- // register one, so it's untrusted external input. esc() only guards- // attribute-breakout; sanitizeUrl() gates the scheme so a malicious- // `javascript:`/`data:` listing can't execute when clicked.- return `- <a class="ae-svc" href="${esc(sanitizeUrl(t.resource || '#'))}" rel="noopener" target="_blank">+ // discovery listings (PayAI / Coinbase CDP / etc.). Any operator can register+ // one, so it is untrusted external input. esc() only guards attribute+ // breakout; sanitizeUrl() gates the scheme so a malicious `javascript:` or+ // `data:` listing cannot execute when clicked.+ const href = sanitizeUrl(t.resource || '');+ // A template endpoint 404s and a rejected scheme collapses to "#", and both+ // are dead links. Those rows render as plain rows instead: the endpoint is+ // still readable and copyable, it just is not pretending to be a page.+ const linkable = !templated && href !== '#';+ const body = `<div class="ae-svc-main">- <span class="ae-svc-name">${method}${esc(t.serviceName || t.toolName || 'Service')}</span>- <span class="ae-svc-desc ae-muted">${esc((t.description || '').slice(0, 120))}</span>- <span class="ae-svc-tags">${tags}</span>+ <span class="ae-svc-name">${method}${esc(name)}</span>+ ${endpoint ? `<span class="ae-svc-ep" title="${esc(endpoint)}">${esc(endpoint)}</span>` : ''}+ <span class="ae-svc-desc ae-muted">${esc((t.description || '').slice(0, 140))}</span>+ <span class="ae-svc-tags">${tags}${templated ? '<span class="ae-tag" title="This endpoint takes path parameters, so there is no page to open">path template</span>' : ''}</span></div><div class="ae-svc-price">- <span class="ae-chip ae-chip-price">${price}</span>+ <span class="ae-chip ${free ? 'ae-chip-free' : 'ae-chip-price'}">${esc(price)}</span>${net ? `<span class="ae-muted ae-svc-net">${esc(net)}</span>` : ''}- </div>- </a>`;+ </div>`;+ return linkable+ ? `<a class="ae-svc" href="${esc(href)}" rel="noopener noreferrer" target="_blank" title="Open ${esc(endpoint)} in a new tab">${body}</a>`+ : `<div class="ae-svc ae-svc-static">${body}</div>`;+}++// The catalog runs to about ninety live endpoints. Rendering all of them made a+// page fourteen thousand pixels tall, so show a first screenful and let the+// visitor open the rest.+const SERVICES_PREVIEW = 24;+let _services = [];+let _servicesExpanded = false;++function renderServices() {+ const host = $('#ae-services');+ const more = $('#ae-services-more');+ if (!host) return;+ if (!_services.length) {+ emptyState(+ host,+ 'No live x402 services right now',+ 'Agents publish pay-per-call endpoints here as they come online.',+ { href: '/docs/x402', label: 'Read how to publish one' },+ );+ if (more) more.hidden = true;+ setStat('#ae-stat-services', '0');+ return;+ }+ const shown = _servicesExpanded ? _services : _services.slice(0, SERVICES_PREVIEW);+ host.innerHTML = shown.map(serviceRow).join('');+ setStat('#ae-stat-services', String(_services.length));+ if (!more) return;+ const hidden = _services.length - shown.length;+ more.hidden = _services.length <= SERVICES_PREVIEW;+ more.textContent = _servicesExpanded ? 'Show fewer services' : `Show all ${_services.length} services`;+ more.setAttribute('aria-expanded', _servicesExpanded ? 'true' : 'false');+ more.title = _servicesExpanded ? `Collapse back to ${SERVICES_PREVIEW}` : `${hidden} more live endpoints`;}async function loadServices({ quiet = false } = {}) {const host = $('#ae-services');if (!host) return;- if (!quiet) skeleton(host, 5, 'row');+ if (!quiet && !_services.length) skeleton(host, 5, 'row');try {const params = new URLSearchParams({ type: 'http', maxItems: '40' });const r = await fetch(`/api/agenc/x402-services?${params}`);if (!r.ok) throw new Error(`status ${r.status}`);const j = await r.json();- const tasks = j?.tasks || [];- if (!tasks.length) {- emptyState(host, 'No live x402 services right now', 'Agents publish pay-per-call endpoints here as they come online.');- setStat('#ae-stat-services', '0');- return;- }- host.innerHTML = tasks.map(serviceRow).join('');- setStat('#ae-stat-services', tasks.length >= 40 ? '40+' : String(tasks.length));+ _services = Array.isArray(j?.tasks) ? j.tasks : [];+ renderServices();} catch (err) {- errorState(host, loadServices);+ if (!_services.length) {+ errorState(host, () => loadServices());+ const more = $('#ae-services-more');+ if (more) more.hidden = true;+ }// eslint-disable-next-line no-consoleconsole.error('[economy-live] services', err);}@@ -271,7 +417,12 @@ function renderOffers() {const host = $('#ae-offers');if (!host) return;if (!_offers.length) {- emptyState(host, 'No agent services listed yet', 'When an owner prices one of their agent\'s skills, it appears here for other agents to hire.');+ emptyState(+ host,+ 'No agent services listed yet',+ 'When an owner prices one of their agent\'s skills, it appears here for other agents to hire.',+ { href: '/agents', label: 'Open your agents and price a skill' },+ );setStat('#ae-stat-hires', '0');return;}@@ -349,6 +500,14 @@ export function initEconomyLive() {if (sortEl) sortEl.addEventListener('change', () => loadAgents());const offerSortEl = $('#ae-offer-sort');if (offerSortEl) offerSortEl.addEventListener('change', () => renderOffers());+ const moreEl = $('#ae-services-more');+ if (moreEl) {+ moreEl.addEventListener('click', () => {+ _servicesExpanded = !_servicesExpanded;+ renderServices();+ if (!_servicesExpanded) moreEl.scrollIntoView({ block: 'nearest' });+ });+ }scheduleRefresh();}diff --git a/tests/api/bazaar-endpoints.test.js b/tests/api/bazaar-endpoints.test.jsindex 4fb398dd8..6d0b63359 100644--- a/tests/api/bazaar-endpoints.test.js+++ b/tests/api/bazaar-endpoints.test.js@@ -129,7 +129,7 @@ const { default: searchHandler } = await import('../../api/bazaar/search.js');const { default: providersHandler } = await import('../../api/bazaar/providers.js');const { default: arbitrageHandler } = await import('../../api/bazaar/arbitrage.js');const { default: contextHandler } = await import('../../api/bazaar/context.js');-const { Bazaar, clearCatalogCache } = await import('../../api/_lib/x402/bazaar-client.js');+const { Bazaar, clearCatalogCache, normalizeItem } = await import('../../api/_lib/x402/bazaar-client.js');let ipCounter = 0;function makeReq({ url, method = 'GET' } = {}) {@@ -482,3 +482,64 @@ describe('bazaar-client paging bounds', () => {expect(items).toHaveLength(2);});});++// The v1 ListDiscoveryResourcesResponse puts the human-facing fields on+// `metadata`, which is exactly where our own facilitator publishes them+// (api/_lib/x402/discovery-resources.js toV1Item). normalizeItem only read the+// v2 bazaar extension, so every listing that carried metadata normalized to an+// empty name, no tags and no icon: /economy rendered seventeen three.ws+// services as an anonymous row called "Service".+describe('bazaar-client v1 metadata', () => {+ const v1Item = {+ resource: 'https://three.ws/api/x402/analytics',+ type: 'http',+ x402Version: 1,+ accepts: [+ {+ scheme: 'exact',+ network: 'solana',+ maxAmountRequired: '5000',+ payTo: 'wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU',+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ },+ ],+ metadata: {+ serviceName: 'three.ws Economy Analytics',+ tags: ['analytics', 'economy'],+ iconUrl: 'https://three.ws/favicon.ico',+ method: 'POST',+ path: '/api/x402/analytics',+ },+ };++ it('reads serviceName, tags, iconUrl and method off metadata', () => {+ const n = normalizeItem(v1Item, FAC_A);+ expect(n.serviceName).toBe('three.ws Economy Analytics');+ expect(n.tags).toEqual(['analytics', 'economy']);+ expect(n.iconUrl).toBe('https://three.ws/favicon.ico');+ expect(n.method).toBe('POST');+ expect(n.minPriceLabel).toBe('0.005 USDC');+ });++ it('keeps a v2 bazaar extension authoritative over metadata', () => {+ const n = normalizeItem(+ {+ ...v1Item,+ extensions: { bazaar: { name: 'Extension name', info: { service: { name: 'Service block name' } } } },+ },+ FAC_A,+ );+ // resource/serviceMeta names still win, so the fix adds a fallback rung+ // rather than reordering the existing ones.+ expect(n.serviceName).toBe('three.ws Economy Analytics');+ });++ it('leaves a listing with no metadata untouched', () => {+ const { metadata, ...bare } = v1Item;+ expect(metadata).toBeTruthy();+ const n = normalizeItem(bare, FAC_A);+ expect(n.serviceName).toBe('');+ expect(n.tags).toEqual([]);+ expect(n.method).toBe('');+ });+});diff --git a/tests/x402-selfpay-fallback.test.js b/tests/x402-selfpay-fallback.test.jsindex 4d460f9f7..ab0092b7b 100644--- a/tests/x402-selfpay-fallback.test.js+++ b/tests/x402-selfpay-fallback.test.js@@ -33,6 +33,10 @@ const ENV = {X402_FEE_PAYER_SECRET_BASE58: 'test-cosigning-key-present',};+// Cleared per test so facilitator routing is decided by X402_SELF_FACILITATOR_ENABLED+// rather than by whatever the ambient environment happens to point at.+const CLEARED = ['X402_FACILITATOR_URL_SOLANA', 'X402_RING_SELF_PAY'];+let saved;beforeEach(() => {saved = {};@@ -40,6 +44,10 @@ beforeEach(() => {saved[k] = process.env[k];process.env[k] = v;}+ for (const k of CLEARED) {+ saved[k] = process.env[k];+ delete process.env[k];+ }vi.resetModules();});afterEach(() => {@@ -104,6 +112,17 @@ describe('a dry sponsor keeps the endpoint payable via self-pay', () => {}});+ it('keeps the sponsor as fee payer when an EXTERNAL facilitator settles', async () => {+ // PayAI and friends pin the sponsor as fee payer and reject a challenge+ // without one at /verify, so the self-pay fallback must not apply there:+ // it would trade a retryable 503 for a hard verify failure.+ process.env.X402_FACILITATOR_URL_SOLANA = 'https://facilitator.payai.network';+ const accepts = solanaAccepts(await requirementsWith({ belowFloor: true }));+ for (const accept of accepts) {+ expect(accept.extra.feePayer).toBe(SPONSOR);+ }+ });+it('still refuses to advertise Solana when the receiving address is missing', async () => {// Self-pay fixes who pays gas. It cannot conjure somewhere to send the// money, so a genuinely unconfigured lane must stay unadvertised, and with