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(arbitrage): stop collapsing unrelated endpoints into one bogus opportunity
nirholas6824f74a2cb8
diff --git a/api/bazaar/arbitrage.js b/api/bazaar/arbitrage.jsindex 644aaa605..71d3d0e61 100644--- a/api/bazaar/arbitrage.js+++ b/api/bazaar/arbitrage.js@@ -37,22 +37,38 @@ function tokenize(s) {.filter((w) => w && !STOP_WORDS.has(w) && w.length >= 2);}+// A trailing segment that is a route placeholder names the ARGUMENT, not the+// capability: `/api/token-safety/:solana_address` and+// `/api/holder-analysis/:solana_address` are different products that happen to+// take the same input. Treating the placeholder as the capability collapsed+// ten unrelated deepnets endpoints into one bogus "solana address" opportunity+// with a 1400% spread. Recognize the common placeholder spellings and walk+// back to the last literal segment instead.+const PLACEHOLDER_SEGMENT = /^(?::.+|\{.+\}|<.+>|\[.+\])$/;+// Many facilitators (orbisapi, hyreagent…) ship empty serviceName and put// the capability in the URL path with a random suffix:// /proxy/who-to-contact-api-97ccc0 → "who-to-contact-api"// Strip a single trailing hash-like segment so the same logical capability-// hosted by different providers collapses to the same key.-function tailFromUrl(url) {+// hosted by different providers collapses to the same key. The suffix has to+// carry a digit to count as a hash: an all-letter tail is the second half of+// the capability's own name, and eating it turned "token-safety" into "token",+// which then had too few tokens to key on at all.+const HASH_SUFFIX = /-(?![a-z]+$)[a-z0-9]{4,12}$/i;++export function tailFromUrl(url) {try {const u = new URL(url);- const tail = u.pathname.replace(/\/+$/, '').split('/').filter(Boolean).pop() || '';- return tail.replace(/-[a-z0-9]{4,12}$/i, '');+ const segments = u.pathname.replace(/\/+$/, '').split('/').filter(Boolean);+ while (segments.length && PLACEHOLDER_SEGMENT.test(segments[segments.length - 1])) segments.pop();+ const tail = segments.pop() || '';+ return tail.replace(HASH_SUFFIX, '');} catch {return '';}}-function capabilityKey(it) {+export function capabilityKey(it) {if (it.type === 'mcp' && it.toolName) {const k = normalizeWord(it.toolName);return k ? `mcp:${k}` : null;@@ -72,6 +88,32 @@ function hostOf(url) {try { return new URL(url).host; } catch { return ''; }}+// The cross-venue case: one provider host, one resource, two facilitators+// quoting it at different prices. Returns only the listings that are actually+// part of such a gap, so a group that qualifies this way reports the venue+// spread rather than the vendor's unrelated per-endpoint price tiers.+export function venueSpreadListings(group) {+ const byResource = new Map();+ for (const entry of group) {+ const resource = entry.it.resource;+ if (!resource) continue;+ let bucket = byResource.get(resource);+ if (!bucket) {+ bucket = { facilitators: new Set(), min: entry.usdc, max: entry.usdc, entries: [] };+ byResource.set(resource, bucket);+ }+ bucket.facilitators.add(hostOf(entry.it.facilitator));+ bucket.min = Math.min(bucket.min, entry.usdc);+ bucket.max = Math.max(bucket.max, entry.usdc);+ bucket.entries.push(entry);+ }+ const out = [];+ for (const bucket of byResource.values()) {+ if (bucket.facilitators.size >= 2 && bucket.max > bucket.min) out.push(...bucket.entries);+ }+ return out;+}+function usdcAccepts(accepts) {return (accepts || []).filter((a) => {const sym = String(a?.assetInfo?.symbol || '').toUpperCase();@@ -135,18 +177,22 @@ async function handler(req, res) {}const opps = [];- for (const [key, list] of groups) {+ for (const [key, group] of groups) {+ if (group.length < 2) continue;+ // Internal pricing tiers on a single host aren't arbitrage, so a group+ // needs `minProviders` distinct hosts. At the default floor a single host+ // also qualifies when the same resource is quoted at two prices by two+ // facilitators, because that is a genuine cross-venue gap. A caller who+ // raises the floor is asking for genuinely competing providers, so that+ // escape hatch closes.+ const spansEnoughHosts = new Set(group.map(({ it }) => hostOf(it.resource)).filter(Boolean)).size >= minProviders;+ const list = spansEnoughHosts+ ? group+ : (minProviders === DEFAULT_MIN_PROVIDERS ? venueSpreadListings(group) : []);if (list.length < 2) continue;+const hosts = new Set(list.map(({ it }) => hostOf(it.resource)).filter(Boolean));const facilitators = new Set(list.map(({ it }) => hostOf(it.facilitator)).filter(Boolean));- // Internal pricing tiers on a single host aren't arbitrage, so a group- // needs `minProviders` distinct hosts. At the default floor a single host- // listed on two facilitators also counts, because the same capability can- // be priced differently per venue. A caller who raises the floor is asking- // for genuinely competing providers, so that escape hatch closes.- const spansEnoughHosts = hosts.size >= minProviders;- const spansFacilitators = minProviders === DEFAULT_MIN_PROVIDERS && facilitators.size >= 2;- if (!spansEnoughHosts && !spansFacilitators) continue;const prices = list.map((x) => x.usdc);const minAtomic = Math.min(...prices);diff --git a/public/arbitrage.html b/public/arbitrage.htmlindex cb402693e..8fc537f76 100644--- a/public/arbitrage.html+++ b/public/arbitrage.html@@ -4,10 +4,10 @@<script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script><meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1" />-<title data-i18n="arbitrage.meta_title">x402 Arbitrage — same capability, different price</title>+<title data-i18n="arbitrage.meta_title">x402 Arbitrage: same capability, different price</title><meta name="description" content="Cross-provider price disparities surfaced live from the merged x402 facilitator catalog. Find the cheapest endpoint for any capability." data-i18n-attr="content:arbitrage.meta_description"/><meta name="theme-color" content="#0b0b0b" />-<meta property="og:title" content="x402 Arbitrage — same capability, different price" data-i18n-attr="content:arbitrage.meta_og_title"/>+<meta property="og:title" content="x402 Arbitrage: same capability, different price" data-i18n-attr="content:arbitrage.meta_og_title"/><meta property="og:description" content="Live cross-provider price disparities from the merged x402 catalog." data-i18n-attr="content:arbitrage.meta_og_description"/><meta property="og:type" content="website" /><link rel="stylesheet" href="/nav.css" />@@ -79,17 +79,30 @@margin: 24px 0 18px;display: flex; align-items: center; gap: 10px; flex-wrap: wrap;}+ .chips { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }.chip {background: var(--panel);border: 1px solid var(--border-strong);color: var(--muted);padding: 7px 13px;font-size: 13px;+ font-family: inherit;border-radius: 999px;cursor: pointer;+ transition: color 0.15s ease, border-color 0.15s ease, background 0.15s ease, transform 0.1s ease;}.chip:hover { color: var(--text); border-color: var(--accent-blue); }+ .chip:active { transform: translateY(1px); }+ .chip:focus-visible { outline: 2px solid var(--accent-blue); outline-offset: 2px; }.chip.active { background: var(--panel-2); color: var(--text); border-color: var(--accent-blue); }++ /* Visible to screen readers only: the search field needs a real label even+ though the placeholder carries the same wording for sighted users. */+ .sr-only {+ position: absolute; width: 1px; height: 1px;+ padding: 0; margin: -1px; overflow: hidden;+ clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0;+ }.toolbar input[type=search] {flex: 1 1 220px;min-width: 180px;@@ -102,20 +115,22 @@outline: none;}.toolbar input[type=search]:focus { border-color: var(--accent-blue); }+ .toolbar input[type=search]:focus-visible { outline: 2px solid var(--accent-blue); outline-offset: 2px; }.toolbar .count { color: var(--muted); font-size: 13px; margin-left: auto; }.toolbar .count strong { color: var(--text); font-weight: 600; }.grid {display: grid;- grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));+ /* min() caps the track floor at the container width, so a 320px viewport+ gets one fluid column instead of a 300px track that overflows. */+ grid-template-columns: repeat(auto-fill, minmax(min(300px, 100%), 1fr));gap: 14px;padding-bottom: 56px;}- /* Below ~340px, min() prevents the 300px track from overflowing the viewport- and forcing a horizontal scroll — collapse to a single fluid column. */- @media (max-width: 360px) {- .grid { grid-template-columns: 1fr; }- }+ /* A grid item's automatic minimum size is its min-content width, which the+ four-up stat strip pushes past the track. Opting out lets the card shrink+ to the column instead of widening the page. */+ .grid > * { min-width: 0; }.arb {background: var(--panel);border: 1px solid var(--border);@@ -193,8 +208,16 @@padding: 9px 10px;border-right: 1px solid var(--border);background: var(--bg-2);+ min-width: 0;}.stats > div:last-child { border-right: none; }+ /* Four columns of uppercase labels need ~400px. Below that the strip folds+ to 2x2 rather than forcing the card wider than the viewport. */+ @media (max-width: 430px) {+ .stats { grid-template-columns: repeat(2, 1fr); }+ .stats > div:nth-child(2n) { border-right: none; }+ .stats > div:nth-child(-n+2) { border-bottom: 1px solid var(--border); }+ }.stats .k {font-size: 9.5px;letter-spacing: 0.08em;@@ -220,7 +243,9 @@font-size: 12.5px;transition: border-color 0.15s ease;}- .provider:hover { border-color: var(--border-strong); }+ a.provider:hover { border-color: var(--accent-blue); }+ a.provider:active { border-color: var(--accent-blue); background: var(--panel); }+ a.provider:focus-visible { outline: 2px solid var(--accent-blue); outline-offset: 2px; }.provider.cheapest { border-color: rgba(74,222,128,0.4); background: rgba(74,222,128,0.05); }.provider .dot {width: 8px; height: 8px; border-radius: 50%;@@ -265,19 +290,24 @@cursor: pointer;font-weight: 600;font-family: inherit;+ transition: background 0.15s ease, transform 0.1s ease;}+ .arb .actions button:active, .arb .actions a:active { transform: translateY(1px); }+ .arb .actions button[disabled] { cursor: progress; opacity: 0.75; transform: none; }.btn-best {background: rgba(74,222,128,0.12);color: var(--accent-green);border: 1px solid rgba(74,222,128,0.3);}.btn-best:hover { background: rgba(74,222,128,0.18); }+ .btn-best:focus-visible { outline: 2px solid var(--accent-green); outline-offset: 2px; }.btn-worst {background: rgba(248,113,113,0.08);color: var(--accent-red);border: 1px solid rgba(248,113,113,0.25);}.btn-worst:hover { background: rgba(248,113,113,0.15); }+ .btn-worst:focus-visible { outline: 2px solid var(--accent-red); outline-offset: 2px; }.empty, .err {padding: 60px 20px;@@ -288,7 +318,25 @@margin-bottom: 56px;}.err { color: #fecaca; border-color: rgba(248,113,113,0.3); border-style: solid; }- .err .err-title { font-weight: 600; margin-bottom: 6px; }+ .err .err-title, .empty .empty-title { font-weight: 600; margin-bottom: 6px; color: var(--text); }+ .empty .empty-actions {+ margin-top: 16px;+ display: flex; gap: 10px; justify-content: center; flex-wrap: wrap;+ }+ .empty .empty-actions a, .empty .empty-actions button {+ background: var(--panel);+ border: 1px solid var(--border-strong);+ color: var(--text);+ padding: 8px 16px;+ font-size: 13px;+ font-family: inherit;+ font-weight: 600;+ border-radius: 999px;+ cursor: pointer;+ }+ .empty .empty-actions a:hover, .empty .empty-actions button:hover { border-color: var(--accent-blue); color: var(--accent-blue); }+ .empty .empty-actions a:active, .empty .empty-actions button:active { transform: translateY(1px); }+ .empty .empty-actions a:focus-visible, .empty .empty-actions button:focus-visible { outline: 2px solid var(--accent-blue); outline-offset: 2px; }.err .retry-btn {margin-top: 16px;background: rgba(74,222,128,0.12);@@ -322,6 +370,14 @@}@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }.sk-card { height: 240px; }++ @media (prefers-reduced-motion: reduce) {+ *, *::before, *::after {+ animation-duration: 0.01ms !important;+ animation-iteration-count: 1 !important;+ transition-duration: 0.01ms !important;+ }+ }</style><link rel="canonical" href="https://three.ws/arbitrage">@@ -338,7 +394,7 @@<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1"><meta property="og:locale" content="en_US">- <meta property="og:image:alt" content="x402 Arbitrage — three.ws">+ <meta property="og:image:alt" content="x402 Arbitrage on three.ws"><meta name="twitter:site" content="@trythreews"></head><body>@@ -349,7 +405,7 @@<div class="left"><div class="eyebrow"><span class="pulse"></span>Cross-provider arbitrage</div><h1 data-i18n="arbitrage.spot_the_same_capability_priced_differently">Spot the same capability priced differently.</h1>- <p data-i18n="arbitrage.live_opportunities_surfaced_from_the_merged">Live opportunities surfaced from the merged x402 facilitator catalog. Same tool, same intent — different price.</p>+ <p data-i18n="arbitrage.live_opportunities_surfaced_from_the_merged">Live opportunities surfaced from the merged x402 facilitator catalog. Same tool, same intent, different price.</p></div><div class="updated">Updated: <strong id="updated">…</strong>@@ -357,14 +413,17 @@</header><div class="toolbar">- <button type="button" class="chip active" data-filter="all" data-i18n="arbitrage.all">All</button>- <button type="button" class="chip" data-filter="http" data-i18n="arbitrage.http">HTTP</button>- <button type="button" class="chip" data-filter="mcp" data-i18n="arbitrage.mcp">MCP</button>+ <div class="chips" role="group" aria-label="Filter opportunities by listing type">+ <button type="button" class="chip active" data-filter="all" aria-pressed="true" data-i18n="arbitrage.all">All</button>+ <button type="button" class="chip" data-filter="http" aria-pressed="false" data-i18n="arbitrage.http">HTTP</button>+ <button type="button" class="chip" data-filter="mcp" aria-pressed="false" data-i18n="arbitrage.mcp">MCP</button>+ </div>+ <label class="sr-only" for="q" data-i18n="arbitrage.filter_label">Filter by capability or provider</label><input type="search" id="q" placeholder="Filter by capability or provider…" />- <div class="count"><strong id="count">…</strong> opportunities</div>+ <div class="count" aria-live="polite"><strong id="count">…</strong> opportunities</div></div>- <div id="grid" class="grid"></div>+ <div id="grid" class="grid" aria-busy="true"></div><div id="empty" class="empty" hidden></div></div>diff --git a/public/arbitrage.js b/public/arbitrage.jsindex 5d1ddfe7a..9430e377e 100644--- a/public/arbitrage.js+++ b/public/arbitrage.js@@ -1,9 +1,13 @@-// public/arbitrage.js — drives the x402 arbitrage page.+// public/arbitrage.js drives the x402 arbitrage page.//// Pulls /api/bazaar/arbitrage, renders one card per opportunity, supports// a type filter (HTTP / MCP) and a free-text search across capability and// provider host. "Pay cheapest" launches the existing x402.js payment modal// so the arb view stays one click from execution.+//+// Inbound state comes from the query string: /bazaar deep-links here as+// /arbitrage?focus=<service> when a listing has priced peers, and the filter+// state is written back with replaceState so a filtered view is shareable.const $ = (sel) => document.querySelector(sel);const $$ = (sel) => Array.from(document.querySelectorAll(sel));@@ -16,10 +20,17 @@ const els = {q: $('#q'),};+const FILTERS = new Set(['all', 'http', 'mcp']);++const params = new URLSearchParams(location.search);+const initialFilter = String(params.get('type') || '').toLowerCase();+const state = {all: [],- filter: 'all',- q: '',+ filter: FILTERS.has(initialFilter) ? initialFilter : 'all',+ // /bazaar sends the capability it wants compared as ?focus=; ?q= is the+ // form this page writes back, so accept either.+ q: params.get('focus') || params.get('q') || '',};function escapeHtml(s) {@@ -27,7 +38,7 @@ function escapeHtml(s) {}function relativeTime(iso) {- if (!iso) return '—';+ if (!iso) return 'unknown';const d = new Date(iso);const diff = Date.now() - d.getTime();if (diff < 60_000) return 'just now';@@ -38,6 +49,8 @@ function relativeTime(iso) {function renderSkeleton() {els.empty.hidden = true;+ els.grid.setAttribute('aria-busy', 'true');+ els.updated.textContent = 'loading';const frag = document.createDocumentFragment();for (let i = 0; i < 6; i++) {const sk = document.createElement('div');@@ -47,6 +60,17 @@ function renderSkeleton() {els.grid.replaceChildren(frag);}+// Keep the address bar in step with the visible filters so a filtered view can+// be shared or reloaded. replaceState keeps the back button pointing at+// whatever page linked here rather than at every keystroke.+function syncUrl() {+ const next = new URLSearchParams();+ if (state.filter !== 'all') next.set('type', state.filter);+ if (state.q.trim()) next.set('q', state.q.trim());+ const qs = next.toString();+ history.replaceState(null, '', qs ? `${location.pathname}?${qs}` : location.pathname);+}+function visibleOpps() {const q = state.q.trim().toLowerCase();return state.all.filter((o) => {@@ -66,13 +90,9 @@ function visibleOpps() {function renderGrid() {const opps = visibleOpps();els.count.textContent = String(opps.length);+ els.grid.setAttribute('aria-busy', 'false');if (opps.length === 0) {- els.grid.innerHTML = '';- els.empty.hidden = false;- els.empty.className = 'empty';- els.empty.textContent = state.all.length- ? 'No matches. Clear the filter or search.'- : 'No arbitrage opportunities right now. Check back as facilitators add listings.';+ renderEmpty();return;}els.empty.hidden = true;@@ -81,6 +101,42 @@ function renderGrid() {els.grid.replaceChildren(frag);}+// Two distinct empty states: the filters excluded everything (recoverable right+// here), or the feed genuinely has no cross-provider gap right now (the next+// useful move is the full catalog).+function renderEmpty() {+ els.grid.replaceChildren();+ els.empty.hidden = false;+ els.empty.className = 'empty';+ els.empty.removeAttribute('role');+ const narrowed = state.all.length > 0;+ els.empty.innerHTML = narrowed+ ? `<div class="empty-title">No opportunities match these filters</div>+ <div>${state.all.length} live ${state.all.length === 1 ? 'opportunity is' : 'opportunities are'} hidden by the current type filter or search.</div>+ <div class="empty-actions"><button type="button" class="clear-btn">Clear filters</button><a href="/bazaar">Browse the full catalog</a></div>`+ : `<div class="empty-title">No cross-provider price gaps right now</div>+ <div>Every capability in the merged catalog is currently quoted at one price. New listings land continuously, so this fills back in on its own.</div>+ <div class="empty-actions"><button type="button" class="clear-btn">Refresh</button><a href="/bazaar">Browse the full catalog</a><a href="/providers">See provider profiles</a></div>`;+ els.empty.querySelector('.clear-btn').addEventListener('click', narrowed ? clearFilters : load);+}++function clearFilters() {+ state.filter = 'all';+ state.q = '';+ els.q.value = '';+ syncChips();+ syncUrl();+ renderGrid();+}++function syncChips() {+ for (const chip of $$('.chip[data-filter]')) {+ const on = chip.dataset.filter === state.filter;+ chip.classList.toggle('active', on);+ chip.setAttribute('aria-pressed', on ? 'true' : 'false');+ }+}+function card(o) {const el = document.createElement('div');el.className = 'arb';@@ -154,7 +210,8 @@ function card(o) {best.onclick = () => payCheapest(o, best);const worst = document.createElement('a');worst.className = 'btn-worst';- worst.href = `/bazaar?q=${encodeURIComponent(o.capability || o.serviceName || '')}`;+ worst.href = bazaarLink(o);+ worst.title = `Most expensive listing is ${o.mostExpensive?.host || 'unknown'} at ${o.maxPriceLabel}. Opens every listing for this capability in the catalog.`;worst.textContent = `Avoid · ${o.maxPriceLabel}`;actions.append(best, worst);@@ -162,6 +219,14 @@ function card(o) {return el;}+// The catalog defaults to HTTP listings, so an MCP capability has to say so or+// the deep link lands on a tab that cannot contain it.+function bazaarLink(o) {+ const p = new URLSearchParams({ q: o.capability || o.serviceName || '' });+ if (o.type === 'mcp') p.set('type', 'mcp');+ return `/bazaar?${p.toString()}`;+}+function formatSpread(o) {const usdc = o.spreadAtomic / 1_000_000;if (usdc >= 0.01) return `${usdc.toFixed(usdc < 1 ? 4 : 2)} USDC`;@@ -176,7 +241,9 @@ function shortFac(host) {async function payCheapest(o, btn) {if (!o.cheapest?.resource) return;if (o.type === 'mcp') {- window.location.href = `/bazaar?q=${encodeURIComponent(o.capability)}`;+ // MCP tools are invoked through a client session, not a one-shot HTTP+ // payment, so the cheapest listing opens in the catalog's tool inspector.+ window.location.href = bazaarLink(o);return;}const orig = btn.textContent;@@ -186,7 +253,7 @@ async function payCheapest(o, btn) {try {await loadX402();} catch {- // /x402.js 404'd or failed to evaluate — surface it instead of no-op.+ // /x402.js 404'd or failed to evaluate: surface it instead of no-op.btn.textContent = 'Payment modal failed to load';setTimeout(() => { btn.disabled = false; btn.textContent = orig; }, 4000);return;@@ -262,9 +329,13 @@ async function load() {const sub = timedOut? 'The facilitator feed took too long to respond.': network ? 'Check your connection and try again.' : escapeHtml(e?.message || String(e));- els.grid.innerHTML = '';+ els.grid.replaceChildren();+ els.grid.setAttribute('aria-busy', 'false');+ els.count.textContent = '0';+ els.updated.textContent = 'unavailable';els.empty.hidden = false;els.empty.className = 'err';+ els.empty.setAttribute('role', 'alert');els.empty.innerHTML = `<div class="err-title">${title}</div><div>${sub}</div>@@ -276,11 +347,15 @@ async function load() {for (const chip of $$('.chip[data-filter]')) {chip.addEventListener('click', () => {- $$('.chip[data-filter]').forEach((c) => c.classList.toggle('active', c === chip));state.filter = chip.dataset.filter;+ syncChips();+ syncUrl();renderGrid();});}-els.q.addEventListener('input', () => { state.q = els.q.value; renderGrid(); });+els.q.addEventListener('input', () => { state.q = els.q.value; syncUrl(); renderGrid(); });++els.q.value = state.q;+syncChips();load();diff --git a/public/bazaar.js b/public/bazaar.jsindex cad73e7eb..b6ac67d90 100644--- a/public/bazaar.js+++ b/public/bazaar.js@@ -594,5 +594,20 @@ els.reset.addEventListener('click', () => {});});+// Inbound deep links carry the search they want run: /arbitrage sends+// /bazaar?q=<capability>&type=<http|mcp> from its "Avoid" and MCP actions, and+// the same shape makes any bazaar search shareable. Without this the query+// string was decorative and every deep link landed on the unfiltered catalog.+function applyDeepLink() {+ const p = new URLSearchParams(location.search);+ const q = p.get('q') || p.get('query') || '';+ if (q) els.q.value = q;+ const type = String(p.get('type') || '').toLowerCase();+ if (type === 'http' || type === 'mcp') els.type.value = type;+ const network = p.get('network');+ if (network && [...els.network.options].some((o) => o.value === network)) els.network.value = network;+}+// Initial render.+applyDeepLink();load();diff --git a/tests/x402-arbitrage-grouping.test.js b/tests/x402-arbitrage-grouping.test.jsnew file mode 100644index 000000000..0750803ec--- /dev/null+++ b/tests/x402-arbitrage-grouping.test.js@@ -0,0 +1,110 @@+import { describe, it, expect } from 'vitest';++import { capabilityKey, tailFromUrl, venueSpreadListings } from '../api/bazaar/arbitrage.js';++const listing = (over = {}) => ({+ type: 'http',+ resource: 'https://api.example.com/api/weather-forecast',+ facilitator: 'https://facilitator.example.com',+ serviceName: '',+ toolName: '',+ ...over,+});++const entry = (resource, facilitator, usdc) => ({ it: listing({ resource, facilitator }), usdc });++describe('arbitrage capability keys from URLs', () => {+ it('reads the last literal segment as the capability', () => {+ expect(tailFromUrl('https://api.example.com/api/weather-forecast')).toBe('weather-forecast');+ });++ it('strips a trailing hash-like suffix so the same capability collapses across hosts', () => {+ expect(tailFromUrl('https://a.example.com/proxy/who-to-contact-api-97ccc0')).toBe('who-to-contact-api');+ expect(tailFromUrl('https://a.example.com/proxy/inbox-ac248a2b')).toBe('inbox');+ });++ it('keeps an all-letter suffix, which is part of the capability name and not a hash', () => {+ expect(tailFromUrl('https://a.example.com/api/token-safety')).toBe('token-safety');+ expect(tailFromUrl('https://a.example.com/api/weather-forecast')).toBe('weather-forecast');+ });++ it('skips a colon route placeholder and uses the segment that names the capability', () => {+ expect(tailFromUrl('https://api.deepnets.ai/api/token-safety/:solana_address')).toBe('token-safety');+ expect(tailFromUrl('https://api.deepnets.ai/api/holder-analysis/:solana_address')).toBe('holder-analysis');+ });++ it('skips brace, angle, and bracket placeholder spellings too', () => {+ expect(tailFromUrl('https://api.example.com/v1/token-details/{mint}')).toBe('token-details');+ expect(tailFromUrl('https://api.example.com/v1/token-details/<mint>')).toBe('token-details');+ expect(tailFromUrl('https://api.example.com/v1/token-details/[mint]')).toBe('token-details');+ });++ it('skips consecutive placeholders', () => {+ expect(tailFromUrl('https://api.paysponge.com/v0/inboxes/:inbox_id/threads/:thread_id')).toBe('threads');+ });++ it('returns empty for a malformed URL', () => {+ expect(tailFromUrl('not a url')).toBe('');+ });++ it('does not group two different products that take the same argument', () => {+ const safety = capabilityKey(listing({ resource: 'https://api.deepnets.ai/api/token-safety/:solana_address' }));+ const holders = capabilityKey(listing({ resource: 'https://api.deepnets.ai/api/holder-analysis/:solana_address' }));+ expect(safety).toBe('http:token-safety');+ expect(holders).toBe('http:holder-analysis');+ expect(safety).not.toBe(holders);+ });++ it('prefers an explicit service name over the URL', () => {+ expect(capabilityKey(listing({ serviceName: 'Chain ID Lookup', resource: 'https://api.delx.ai/api/v1/x402/chain-id-lookup' })))+ .toBe('http:chain-id-lookup');+ });++ it('keys MCP listings by tool name', () => {+ expect(capabilityKey(listing({ type: 'mcp', toolName: 'get_weather' }))).toBe('mcp:getweather');+ });++ it('refuses a single short URL token that would collide across unrelated services', () => {+ expect(capabilityKey(listing({ resource: 'https://api.example.com/buy' }))).toBe(null);+ });+});++describe('cross-venue spread detection', () => {+ it('keeps only listings where one resource is quoted by two facilitators at two prices', () => {+ const shared = 'https://one.example.com/api/quote';+ const group = [+ entry(shared, 'https://facilitator-a.example.com', 20000),+ entry(shared, 'https://facilitator-b.example.com', 100000),+ entry('https://one.example.com/api/other', 'https://facilitator-a.example.com', 5000),+ ];+ const kept = venueSpreadListings(group);+ expect(kept).toHaveLength(2);+ expect(kept.every((e) => e.it.resource === shared)).toBe(true);+ });++ it('rejects a vendor pricing its own distinct endpoints differently', () => {+ const group = [+ entry('https://conc-exe.xyz/api/concierge-intel-whales', 'https://facilitator-a.example.com', 20000),+ entry('https://conc-exe.xyz/api/concierge-intel-airdrop', 'https://facilitator-b.example.com', 100000),+ ];+ expect(venueSpreadListings(group)).toHaveLength(0);+ });++ it('rejects the same resource on two facilitators at the same price', () => {+ const shared = 'https://one.example.com/api/quote';+ const group = [+ entry(shared, 'https://facilitator-a.example.com', 20000),+ entry(shared, 'https://facilitator-b.example.com', 20000),+ ];+ expect(venueSpreadListings(group)).toHaveLength(0);+ });++ it('rejects one facilitator quoting one resource at two prices', () => {+ const shared = 'https://one.example.com/api/quote';+ const group = [+ entry(shared, 'https://facilitator-a.example.com', 20000),+ entry(shared, 'https://facilitator-a.example.com', 100000),+ ];+ expect(venueSpreadListings(group)).toHaveLength(0);+ });+});