Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

sns: native register UI, on-chain favorite reverse-lookup, pay-by-name tests

oversteppinge95dd5b980e9
diff --git a/public/dashboard/sns.html b/public/dashboard/sns.html
index 6fef1cd07..1d6fc03bd 100644
--- a/public/dashboard/sns.html
+++ b/public/dashboard/sns.html
@@ -11,9 +11,9 @@
<a class="dash-back" href="/dashboard/agents">← Back to dashboard</a>
<h1 class="dash-title">SNS Domains</h1>
<p class="dash-sub">
- Attach a Solana Name Service <code class="dash-mono">.sol</code> domain as your agent's
- readable id. Domains owned by either the agent's wallet or any wallet linked to your account
- are eligible.
+ Attach a Solana Name Service <code class="dash-mono">.sol</code> domain as your
+ agent's readable id. Domains owned by either the agent's wallet or any wallet linked
+ to your account are eligible.
</p>
<div id="picker"></div>
@@ -35,7 +35,10 @@
function escapeHtml(s) {
return String(s == null ? '' : s).replace(
/[&<>"']/g,
- (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' })[c],
+ (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' })[
+ c
+ ],
);
}
@@ -101,36 +104,59 @@
function detectSolanaProvider() {
if (typeof window === 'undefined') return null;
- return window.phantom?.solana || window.solana || window.backpack || window.solflare || null;
+ return (
+ window.phantom?.solana ||
+ window.solana ||
+ window.backpack ||
+ window.solflare ||
+ null
+ );
}
async function registerWithBrowserWallet(agentId, domain) {
const provider = detectSolanaProvider();
- if (!provider) throw new Error('No Solana wallet detected. Install Phantom, Backpack, or Solflare.');
+ if (!provider)
+ throw new Error(
+ 'No Solana wallet detected. Install Phantom, Backpack, or Solflare.',
+ );
if (!provider.isConnected) {
- try { await provider.connect(); } catch (e) {
+ try {
+ await provider.connect();
+ } catch (e) {
throw new Error(e?.message || 'Wallet connection refused');
}
}
const walletAddress = provider.publicKey?.toBase58?.();
if (!walletAddress) throw new Error('Wallet did not return a public key');
- const prepRes = await fetch(`/api/agents/${encodeURIComponent(agentId)}/sns/register-prep`, {
- method: 'POST',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ domain, wallet_address: walletAddress }),
- });
+ const prepRes = await fetch(
+ `/api/agents/${encodeURIComponent(agentId)}/sns/register-prep`,
+ {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ domain, wallet_address: walletAddress }),
+ },
+ );
const prepJson = await prepRes.json().catch(() => ({}));
if (!prepRes.ok) {
- if (prepRes.status === 403 && /not linked/.test(prepJson.error_description || '')) {
- throw new Error(`Link this Solana wallet first at /dashboard/wallets (${walletAddress.slice(0, 6)}…${walletAddress.slice(-4)}).`);
+ if (
+ prepRes.status === 403 &&
+ /not linked/.test(prepJson.error_description || '')
+ ) {
+ throw new Error(
+ `Link this Solana wallet first at /dashboard/wallets (${walletAddress.slice(0, 6)}…${walletAddress.slice(-4)}).`,
+ );
}
- throw new Error(prepJson.error_description || `register-prep failed (${prepRes.status})`);
+ throw new Error(
+ prepJson.error_description || `register-prep failed (${prepRes.status})`,
+ );
}
const { tx_base64 } = prepJson.data;
- const { VersionedTransaction } = await import('https://esm.sh/@solana/[email protected]');
+ const { VersionedTransaction } = await import(
+ 'https://esm.sh/@solana/[email protected]'
+ );
const txBytes = Uint8Array.from(atob(tx_base64), (c) => c.charCodeAt(0));
const tx = VersionedTransaction.deserialize(txBytes);
@@ -150,25 +176,35 @@
}),
});
const submitJson = await submitRes.json();
- if (submitJson.error) throw new Error(submitJson.error.message || 'tx submit failed');
+ if (submitJson.error)
+ throw new Error(submitJson.error.message || 'tx submit failed');
const signature = submitJson.result;
// Poll for confirmation up to ~30s, then ask the API to mark it attached.
for (let i = 0; i < 15; i++) {
await new Promise((r) => setTimeout(r, 2000));
- const confirmRes = await fetch(`/api/agents/${encodeURIComponent(agentId)}/sns/register-confirm`, {
- method: 'POST',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ signature, domain, wallet_address: walletAddress }),
- });
+ const confirmRes = await fetch(
+ `/api/agents/${encodeURIComponent(agentId)}/sns/register-confirm`,
+ {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ signature,
+ domain,
+ wallet_address: walletAddress,
+ }),
+ },
+ );
const confirmJson = await confirmRes.json().catch(() => ({}));
if (confirmRes.ok) return confirmJson.data;
if (confirmJson.error !== 'not_confirmed') {
throw new Error(confirmJson.error_description || 'register-confirm failed');
}
}
- throw new Error('Registered on-chain but confirmation timed out — retry attaching from the owned-domains list in a moment.');
+ throw new Error(
+ 'Registered on-chain but confirmation timed out — retry attaching from the owned-domains list in a moment.',
+ );
}
function render(agentId, data) {
@@ -195,17 +231,15 @@
<div class="dash-card">
<h2>Owned domains</h2>
- ${
- !data.upstream_ok
- ? '<div class="dash-err">SNS API unreachable — retry in a moment.</div>'
- : ''
- }
+ ${!data.upstream_ok ? '<div class="dash-err">SNS API unreachable — retry in a moment.</div>' : ''}
${
domains.length
? `<ul class="dash-list">
${domains
.map(
- (d) => `<li class="dash-row" style="justify-content:space-between">
+ (
+ d,
+ ) => `<li class="dash-row" style="justify-content:space-between">
<div>
<span class="dash-mono" style="font-size:14px">${escapeHtml(d)}.sol</span>
${favorite === d ? ' <span class="dash-pill">favorite</span>' : ''}
@@ -291,11 +325,17 @@
setRegisterStatus('');
});
input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.preventDefault(); checkBtn.click(); }
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ checkBtn.click();
+ }
});
checkBtn.addEventListener('click', async () => {
- const raw = (input.value || '').trim().toLowerCase().replace(/\.sol$/, '');
+ const raw = (input.value || '')
+ .trim()
+ .toLowerCase()
+ .replace(/\.sol$/, '');
if (!/^[a-z0-9-]{1,63}$/.test(raw)) {
setRegisterStatus('Use a–z, 0–9, hyphen (max 63 chars).', 'err');
return;
@@ -305,11 +345,17 @@
try {
const info = await checkDomain(agentId, raw);
if (!info.available) {
- setRegisterStatus(`${raw}.sol is already registered (owner ${info.owner}).`, 'err');
+ setRegisterStatus(
+ `${raw}.sol is already registered (owner ${info.owner}).`,
+ 'err',
+ );
actionsEl.style.display = 'none';
return;
}
- setRegisterStatus(`${raw}.sol is available — ${info.price_usdc} USDC.`, 'ok');
+ setRegisterStatus(
+ `${raw}.sol is available — ${info.price_usdc} USDC.`,
+ 'ok',
+ );
actionsEl.innerHTML = `
<button class="dash-btn primary" id="register-agent-btn">
Buy with agent wallet (${info.price_usdc} USDC)
@@ -320,38 +366,53 @@
`;
actionsEl.style.display = '';
- document.getElementById('register-agent-btn').addEventListener('click', async () => {
- if (!confirm(`Register ${raw}.sol using the agent's wallet for ${info.price_usdc} USDC? The agent's USDC ATA must be funded.`)) return;
- const btn = document.getElementById('register-agent-btn');
- btn.disabled = true;
- setRegisterStatus('Registering on-chain (this can take 10-30s)…');
- try {
- const out = await registerWithAgent(agentId, raw);
- setRegisterStatus(`Registered ${out.sns_domain}.sol — signature ${out.signature.slice(0, 8)}…`, 'ok');
- input.value = '';
- actionsEl.style.display = 'none';
- await refresh(agentId);
- } catch (e) {
- setRegisterStatus(e.message || 'Register failed', 'err');
- btn.disabled = false;
- }
- });
+ document
+ .getElementById('register-agent-btn')
+ .addEventListener('click', async () => {
+ if (
+ !confirm(
+ `Register ${raw}.sol using the agent's wallet for ${info.price_usdc} USDC? The agent's USDC ATA must be funded.`,
+ )
+ )
+ return;
+ const btn = document.getElementById('register-agent-btn');
+ btn.disabled = true;
+ setRegisterStatus('Registering on-chain (this can take 10-30s)…');
+ try {
+ const out = await registerWithAgent(agentId, raw);
+ setRegisterStatus(
+ `Registered ${out.sns_domain}.sol — signature ${out.signature.slice(0, 8)}…`,
+ 'ok',
+ );
+ input.value = '';
+ actionsEl.style.display = 'none';
+ await refresh(agentId);
+ } catch (e) {
+ setRegisterStatus(e.message || 'Register failed', 'err');
+ btn.disabled = false;
+ }
+ });
- document.getElementById('register-browser-btn').addEventListener('click', async () => {
- const btn = document.getElementById('register-browser-btn');
- btn.disabled = true;
- setRegisterStatus('Connecting wallet…');
- try {
- const out = await registerWithBrowserWallet(agentId, raw);
- setRegisterStatus(`Registered ${out.sns_domain}.sol — signature ${out.signature.slice(0, 8)}…`, 'ok');
- input.value = '';
- actionsEl.style.display = 'none';
- await refresh(agentId);
- } catch (e) {
- setRegisterStatus(e.message || 'Register failed', 'err');
- btn.disabled = false;
- }
- });
+ document
+ .getElementById('register-browser-btn')
+ .addEventListener('click', async () => {
+ const btn = document.getElementById('register-browser-btn');
+ btn.disabled = true;
+ setRegisterStatus('Connecting wallet…');
+ try {
+ const out = await registerWithBrowserWallet(agentId, raw);
+ setRegisterStatus(
+ `Registered ${out.sns_domain}.sol — signature ${out.signature.slice(0, 8)}…`,
+ 'ok',
+ );
+ input.value = '';
+ actionsEl.style.display = 'none';
+ await refresh(agentId);
+ } catch (e) {
+ setRegisterStatus(e.message || 'Register failed', 'err');
+ btn.disabled = false;
+ }
+ });
} catch (e) {
setRegisterStatus(e.message || 'Check failed', 'err');
} finally {
diff --git a/src/agent-detail.js b/src/agent-detail.js
index cc8ca37bc..494ea1e17 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -16,7 +16,14 @@ import {
LAMPORTS_PER_SOL,
clusterApiUrl,
} from '@solana/web3.js';
-const solanaWeb3 = { Connection, PublicKey, Transaction, SystemProgram, LAMPORTS_PER_SOL, clusterApiUrl };
+const solanaWeb3 = {
+ Connection,
+ PublicKey,
+ Transaction,
+ SystemProgram,
+ LAMPORTS_PER_SOL,
+ clusterApiUrl,
+};
import { openSwapModal } from './swap-jupiter.js';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -94,11 +101,15 @@ function renderService(svc) {
el('div', { class: 'ad-svc-link' }, [
el('span', { text: '🔗' }),
el('span', { text: svc.url }),
- el('button', {
- class: 'ad-copy',
- 'aria-label': 'Copy',
- onclick: () => navigator.clipboard?.writeText(svc.url),
- }, '⧉'),
+ el(
+ 'button',
+ {
+ class: 'ad-copy',
+ 'aria-label': 'Copy',
+ onclick: () => navigator.clipboard?.writeText(svc.url),
+ },
+ '⧉',
+ ),
]),
);
}
@@ -124,7 +135,9 @@ function render(agent) {
$('ad-avatar').src = agent.avatar || avatarDataUri(agent.name);
$('ad-avatar').alt = agent.name;
- $('ad-avatar').onerror = () => { $('ad-avatar').src = avatarDataUri(agent.name); };
+ $('ad-avatar').onerror = () => {
+ $('ad-avatar').src = avatarDataUri(agent.name);
+ };
$('ad-name').textContent = agent.name;
const status = $('ad-status');
@@ -160,8 +173,9 @@ function render(agent) {
el('span', { class: 'ad-mono', text: shortAddr(agent.token.mint) }),
]);
$('ad-token-body').appendChild(tokenRow);
- const dashLink = agent.token.pumpfun_url
- || (agent.token.cluster === 'devnet'
+ const dashLink =
+ agent.token.pumpfun_url ||
+ (agent.token.cluster === 'devnet'
? `https://explorer.solana.com/address/${agent.token.mint}?cluster=devnet`
: `https://pump.fun/${agent.token.mint}`);
const viewBtn = el('a', {
@@ -221,7 +235,9 @@ function render(agent) {
const pay = $('ad-payment');
pay.innerHTML = '';
- pay.appendChild(pill(agent.x402 ? 'x402 Supported' : 'x402 Not Supported', agent.x402 ? 'green' : ''));
+ pay.appendChild(
+ pill(agent.x402 ? 'x402 Supported' : 'x402 Not Supported', agent.x402 ? 'green' : ''),
+ );
$('ad-agent-id').textContent = shortAddr(agent.id);
const regs = $('ad-registries');
@@ -264,17 +280,35 @@ function render(agent) {
if (agent.tradeUrl && agent.tradeUrl !== '#') $('ad-trade').href = agent.tradeUrl;
else $('ad-trade').style.display = 'none';
- const sns = agent.rawMetadata?.meta?.sns_domain;
- if (sns) {
+ const attachedSns = agent.rawMetadata?.meta?.sns_domain;
+ const solAddress = agent.rawMetadata?.meta?.solana_address;
+ if (attachedSns) {
document.getElementById('ad-sns-row').style.display = '';
- document.getElementById('ad-sns').textContent = `${sns}.sol`;
+ document.getElementById('ad-sns').textContent = `${attachedSns}.sol`;
+ } else if (solAddress) {
+ // Lazy reverse-lookup of the wallet's on-chain favorite. Fire-and-forget;
+ // 404s and timeouts just leave the row hidden — non-essential UX.
+ fetch(`/api/sns?address=${encodeURIComponent(solAddress)}`)
+ .then((r) => (r.ok ? r.json() : null))
+ .then((body) => {
+ const name = body?.data?.name;
+ if (!name) return;
+ const row = document.getElementById('ad-sns-row');
+ const span = document.getElementById('ad-sns');
+ if (!row || !span) return;
+ row.style.display = '';
+ span.textContent = name;
+ span.title = 'On-chain favorite domain';
+ })
+ .catch(() => {});
}
const voiceProvider = agent.rawMetadata?.voice_provider;
const voiceId = agent.rawMetadata?.voice_id;
if (voiceProvider && voiceProvider !== 'browser') {
document.getElementById('ad-voice-row').style.display = '';
- document.getElementById('ad-voice').innerHTML = `<span class="ad-pill ad-pill-green">cloned · ${voiceProvider}</span>`;
+ document.getElementById('ad-voice').innerHTML =
+ `<span class="ad-pill ad-pill-green">cloned · ${voiceProvider}</span>`;
} else if (voiceProvider === 'browser') {
document.getElementById('ad-voice-row').style.display = '';
document.getElementById('ad-voice').textContent = 'browser TTS';
@@ -290,21 +324,38 @@ async function loadExtraSections(agentId, rec) {
const url = (p) => `/api/agents/${encodeURIComponent(agentId)}${p}`;
const safe = async (fn) => {
- try { return await fn(); } catch (e) { return null; }
+ try {
+ return await fn();
+ } catch (e) {
+ return null;
+ }
};
const [actions, memory, strategy, reputation, embedPolicy] = await Promise.all([
safe(() => fetchJson(url('/actions?limit=8'))),
- safe(() => fetch(`/api/agent-memory?agentId=${encodeURIComponent(agentId)}&limit=6`, { credentials: 'include' }).then((r) => r.ok ? r.json() : null)),
- safe(() => fetch(`/api/agent-strategy?id=${encodeURIComponent(agentId)}`, { credentials: 'include' }).then((r) => r.ok ? r.json() : null)),
+ safe(() =>
+ fetch(`/api/agent-memory?agentId=${encodeURIComponent(agentId)}&limit=6`, {
+ credentials: 'include',
+ }).then((r) => (r.ok ? r.json() : null)),
+ ),
+ safe(() =>
+ fetch(`/api/agent-strategy?id=${encodeURIComponent(agentId)}`, {
+ credentials: 'include',
+ }).then((r) => (r.ok ? r.json() : null)),
+ ),
safe(() => fetchJson(url('/reputation'))),
- safe(() => fetch(url('/embed-policy'), { credentials: 'include' }).then((r) => r.ok ? r.json() : null)),
+ safe(() =>
+ fetch(url('/embed-policy'), { credentials: 'include' }).then((r) =>
+ r.ok ? r.json() : null,
+ ),
+ ),
]);
if (actions?.actions?.length) renderActions(actions.actions, agentId);
if (memory?.entries?.length) renderMemory(memory.entries);
if (strategy?.data?.strategy != null) renderStrategy(strategy.data.strategy);
- if (reputation && (reputation.count > 0 || reputation.average > 0)) renderReputation(reputation);
+ if (reputation && (reputation.count > 0 || reputation.average > 0))
+ renderReputation(reputation);
if (embedPolicy) renderEmbedPolicy(embedPolicy);
}
@@ -323,7 +374,16 @@ function fmtRelTime(iso) {
}
function actionIcon(type) {
- return ({ speak: '💬', remember: '📝', sign: '✍️', 'skill-done': '✓', validate: '✔', 'load-end': '📦' })[type] || '•';
+ return (
+ {
+ speak: '💬',
+ remember: '📝',
+ sign: '✍️',
+ 'skill-done': '✓',
+ validate: '✔',
+ 'load-end': '📦',
+ }[type] || '•'
+ );
}
function summarizeActionPayload(p) {
@@ -343,29 +403,53 @@ function renderActions(actions, agentId) {
list.innerHTML = '';
for (const a of actions) {
const verifyMark =
- a.verified === true ? '<span class="ad-pill ad-pill-green" title="signature verified">✓</span>'
- : a.verified === false ? '<span class="ad-pill" title="invalid signature">✗</span>'
- : '';
- const meta = el('span', { class: 'ad-muted', style: 'font-size:11px;display:flex;align-items:center;gap:6px' });
+ a.verified === true
+ ? '<span class="ad-pill ad-pill-green" title="signature verified">✓</span>'
+ : a.verified === false
+ ? '<span class="ad-pill" title="invalid signature">✗</span>'
+ : '';
+ const meta = el('span', {
+ class: 'ad-muted',
+ style: 'font-size:11px;display:flex;align-items:center;gap:6px',
+ });
if (verifyMark) {
const m = document.createElement('span');
m.innerHTML = verifyMark;
meta.appendChild(m);
}
meta.appendChild(el('span', { text: fmtRelTime(a.timestamp) }));
- const row = el('div', { class: 'ad-row ad-row-split', style: 'padding:8px 0;border-bottom:1px solid rgba(255,255,255,0.04)' }, [
- el('span', { style: 'display:flex;align-items:center;gap:8px;min-width:0' }, [
- el('span', { text: actionIcon(a.type) }),
- el('span', { class: 'ad-mono', style: 'min-width:90px;flex-shrink:0', text: a.type }),
- el('span', { class: 'ad-muted', style: 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap', text: summarizeActionPayload(a.payload) }),
- ]),
- meta,
- ]);
+ const row = el(
+ 'div',
+ {
+ class: 'ad-row ad-row-split',
+ style: 'padding:8px 0;border-bottom:1px solid rgba(255,255,255,0.04)',
+ },
+ [
+ el('span', { style: 'display:flex;align-items:center;gap:8px;min-width:0' }, [
+ el('span', { text: actionIcon(a.type) }),
+ el('span', {
+ class: 'ad-mono',
+ style: 'min-width:90px;flex-shrink:0',
+ text: a.type,
+ }),
+ el('span', {
+ class: 'ad-muted',
+ style: 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap',
+ text: summarizeActionPayload(a.payload),
+ }),
+ ]),
+ meta,
+ ],
+ );
list.appendChild(row);
}
list.appendChild(
el('div', { style: 'text-align:center;padding-top:10px' }, [
- el('a', { class: 'ad-cta', href: `/dashboard/actions?agent=${encodeURIComponent(agentId)}`, text: 'See full action log →' }),
+ el('a', {
+ class: 'ad-cta',
+ href: `/dashboard/actions?agent=${encodeURIComponent(agentId)}`,
+ text: 'See full action log →',
+ }),
]),
);
card.style.display = '';
@@ -377,10 +461,21 @@ function renderMemory(entries) {
const list = document.getElementById('ad-memory-list');
list.innerHTML = '';
for (const m of entries) {
- const row = el('div', { style: 'padding:8px 0;border-bottom:1px solid rgba(255,255,255,0.04)' }, [
- el('div', { class: 'ad-muted', style: 'font-size:11px;text-transform:uppercase;letter-spacing:.05em;margin-bottom:2px', text: m.type || 'memory' }),
- el('div', { style: 'color:#ddd;font-size:13px;white-space:pre-wrap', text: String(m.content || '').slice(0, 240) }),
- ]);
+ const row = el(
+ 'div',
+ { style: 'padding:8px 0;border-bottom:1px solid rgba(255,255,255,0.04)' },
+ [
+ el('div', {
+ class: 'ad-muted',
+ style: 'font-size:11px;text-transform:uppercase;letter-spacing:.05em;margin-bottom:2px',
+ text: m.type || 'memory',
+ }),
+ el('div', {
+ style: 'color:#ddd;font-size:13px;white-space:pre-wrap',
+ text: String(m.content || '').slice(0, 240),
+ }),
+ ],
+ );
list.appendChild(row);
}
card.style.display = '';
@@ -395,7 +490,9 @@ function renderStrategy(strategy) {
function renderReputation(r) {
const card = document.getElementById('ad-reputation-card');
- document.getElementById('ad-rep-avg').textContent = r.average ? Number(r.average).toFixed(2) : '0.00';
+ document.getElementById('ad-rep-avg').textContent = r.average
+ ? Number(r.average).toFixed(2)
+ : '0.00';
document.getElementById('ad-rep-count').textContent = String(r.count || 0);
if (r.total_stake_wei && r.total_stake_wei !== '0') {
document.getElementById('ad-rep-stake-row').style.display = '';
@@ -416,26 +513,40 @@ function renderEmbedPolicy(p) {
const allowedOrigins = Array.isArray(p.allowed_origins) ? p.allowed_origins : [];
const monthlyQuota = p?.brain?.monthly_quota;
- host.appendChild(el('div', { class: 'ad-row ad-row-split' }, [
- el('span', { class: 'ad-muted', text: 'Embeddable' }),
- el('span', { text: allowEmbed }),
- ]));
+ host.appendChild(
+ el('div', { class: 'ad-row ad-row-split' }, [
+ el('span', { class: 'ad-muted', text: 'Embeddable' }),
+ el('span', { text: allowEmbed }),
+ ]),
+ );
if (allowedOrigins.length) {
- host.appendChild(el('div', { class: 'ad-row ad-row-split' }, [
- el('span', { class: 'ad-muted', text: 'Allowed origins' }),
- el('span', { class: 'ad-mono', style: 'font-size:11px;text-align:right', text: allowedOrigins.slice(0, 3).join(', ') + (allowedOrigins.length > 3 ? ` +${allowedOrigins.length - 3}` : '') }),
- ]));
+ host.appendChild(
+ el('div', { class: 'ad-row ad-row-split' }, [
+ el('span', { class: 'ad-muted', text: 'Allowed origins' }),
+ el('span', {
+ class: 'ad-mono',
+ style: 'font-size:11px;text-align:right',
+ text:
+ allowedOrigins.slice(0, 3).join(', ') +
+ (allowedOrigins.length > 3 ? ` +${allowedOrigins.length - 3}` : ''),
+ }),
+ ]),
+ );
} else if (allowEmbed === 'Yes') {
- host.appendChild(el('div', { class: 'ad-row ad-row-split' }, [
- el('span', { class: 'ad-muted', text: 'Allowed origins' }),
- el('span', { text: 'any' }),
- ]));
+ host.appendChild(
+ el('div', { class: 'ad-row ad-row-split' }, [
+ el('span', { class: 'ad-muted', text: 'Allowed origins' }),
+ el('span', { text: 'any' }),
+ ]),
+ );
}
if (monthlyQuota != null) {
- host.appendChild(el('div', { class: 'ad-row ad-row-split' }, [
- el('span', { class: 'ad-muted', text: 'Monthly LLM quota' }),
- el('span', { text: String(monthlyQuota) }),
- ]));
+ host.appendChild(
+ el('div', { class: 'ad-row ad-row-split' }, [
+ el('span', { class: 'ad-muted', text: 'Monthly LLM quota' }),
+ el('span', { text: String(monthlyQuota) }),
+ ]),
+ );
}
card.style.display = '';
}
@@ -462,7 +573,9 @@ function makeSnsResolver(inputEl, statusEl) {
const myId = ++seq;
pending = (async () => {
try {
- const r = await fetch(`/api/sns?name=${encodeURIComponent(name)}`, { credentials: 'include' });
+ const r = await fetch(`/api/sns?name=${encodeURIComponent(name)}`, {
+ credentials: 'include',
+ });
if (myId !== seq) return null; // superseded
if (r.status === 404) {
setStatus('warn', `${name} does not resolve`);
@@ -498,7 +611,10 @@ function makeSnsResolver(inputEl, statusEl) {
pending = null;
lastResolved = null;
- if (!raw) { setStatus('', ''); return; }
+ if (!raw) {
+ setStatus('', '');
+ return;
+ }
if (SOL_ADDR_RE.test(raw)) {
lastResolved = { name: null, address: raw };
setStatus('', '');
@@ -560,17 +676,17 @@ function bindWalletActions() {
const snsResolver = makeSnsResolver(recipientAddressInput, recipientResolvedEl);
receiveBtn.addEventListener('click', () => {
- const walletAddress = walletAddressSpan.dataset.full;
- if (walletAddress) {
- qrCodeContainer.classList.toggle('hidden');
- if (!qrCodeContainer.classList.contains('hidden')) {
- new QRious({
- element: qrCodeCanvas,
- value: walletAddress,
- size: 160,
- });
- }
+ const walletAddress = walletAddressSpan.dataset.full;
+ if (walletAddress) {
+ qrCodeContainer.classList.toggle('hidden');
+ if (!qrCodeContainer.classList.contains('hidden')) {
+ new QRious({
+ element: qrCodeCanvas,
+ value: walletAddress,
+ size: 160,
+ });
}
+ }
});
withdrawBtn.addEventListener('click', () => {
@@ -618,7 +734,7 @@ function bindWalletActions() {
fromPubkey: wallet,
toPubkey: recipientPubKey,
lamports: amount * solanaWeb3.LAMPORTS_PER_SOL,
- })
+ }),
);
transaction.feePayer = wallet;
@@ -630,16 +746,16 @@ function bindWalletActions() {
const signature = await connection.sendRawTransaction(signedTransaction.serialize());
await connection.confirmTransaction(signature);
- const displayTarget = typedRecipient === recipientAddress
- ? recipientAddress
- : `${typedRecipient} (${recipientAddress})`;
+ const displayTarget =
+ typedRecipient === recipientAddress
+ ? recipientAddress
+ : `${typedRecipient} (${recipientAddress})`;
alert(`Withdrawal of ${amount} SOL to ${displayTarget} successful!`);
modal.classList.add('hidden');
withdrawAmountInput.value = '';
recipientAddressInput.value = '';
snsResolver.reset();
-
} catch (error) {
console.error('Withdrawal failed:', error);
alert(`Withdrawal failed: ${error.message}`);
@@ -711,7 +827,9 @@ function normalize(rec, avatar) {
type: 'a2a',
version: meta.a2a_version || '0.3.0',
url: `${location.origin}/agent/${rec.id}`,
- skills: rec.skills.map((s) => (typeof s === 'string' ? s : s.name || s.id)).filter(Boolean),
+ skills: rec.skills
+ .map((s) => (typeof s === 'string' ? s : s.name || s.id))
+ .filter(Boolean),
domains: meta.domains || undefined,
});
}
@@ -731,7 +849,8 @@ function normalize(rec, avatar) {
if (rec.home_url) protocols.push('WEB');
if (rec.skills?.length) protocols.push(`A2A ${meta.a2a_version || '0.3.0'}`);
if (rec.token?.symbol) protocols.push(`TOKEN ${rec.token.symbol}`);
- if (onchain?.chain_id || rec.chain_id) protocols.push(`CHAIN ${onchain?.chain_id ?? rec.chain_id}`);
+ if (onchain?.chain_id || rec.chain_id)
+ protocols.push(`CHAIN ${onchain?.chain_id ?? rec.chain_id}`);
const wallet = rec.wallet_address || onchain.wallet || meta.solana_wallet || '';
@@ -759,7 +878,7 @@ function normalize(rec, avatar) {
authority: onchain.authority || rec.erc8004_registry || '',
solBalance: meta.sol_balance ?? 0,
creatorRewards: meta.creator_rewards ?? 0,
- x402: !!(rec.payments?.accepted_tokens?.length),
+ x402: !!rec.payments?.accepted_tokens?.length,
registries,
protocols,
explorerUrl,
@@ -782,7 +901,10 @@ async function loadAgent(id) {
const json = await fetchJson(`/api/agents/${encodeURIComponent(id)}`);
rec = json.agent;
} catch (e) {
- return { error: e.status === 404 ? 'No agent with id' : `Fetch failed: ${e.message}`, agent: null };
+ return {
+ error: e.status === 404 ? 'No agent with id' : `Fetch failed: ${e.message}`,
+ agent: null,
+ };
}
if (!rec) return { error: 'No agent with id', agent: null };
@@ -816,7 +938,10 @@ let wallet = null;
// Route through our same-origin proxy. Public devnet RPC is also rate-limited
// from browsers; the proxy keeps both clusters consistent.
const _rpcOrigin = window.location?.origin || 'https://three.ws';
-const connection = new solanaWeb3.Connection(`${_rpcOrigin}/api/solana-rpc?net=devnet`, 'confirmed');
+const connection = new solanaWeb3.Connection(
+ `${_rpcOrigin}/api/solana-rpc?net=devnet`,
+ 'confirmed',
+);
const connectWalletBtn = document.getElementById('connect-wallet-btn');
connectWalletBtn.addEventListener('click', async () => {
@@ -833,8 +958,9 @@ connectWalletBtn.addEventListener('click', async () => {
}
});
-
-const id = new URLSearchParams(location.search).get('id') || location.pathname.match(/\/agents\/([^/]+)/)?.[1];
+const id =
+ new URLSearchParams(location.search).get('id') ||
+ location.pathname.match(/\/agents\/([^/]+)/)?.[1];
loadAgent(id)
.then(({ agent, error }) => {
if (!agent) return renderNotFound(id, error);
diff --git a/tests/api/x402-pay-by-name.test.js b/tests/api/x402-pay-by-name.test.js
index 59189a52b..4d52ab639 100644
--- a/tests/api/x402-pay-by-name.test.js
+++ b/tests/api/x402-pay-by-name.test.js
@@ -37,7 +37,9 @@ const connMock = {
};
vi.mock('../../api/_lib/agent-pumpfun.js', () => ({
solanaConnection: () => connMock,
- loadAgentForSigning: vi.fn(async () => ({ error: { status: 404, code: 'not_found', msg: 'agent not found' } })),
+ loadAgentForSigning: vi.fn(async () => ({
+ error: { status: 404, code: 'not_found', msg: 'agent not found' },
+ })),
}));
beforeAll(() => {
@@ -60,8 +62,10 @@ function makeReq(url, method = 'GET', body = null) {
const buf = Buffer.from(JSON.stringify(body));
let read = false;
req.on = (event, cb) => {
- if (event === 'data' && !read) { cb(buf); read = true; }
- else if (event === 'end') queueMicrotask(cb);
+ if (event === 'data' && !read) {
+ cb(buf);
+ read = true;
+ } else if (event === 'end') queueMicrotask(cb);
return req;
};
req.headers['content-length'] = String(buf.length);
@@ -72,16 +76,24 @@ function makeRes() {
return {
statusCode: 200,
_h: {},
- setHeader(k, v) { this._h[k.toLowerCase()] = v; },
- getHeader(k) { return this._h[k.toLowerCase()]; },
- end(body) { this._body = body; },
+ setHeader(k, v) {
+ this._h[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this._h[k.toLowerCase()];
+ },
+ end(body) {
+ this._body = body;
+ },
};
}
async function call(url, method, body) {
const res = makeRes();
await handler(makeReq(url, method, body), res);
let parsed = null;
- try { parsed = JSON.parse(res._body); } catch {}
+ try {
+ parsed = JSON.parse(res._body);
+ } catch {}
return { res, body: parsed };
}
@@ -114,13 +126,15 @@ describe('GET /api/x402/pay-by-name?name=… (resolve)', () => {
it('resolves a <label>.threews.sol and joins the DB claim', async () => {
snsResolveMock.mockResolvedValue({ toBase58: () => ADDR });
- sqlMock.mockResolvedValueOnce([{
- label: 'nich',
- parent: 'threews',
- user_id: '00000000-0000-0000-0000-000000000001',
- username: 'nich',
- display_name: 'Nicholas',
- }]);
+ sqlMock.mockResolvedValueOnce([
+ {
+ label: 'nich',
+ parent: 'threews',
+ user_id: '00000000-0000-0000-0000-000000000001',
+ username: 'nich',
+ display_name: 'Nicholas',
+ },
+ ]);
const { res, body } = await call('/api/x402/pay-by-name?name=nich.threews.sol');
expect(res.statusCode).toBe(200);
expect(body.data.address).toBe(ADDR);
@@ -141,7 +155,7 @@ describe('GET /api/x402/pay-by-name?name=… (resolve)', () => {
expect(body.error).toBe('not_found');
});
- it('resolves @username to the user\'s default agent wallet', async () => {
+ it("resolves @username to the user's default agent wallet", async () => {
sqlMock
.mockResolvedValueOnce([{ id: 'u1', username: 'nich', display_name: 'Nicholas' }])
.mockResolvedValueOnce([{ sol: ADDR }]);
@@ -197,7 +211,9 @@ describe('GET /api/x402/pay-by-name?name=… (resolve)', () => {
describe('POST /api/x402/pay-by-name (mode=prep)', () => {
it('rejects when payer_wallet is missing or malformed', async () => {
const { res, body } = await call('/api/x402/pay-by-name', 'POST', {
- mode: 'prep', name: ADDR, amount_usdc: 1,
+ mode: 'prep',
+ name: ADDR,
+ amount_usdc: 1,
});
expect(res.statusCode).toBe(400);
expect(body.error_description).toMatch(/payer_wallet/);
@@ -205,7 +221,10 @@ describe('POST /api/x402/pay-by-name (mode=prep)', () => {
it('rejects amount_usdc <= 0', async () => {
const { res, body } = await call('/api/x402/pay-by-name', 'POST', {
- mode: 'prep', name: ADDR, amount_usdc: 0, payer_wallet: PAYER,
+ mode: 'prep',
+ name: ADDR,
+ amount_usdc: 0,
+ payer_wallet: PAYER,
});
expect(res.statusCode).toBe(400);
expect(body.error_description).toMatch(/amount_usdc/);
@@ -213,7 +232,10 @@ describe('POST /api/x402/pay-by-name (mode=prep)', () => {
it('rejects amount_usdc above the per-call cap', async () => {
const { res, body } = await call('/api/x402/pay-by-name', 'POST', {
- mode: 'prep', name: ADDR, amount_usdc: 50_000, payer_wallet: PAYER,
+ mode: 'prep',
+ name: ADDR,
+ amount_usdc: 50_000,
+ payer_wallet: PAYER,
});
expect(res.statusCode).toBe(400);
expect(body.error_description).toMatch(/amount_usdc/);
@@ -221,7 +243,10 @@ describe('POST /api/x402/pay-by-name (mode=prep)', () => {
it('rejects self-pay (payer == recipient)', async () => {
const { res, body } = await call('/api/x402/pay-by-name', 'POST', {
- mode: 'prep', name: PAYER, amount_usdc: 1, payer_wallet: PAYER,
+ mode: 'prep',
+ name: PAYER,
+ amount_usdc: 1,
+ payer_wallet: PAYER,
});
expect(res.statusCode).toBe(400);
expect(body.error).toBe('self_pay');
@@ -230,7 +255,10 @@ describe('POST /api/x402/pay-by-name (mode=prep)', () => {
it('returns 404 if the name does not resolve', async () => {
snsResolveMock.mockRejectedValue(new Error('DomainDoesNotExist'));
const { res, body } = await call('/api/x402/pay-by-name', 'POST', {
- mode: 'prep', name: 'ghost.sol', amount_usdc: 1, payer_wallet: PAYER,
+ mode: 'prep',
+ name: 'ghost.sol',
+ amount_usdc: 1,
+ payer_wallet: PAYER,
});
expect(res.statusCode).toBe(404);
expect(body.error).toBe('not_found');
@@ -238,7 +266,10 @@ describe('POST /api/x402/pay-by-name (mode=prep)', () => {
it('builds a base64 VersionedTransaction when inputs are valid', async () => {
const { res, body } = await call('/api/x402/pay-by-name', 'POST', {
- mode: 'prep', name: ADDR, amount_usdc: 1.5, payer_wallet: PAYER,
+ mode: 'prep',
+ name: ADDR,
+ amount_usdc: 1.5,
+ payer_wallet: PAYER,
});
expect(res.statusCode).toBe(200);
expect(body.data.recipient.address).toBe(ADDR);
@@ -252,7 +283,10 @@ describe('POST /api/x402/pay-by-name (mode=prep)', () => {
describe('POST /api/x402/pay-by-name (mode=send)', () => {
it('requires authentication', async () => {
const { res, body } = await call('/api/x402/pay-by-name', 'POST', {
- mode: 'send', name: ADDR, amount_usdc: 1, agent_id: 'a1',
+ mode: 'send',
+ name: ADDR,
+ amount_usdc: 1,
+ agent_id: 'a1',
});
expect(res.statusCode).toBe(401);
expect(body.error).toBe('unauthorized');
@@ -261,7 +295,9 @@ describe('POST /api/x402/pay-by-name (mode=send)', () => {
it('requires agent_id even when authenticated', async () => {
getSessionUserMock.mockResolvedValue({ id: 'u1' });
const { res, body } = await call('/api/x402/pay-by-name', 'POST', {
- mode: 'send', name: ADDR, amount_usdc: 1,
+ mode: 'send',
+ name: ADDR,
+ amount_usdc: 1,
});
expect(res.statusCode).toBe(400);
expect(body.error_description).toMatch(/agent_id/);