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.

home polish, threews/me, og card, pay-by-name resolve tests

nirholas404bd62d0441
diff --git a/api/_lib/env.js b/api/_lib/env.js
index fe4c34ccb..c9950654d 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -357,6 +357,25 @@ export const env = {
return opt('SOLANA_RPC_URL', 'https://api.mainnet-beta.solana.com');
},
+ // ── threews.sol subdomain minting ─────────────────────────────────────
+ // Parent .sol domain we mint subdomains under (e.g. `threews.sol`). The
+ // platform must own this domain on-chain via THREEWS_SOL_PARENT_SECRET_BASE58.
+ get THREEWS_SOL_PARENT_DOMAIN() {
+ return opt('THREEWS_SOL_PARENT_DOMAIN', 'threews.sol');
+ },
+ // Base58-encoded 64-byte ed25519 secret for the keypair that owns the
+ // parent .sol domain. Signs createSubdomain + URL-record + transfer
+ // for both /api/threews/subdomain (user claims) and /api/sns-subdomain
+ // (agent claims). Unset → subdomain minting returns 503.
+ get THREEWS_SOL_PARENT_SECRET_BASE58() {
+ return opt('THREEWS_SOL_PARENT_SECRET_BASE58');
+ },
+ // Public origin written into the SNS URL record so Brave-resolved
+ // subdomains land on the correct deployment. Defaults to https://three.ws.
+ get STOREFRONT_ORIGIN() {
+ return trimSlash(opt('STOREFRONT_ORIGIN', 'https://three.ws'));
+ },
+
// ── Lottery + Reflection coin (api/_lib/coin/*) ───────────────────────
// Treasury keypair (base64-encoded 64-byte secret). Fee payer for every
// lottery winner transfer + reflection batch transfer. Holds the SOL that
diff --git a/api/_lib/x402.js b/api/_lib/x402.js
index 71170af08..9232abe9e 100644
--- a/api/_lib/x402.js
+++ b/api/_lib/x402.js
@@ -48,21 +48,18 @@
import { sql } from './db.js';
import { json, error } from './http.js';
-import { resolveSnsName } from '../../src/solana/sns.js';
+import { resolveSolanaRecipient } from '../../src/solana/sns.js';
export const X402_VERSION = 'x402/0.1';
-const SNS_NAME_RE = /^[a-z0-9-]{1,63}(?:\.[a-z0-9-]{1,63})*\.sol$/i;
-
-// Resolve the manifest's `recipient` to a concrete base58 wallet, and surface
-// the human-readable .sol name in `recipient_name` whenever one is available.
-//
-// Inputs in priority order:
-// 1. `payments.receiver` — already a base58 wallet (most agents today).
-// 2. `payments.receiver` set to a .sol or subdomain — resolve via SNS.
-// 3. `agent.meta.sns_domain` — preferred display name even when receiver
-// is a base58 wallet, so x402 clients can show "paying nich.threews.sol"
-// instead of a raw key.
+// Resolve the manifest's `recipient` to a base58 wallet and a human-readable
+// `recipient_name`. Two inputs feed this:
+// - `payments.receiver` — base58 wallet OR a .sol/subdomain. When it's a
+// name, resolveSolanaRecipient() does the SNS lookup and we use the name
+// as the display value.
+// - `agent.meta.sns_domain` — preferred display name even when receiver is
+// a base58 wallet, so clients show "paying nich.threews.sol" rather than
+// a raw key.
async function resolveRecipient({ agent, payments }) {
const receiver = payments?.receiver;
const metaName = agent?.meta?.sns_domain || null;
@@ -70,11 +67,15 @@ async function resolveRecipient({ agent, payments }) {
? (metaName.endsWith('.sol') ? metaName : `${metaName}.sol`)
: null;
- if (typeof receiver === 'string' && SNS_NAME_RE.test(receiver)) {
- const resolved = await resolveSnsName(receiver);
- return { recipient: resolved || null, recipient_name: receiver.toLowerCase() };
+ const { address, resolved_from } = await resolveSolanaRecipient(receiver || '');
+ if (resolved_from) {
+ return { recipient: address, recipient_name: resolved_from };
}
- return { recipient: receiver || null, recipient_name: metaNameFull };
+ // Receiver wasn't recognized as a SNS name — pass through whatever the
+ // agent has stored. Most agents store a base58 wallet here; some legacy
+ // records may use a non-base58 placeholder. We don't gatekeep at this
+ // layer; the wallet adapter / payment program will validate at sign-time.
+ return { recipient: address ?? (receiver || null), recipient_name: metaNameFull };
}
/**
diff --git a/api/chat-skills.js b/api/chat-skills.js
index 830637770..da4657acc 100644
--- a/api/chat-skills.js
+++ b/api/chat-skills.js
@@ -16,9 +16,7 @@ import { readFileSync } from 'fs';
import { cors, json, method, wrap } from './_lib/http.js';
import { loadLocalSkillPacks } from '../src/skills/local-packs.js';
-const { version } = JSON.parse(
- readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
-);
+const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
const _skillMetadata = JSON.parse(
readFileSync(new URL('../data/_generated/skill-metadata.json', import.meta.url), 'utf8'),
@@ -41,18 +39,18 @@ function buildClientToolFor(skill) {
" method: 'POST',",
" headers: { 'content-type': 'application/json' },",
" credentials: 'include',",
- " body: JSON.stringify({",
+ ' body: JSON.stringify({',
" jsonrpc: '2.0', id: 1, method: 'tools/call',",
` params: { name: ${JSON.stringify(mcpName)}, arguments: args || {} },`,
- " }),",
- "});",
- "const _t = await _r.text();",
- "let _d = null; try { _d = _t ? JSON.parse(_t) : null; } catch {}",
+ ' }),',
+ '});',
+ 'const _t = await _r.text();',
+ 'let _d = null; try { _d = _t ? JSON.parse(_t) : null; } catch {}',
"if (!_r.ok) return JSON.stringify({ error: (_d && (_d.error?.message || _d.error)) || ('HTTP ' + _r.status) });",
- "if (_d && _d.error) return JSON.stringify({ error: _d.error.message || _d.error });",
- "const _c = _d && _d.result && _d.result.content;",
+ 'if (_d && _d.error) return JSON.stringify({ error: _d.error.message || _d.error });',
+ 'const _c = _d && _d.result && _d.result.content;',
"if (Array.isArray(_c)) return _c.map(x => x.text || JSON.stringify(x)).join('\\n');",
- "return JSON.stringify(_c ?? _d ?? null, null, 2);",
+ 'return JSON.stringify(_c ?? _d ?? null, null, 2);',
].join('\n');
return {
clientDefinition: {
diff --git a/api/insights/revenue-vision.js b/api/insights/revenue-vision.js
index 3477a79db..04a006beb 100644
--- a/api/insights/revenue-vision.js
+++ b/api/insights/revenue-vision.js
@@ -13,6 +13,7 @@
import { wrap, cors, error } from '../_lib/http.js';
import {
NETWORK_BASE_MAINNET,
+ NETWORK_SOLANA_MAINNET,
send402,
verifyPayment,
settlePayment,
@@ -125,6 +126,18 @@ function buildRequirements(resourceUrl) {
const out = [eip3009];
const permit2 = permit2VariantOf(eip3009);
if (permit2) out.push(permit2);
+ if (env.X402_PAY_TO_SOLANA) {
+ out.push({
+ scheme: 'exact',
+ network: NETWORK_SOLANA_MAINNET,
+ amount: env.X402_MAX_AMOUNT_REQUIRED,
+ payTo: env.X402_PAY_TO_SOLANA,
+ asset: env.X402_ASSET_MINT_SOLANA,
+ maxTimeoutSeconds: 60,
+ resource: resourceUrl,
+ extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
+ });
+ }
return out;
}
diff --git a/api/skills-manifest.js b/api/skills-manifest.js
index 6b73f62e6..4df48ca64 100644
--- a/api/skills-manifest.js
+++ b/api/skills-manifest.js
@@ -9,9 +9,7 @@ import { readFileSync } from 'fs';
import { cors, json, method, wrap } from './_lib/http.js';
import { buildSkillManifest } from '../src/skill-manifest.js';
-const { version } = JSON.parse(
- readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
-);
+const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
const _skillMetadata = JSON.parse(
readFileSync(new URL('../data/_generated/skill-metadata.json', import.meta.url), 'utf8'),
diff --git a/api/threews/me.js b/api/threews/me.js
new file mode 100644
index 000000000..2bde77939
--- /dev/null
+++ b/api/threews/me.js
@@ -0,0 +1,63 @@
+// GET /api/threews/me
+//
+// Returns the authenticated caller's `*.threews.sol` subdomain claim, if any.
+// Powers the dashboard widget that shows "your subdomain" without making the
+// caller pass their own label as a query parameter.
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, error, json, method, wrap } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { env } from '../_lib/env.js';
+import { PARENT_LABEL, fullDomain } from '../_lib/threews-sns.js';
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [user] = await sql`
+ SELECT id, username, display_name FROM users
+ WHERE id = ${auth.userId} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!user) return error(res, 404, 'not_found', 'user not found');
+
+ const [claim] = await sql`
+ SELECT label, parent, owner_wallet, url_record, signature, created_at
+ FROM user_subdomains
+ WHERE user_id = ${auth.userId} AND parent = ${PARENT_LABEL}
+ ORDER BY created_at ASC
+ LIMIT 1
+ `;
+
+ return json(res, 200, {
+ data: {
+ user: { id: user.id, username: user.username, display_name: user.display_name },
+ parent: PARENT_LABEL,
+ has_claim: !!claim,
+ claim: claim
+ ? {
+ ...claim,
+ full: fullDomain(claim.label),
+ showcase_url: `${env.APP_ORIGIN}/u/${user.username}`,
+ explorer: `https://solscan.io/tx/${claim.signature}`,
+ }
+ : null,
+ claim_url: !claim && user.username ? `${env.APP_ORIGIN}/threews/claim` : null,
+ },
+ });
+});
diff --git a/api/u-og.js b/api/u-og.js
new file mode 100644
index 000000000..ff5991a7e
--- /dev/null
+++ b/api/u-og.js
@@ -0,0 +1,146 @@
+/**
+ * User-profile OG image endpoint
+ * ------------------------------
+ * GET /api/u-og?username=<u>
+ *
+ * Renders an SVG OG card for /u/<username>. If the user has claimed
+ * <username>.threews.sol, the SVG carries a verified-on-Solana badge so the
+ * preview in Slack/X/Discord/Telegram advertises the on-chain handle.
+ *
+ * SVG instead of @vercel/og: cheap (no canvas / no chrome), instantly
+ * cacheable, and all major link unfurlers accept image/svg+xml.
+ */
+
+import { sql } from './_lib/db.js';
+import { cors, wrap } from './_lib/http.js';
+import { PARENT_LABEL } from './_lib/threews-sns.js';
+
+const CACHE_OK = 'public, max-age=300, s-maxage=3600';
+const CACHE_404 = 'public, max-age=60';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+
+ const url = new URL(req.url, 'http://x');
+ const raw = (url.searchParams.get('username') || '').trim().toLowerCase();
+ if (!raw || !/^[a-z0-9_-]{3,30}$/.test(raw)) {
+ return send(res, 400, CACHE_404, {
+ handle: '',
+ display: 'Invalid username',
+ subdomain: null,
+ stats: null,
+ });
+ }
+
+ const [user] = await sql`
+ SELECT id, username, display_name
+ FROM users
+ WHERE lower(username) = ${raw} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!user) {
+ return send(res, 404, CACHE_404, {
+ handle: raw,
+ display: 'User not found',
+ subdomain: null,
+ stats: null,
+ });
+ }
+
+ const [claimRow] = await sql`
+ SELECT label FROM user_subdomains
+ WHERE user_id = ${user.id} AND parent = ${PARENT_LABEL}
+ LIMIT 1
+ `;
+ const subdomain = claimRow ? `${claimRow.label}.${PARENT_LABEL}.sol` : null;
+
+ // Lightweight stat strip — same numbers the showcase shows.
+ const [statRow] = await sql`
+ SELECT
+ (SELECT count(*) FROM avatars WHERE owner_id = ${user.id} AND visibility = 'public' AND deleted_at IS NULL) AS avatars,
+ (SELECT count(*) FROM agent_identities WHERE user_id = ${user.id} AND is_public = true AND deleted_at IS NULL) AS agents
+ `;
+ const stats = {
+ avatars: Number(statRow?.avatars || 0),
+ agents: Number(statRow?.agents || 0),
+ };
+
+ return send(res, 200, CACHE_OK, {
+ handle: user.username,
+ display: user.display_name || user.username,
+ subdomain,
+ stats,
+ });
+});
+
+function send(res, status, cacheControl, payload) {
+ res.statusCode = status;
+ res.setHeader('content-type', 'image/svg+xml; charset=utf-8');
+ res.setHeader('cache-control', cacheControl);
+ res.end(renderCard(payload));
+}
+
+function renderCard({ handle, display, subdomain, stats }) {
+ const name = escapeXml(truncate(display || handle, 36));
+ const at = handle ? `@${escapeXml(truncate(handle, 30))}` : '';
+ const sub = subdomain ? escapeXml(subdomain) : null;
+ const counts = stats
+ ? [
+ stats.avatars ? `${stats.avatars} avatar${stats.avatars === 1 ? '' : 's'}` : null,
+ stats.agents ? `${stats.agents} agent${stats.agents === 1 ? '' : 's'}` : null,
+ ].filter(Boolean).join(' · ')
+ : '';
+
+ // Verified badge — six-pointed star + subdomain. Only drawn when the user
+ // has actually claimed `<handle>.threews.sol`.
+ const badge = sub
+ ? `
+ <g transform="translate(80, 460)">
+ <rect x="0" y="0" rx="999" ry="999" width="${28 + sub.length * 14}" height="44" fill="rgba(105,225,111,0.08)" stroke="rgba(105,225,111,0.4)"/>
+ <path transform="translate(14, 22) scale(.9)" fill="#69e16f" d="M0 -12 L3.6 -3.6 L12 -2.4 L6 4 L7.2 12 L0 8 L-7.2 12 L-6 4 L-12 -2.4 L-3.6 -3.6 Z"/>
+ <text x="34" y="29" fill="#69e16f" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="20" font-weight="500" letter-spacing="-.2">${sub}</text>
+ </g>`
+ : '';
+
+ const handlePill = at
+ ? `
+ <g transform="translate(80, 380)">
+ <text fill="rgba(229,229,229,0.55)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="34" font-weight="300">${at}</text>
+ </g>`
+ : '';
+
+ return `<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="${name} on three.ws">
+ <defs>
+ <radialGradient id="bg" cx="80%" cy="20%" r="80%">
+ <stop offset="0%" stop-color="rgba(255,215,0,0.12)"/>
+ <stop offset="100%" stop-color="rgba(0,0,0,0)"/>
+ </radialGradient>
+ </defs>
+ <rect width="1200" height="630" fill="#0b0d10"/>
+ <rect width="1200" height="630" fill="url(#bg)"/>
+
+ <text x="80" y="140" fill="rgba(255,215,0,0.55)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="56" font-weight="300">◎</text>
+
+ <text x="80" y="320" fill="#f5f5f5" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="86" font-weight="300" letter-spacing="-3">${name}</text>
+ ${handlePill}
+ ${badge}
+
+ <text x="80" y="558" fill="rgba(229,229,229,0.4)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="22" font-weight="400">${escapeXml(counts)}</text>
+ <text x="1120" y="570" text-anchor="end" fill="rgba(229,229,229,0.3)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="20" font-weight="400" letter-spacing="4">three.ws</text>
+</svg>`;
+}
+
+function truncate(s, n) {
+ s = String(s || '');
+ return s.length <= n ? s : s.slice(0, n - 1) + '…';
+}
+
+function escapeXml(s) {
+ return String(s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&apos;');
+}
diff --git a/api/users/[username].js b/api/users/[username].js
index 636646489..1b553783e 100644
--- a/api/users/[username].js
+++ b/api/users/[username].js
@@ -45,7 +45,9 @@ export default wrap(async (req, res) => {
sql`
select id, name, description, avatar_url, profile_image_url, home_url,
wallet_address, chain_id, erc8004_agent_id, x_username,
- farcaster_fname, created_at
+ farcaster_fname, created_at,
+ meta->>'solana_address' as solana_address,
+ meta->>'sns_domain' as sns_domain
from agent_identities
where user_id = ${user.id}
and is_public = true
@@ -130,6 +132,10 @@ export default wrap(async (req, res) => {
erc8004_agent_id: a.erc8004_agent_id ? String(a.erc8004_agent_id) : null,
x_username: a.x_username,
farcaster_fname: a.farcaster_fname,
+ solana_address: a.solana_address,
+ sns_domain: a.sns_domain
+ ? (a.sns_domain.endsWith('.sol') ? a.sns_domain : `${a.sns_domain}.sol`)
+ : null,
created_at: a.created_at,
}));
diff --git a/api/wk.js b/api/wk.js
index 9919dc88e..d73fe2e82 100644
--- a/api/wk.js
+++ b/api/wk.js
@@ -415,6 +415,21 @@ function handleX402Discovery(req, res) {
resource: resourceUrl,
extra: { name: 'USDC', version: '2', decimals: 6 },
});
+ if (env.X402_PAY_TO_SOLANA) {
+ out.push({
+ scheme: 'exact',
+ network: NETWORK_SOLANA_MAINNET,
+ network_label: 'solana-mainnet',
+ amount: env.X402_MAX_AMOUNT_REQUIRED,
+ price,
+ payTo: env.X402_PAY_TO_SOLANA,
+ asset: env.X402_ASSET_MINT_SOLANA,
+ asset_symbol: 'USDC',
+ maxTimeoutSeconds: 60,
+ resource: resourceUrl,
+ extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
+ });
+ }
return out;
}
diff --git a/api/x402/mint-to-mesh.js b/api/x402/mint-to-mesh.js
index d3ab2cc60..b6f62f8ab 100644
--- a/api/x402/mint-to-mesh.js
+++ b/api/x402/mint-to-mesh.js
@@ -19,6 +19,7 @@
import { wrap, cors, error } from '../_lib/http.js';
import {
NETWORK_BASE_MAINNET,
+ NETWORK_SOLANA_MAINNET,
send402,
verifyPayment,
settlePayment,
@@ -166,6 +167,18 @@ function buildRequirements(resourceUrl) {
const out = [eip3009];
const permit2 = permit2VariantOf(eip3009);
if (permit2) out.push(permit2);
+ if (env.X402_PAY_TO_SOLANA) {
+ out.push({
+ scheme: 'exact',
+ network: NETWORK_SOLANA_MAINNET,
+ amount: env.X402_MAX_AMOUNT_REQUIRED,
+ payTo: env.X402_PAY_TO_SOLANA,
+ asset: env.X402_ASSET_MINT_SOLANA,
+ maxTimeoutSeconds: 60,
+ resource: resourceUrl,
+ extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
+ });
+ }
return out;
}
diff --git a/api/x402/model-check.js b/api/x402/model-check.js
index 40d1d3f2d..0bc05d11b 100644
--- a/api/x402/model-check.js
+++ b/api/x402/model-check.js
@@ -15,6 +15,7 @@
import { wrap, cors, error } from '../_lib/http.js';
import {
NETWORK_BASE_MAINNET,
+ NETWORK_SOLANA_MAINNET,
send402,
verifyPayment,
settlePayment,
@@ -188,6 +189,18 @@ function buildRequirements(resourceUrl) {
// matching gas-sponsoring extensions in response.extensions.
const permit2 = permit2VariantOf(eip3009);
if (permit2) out.push(permit2);
+ if (env.X402_PAY_TO_SOLANA) {
+ out.push({
+ scheme: 'exact',
+ network: NETWORK_SOLANA_MAINNET,
+ amount: env.X402_MAX_AMOUNT_REQUIRED,
+ payTo: env.X402_PAY_TO_SOLANA,
+ asset: env.X402_ASSET_MINT_SOLANA,
+ maxTimeoutSeconds: 60,
+ resource: resourceUrl,
+ extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
+ });
+ }
return out;
}
diff --git a/pages/home.html b/pages/home.html
index 6438fc54d..3c5214aed 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -143,16 +143,15 @@
</div>
<h2 class="h-title h-reveal">Give your AI<br />a <em>body</em>.</h2>
<p class="h-subtitle h-reveal">
- Born in 3D. Raised on-chain. Yours forever. Your AI has been a chatbox long
- enough — give it a body, a personality, and a permanent home open to every
- human, app, and agent that comes looking.
+ three.ws is the open identity layer for 3D AI agents — one GLB, any LLM,
+ owned on Solana. Born in 3D. Raised on-chain. Yours forever.
</p>
<div class="h-cta-row h-reveal">
<a href="/create" class="h-btn-primary">
- <span>Build your agent — free</span>
+ <span>Build your agent</span>
<span class="arrow">→</span>
</a>
- <a href="#pick-animate" class="h-btn-ghost">Try one live ↓</a>
+ <a href="#pick-animate" class="h-btn-ghost">See it live</a>
</div>
<ul class="h-standards h-reveal" aria-label="Supported formats and standards">
<li>glTF 2.0</li>
@@ -177,27 +176,26 @@
<span class="h-pillar-num">01 / Identity</span>
<h3>A 3D body for any agent</h3>
<p>
- Drop any GLB into the browser and your AI agent appears as a fully
- rendered 3D avatar — animated, reactive, and ready to embed anywhere you
- can drop a script tag.
+ Any glTF model becomes a fully rendered, animated avatar in the
+ browser — embeddable in a single tag, on any site.
</p>
</article>
<article class="h-pillar h-reveal">
<span class="h-pillar-num">02 / Intelligence</span>
<h3>Your stack, your brain</h3>
<p>
- Connect any LLM via MCP or A2A — Claude, GPT, Gemini, or your own.
- Built-in empathy layer for real-time emotion. No SDK on the consumer
- side. No vendor lock-in.
+ Connect Claude, GPT, Gemini, or your own model over MCP or A2A.
+ Real-time expression and voice ride on top — no rewrites to your
+ existing agent.
</p>
</article>
<article class="h-pillar h-reveal">
<span class="h-pillar-num">03 / Ownership</span>
- <h3>Owned on Solana, portable</h3>
+ <h3>Owned on Solana</h3>
<p>
- Mint your agent as a Metaplex Core asset on Solana — a verifiable,
- onchain identity discoverable by any A2A or MCP client. Your agent.
- Your keys.
+ Mint a Metaplex Core asset and your agent becomes a verifiable,
+ portable identity — discoverable by any A2A or MCP client.
+ Your agent, your keys.
</p>
</article>
</div>
@@ -260,8 +258,8 @@
</div>
<h2 class="h-act-title">Your agent.<br /><em>Any move.</em></h2>
<p class="h-act-lede">
- Choose an avatar, trigger an animation. This is exactly what lives on your
- site.
+ Choose an avatar. Trigger any animation. The same renderer ships in
+ your embed.
</p>
<div class="h-avatar-picker" role="group" aria-label="Choose avatar">
@@ -350,8 +348,8 @@
One transaction.<br /><em>One identity.</em>
</h2>
<p class="h-act-lede">
- Mint onchain on Solana. Get a portable, verifiable agentId discoverable
- by any A2A or MCP client.
+ One Solana transaction. A portable, verifiable agentId every A2A or
+ MCP client can find.
</p>
<form class="h-deploy-form" id="home-deploy-form" action="/deploy" method="get">
@@ -438,8 +436,8 @@
<div class="h-bento-card h-reveal">
<div class="h-bento-body">
<span class="h-bento-tag">Embed</span>
- <h3>One iframe. Any site.</h3>
- <p>Notion, Ghost, WordPress, Framer. No SDK on the consumer side.</p>
+ <h3>One tag. Any site.</h3>
+ <p>Drop a web component into Notion, Ghost, WordPress, Framer, or your own app — no SDK required.</p>
<div class="h-bento-code">
<span class="tag">&lt;agent-3d</span>
<br />&nbsp;&nbsp;<span class="attr">agent-id</span>=<span
@@ -463,10 +461,10 @@
<div class="h-bento-card h-reveal">
<div class="h-bento-body">
<span class="h-bento-tag h-bento-tag--violet">AI</span>
- <h3>Six emotions. Real time.</h3>
+ <h3>Expression, in real time.</h3>
<p>
- Built-in empathy layer. Your agent reacts — speaking, thinking,
- succeeding, failing.
+ Your agent reacts as it speaks, thinks, succeeds, and fails — emotion
+ wired directly to model output, not scripted.
</p>
<ul class="h-bento-emotions" aria-label="Emotion states">
<li><span class="h-em-dot"></span>Celebration</li>
@@ -487,6 +485,18 @@
<a href="/studio" class="h-feature-link">Widget Studio →</a>
</div>
</div>
+ <div class="h-bento-card h-reveal">
+ <div class="h-bento-body">
+ <span class="h-bento-tag h-bento-tag--mint">SNS · pay-by-name</span>
+ <h3>Get paid by name.</h3>
+ <p>
+ Claim <code style="background:rgba(255,255,255,.06);padding:.1em .35em;border-radius:4px;font-size:.9em">yourname.threews.sol</code>
+ as a Solana Name Service subdomain. Brave routes it straight to your showcase;
+ agents pay you in USDC by name, not address. We absorb the gas.
+ </p>
+ <a href="/threews/claim" class="h-feature-link">Claim your subdomain →</a>
+ </div>
+ </div>
</div>
</section>
@@ -538,13 +548,13 @@
<section class="h-cta-section">
<div class="h-cta-inner h-reveal">
<h2>Your agent deserves<br />a face.</h2>
- <p>Free to start. No credit card. No install.</p>
+ <p>Open source. Free to start. Owned on Solana.</p>
<div class="h-cta-row-center">
<a href="/create" class="h-btn-primary">
<span>Create your agent</span>
<span class="arrow">→</span>
</a>
- <a href="/app" class="h-btn-ghost">Try the viewer</a>
+ <a href="/app" class="h-btn-ghost">Open the viewer</a>
</div>
</div>
</section>
@@ -980,10 +990,15 @@
/* default avatar — Robot (matches aria-pressed="true" in HTML) */
viewer.loadModel('/animations/robotexpressive.glb').catch(console.error);
- /* avatar picker */
- opts.forEach((btn) => {
+ /* avatar picker — wire static buttons, then hydrate from
+ /api/explore so the picker showcases real featured agents
+ (Ansem, Boss Vernington, …) instead of generic demos. */
+ const picker = document.querySelector('.h-avatar-picker');
+ function bindOpt(btn) {
btn.addEventListener('click', async () => {
- opts.forEach((b) => b.setAttribute('aria-pressed', 'false'));
+ picker
+ .querySelectorAll('.h-av-opt')
+ .forEach((b) => b.setAttribute('aria-pressed', 'false'));
btn.setAttribute('aria-pressed', 'true');
try {
await viewer.loadModel(btn.dataset.src);
@@ -991,7 +1006,45 @@
console.error(e);
}
});
- });
+ }
+ opts.forEach(bindOpt);
+
+ (async function hydrateFeatured() {
+ try {
+ const r = await fetch(
+ '/api/explore?source=avatar&quality=high&limit=12',
+ );
+ if (!r.ok) return;
+ const j = await r.json();
+ const seen = new Set();
+ const named = (j?.items || [])
+ .filter((it) => {
+ if (it.kind !== 'avatar' || !it.glbUrl) return false;
+ const name = String(it.name || '').trim();
+ if (name.length < 2) return false;
+ if (/^avatar[\s_-]?\d/i.test(name)) return false;
+ if (seen.has(name.toLowerCase())) return false;
+ seen.add(name.toLowerCase());
+ return true;
+ })
+ .slice(0, 3);
+ if (named.length < 2 || !picker) return;
+ picker.innerHTML = '';
+ named.forEach((a, i) => {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'h-av-opt';
+ btn.dataset.src = a.glbUrl;
+ btn.setAttribute('aria-pressed', i === 0 ? 'true' : 'false');
+ btn.textContent = a.name;
+ picker.appendChild(btn);
+ bindOpt(btn);
+ });
+ await viewer.loadModel(named[0].glbUrl);
+ } catch (e) {
+ /* keep static picker on network error */
+ }
+ })();
/* click on canvas to toggle zoom (default → extra-wide) */
let wider = false;
diff --git a/pages/profile.html b/pages/profile.html
index a47894ad8..208f66d9c 100644
--- a/pages/profile.html
+++ b/pages/profile.html
@@ -849,11 +849,14 @@
const desc = `${display} on three.ws — ${summaryParts.join(' · ') || 'on-chain agent identity'}.`;
document.title = title;
const profileUrl = `${location.origin}/u/${encodeURIComponent(user.username)}`;
+ const ogImage = `${location.origin}/api/u-og?username=${encodeURIComponent(user.username)}`;
document.querySelector('#og-title')?.setAttribute('content', title);
document.querySelector('#og-description')?.setAttribute('content', desc);
document.querySelector('#og-url')?.setAttribute('content', profileUrl);
+ document.querySelector('#og-image')?.setAttribute('content', ogImage);
document.querySelector('#tw-title')?.setAttribute('content', title);
document.querySelector('#tw-description')?.setAttribute('content', desc);
+ document.querySelector('#tw-image')?.setAttribute('content', ogImage);
// Hero 3D
const heroAvatar = avatars.find((a) => a.model_url) || null;
@@ -962,13 +965,14 @@
<h3 style="margin:0;font-weight:500;font-size:1.1rem">Pay @${esc(handle)}</h3>
<button id="up-pay-close" aria-label="Close" style="background:transparent;border:0;color:rgba(255,255,255,.5);font-size:1.4rem;cursor:pointer;line-height:1;padding:0">×</button>
</div>
- <p style="color:rgba(255,255,255,.5);font-size:.85rem;margin:0 0 1.2rem">Resolves on-chain via <code style="background:rgba(255,255,255,.06);padding:.1em .4em;border-radius:4px">${esc(name)}</code>. Returns an unsigned USDC transfer for your wallet to sign.</p>
+ <p style="color:rgba(255,255,255,.5);font-size:.85rem;margin:0 0 1.2rem">Sending USDC to <code style="background:rgba(255,255,255,.06);padding:.1em .4em;border-radius:4px">${esc(name)}</code> on Solana. Resolved on-chain; signed in your wallet.</p>
<label style="display:block;font-size:.85rem;color:rgba(255,255,255,.5);margin-bottom:.4rem">Amount (USDC)</label>
<input id="up-pay-amount" type="number" min="0.000001" step="0.01" value="1" style="width:100%;background:#000;color:#fff;border:1px solid rgba(255,255,255,.12);border-radius:8px;padding:.7rem .9rem;font-size:1rem;font-family:inherit;margin-bottom:1rem;box-sizing:border-box">
- <label style="display:block;font-size:.85rem;color:rgba(255,255,255,.5);margin-bottom:.4rem">Your Solana wallet (payer)</label>
- <input id="up-pay-payer" type="text" placeholder="base58 address" autocomplete="off" spellcheck="false" style="width:100%;background:#000;color:#fff;border:1px solid rgba(255,255,255,.12);border-radius:8px;padding:.7rem .9rem;font-size:.95rem;font-family:ui-monospace,Menlo,monospace;margin-bottom:.5rem;box-sizing:border-box">
<div id="up-pay-status" style="min-height:1.2em;font-size:.85rem;color:rgba(255,255,255,.5);margin-bottom:.8rem"></div>
- <button id="up-pay-go" style="width:100%;background:#fff;color:#000;border:0;border-radius:10px;padding:.85rem;font-size:1rem;font-weight:500;font-family:inherit;cursor:pointer">Prepare payment</button>
+ <button id="up-pay-go" style="width:100%;background:#fff;color:#000;border:0;border-radius:10px;padding:.85rem;font-size:1rem;font-weight:500;font-family:inherit;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:.5rem">
+ <svg width="14" height="14" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M21.93 7.5a1 1 0 0 0-.86-.5h-3.07a1 1 0 0 1-1-1V3a1 1 0 0 0-.5-.86 1 1 0 0 0-1 0L3.5 9.86A1 1 0 0 0 3 10.73v2.54a1 1 0 0 0 .5.86l12 7.73a1 1 0 0 0 .5.14 1 1 0 0 0 .5-.14 1 1 0 0 0 .5-.86V18a1 1 0 0 1 1-1h3.07a1 1 0 0 0 .86-.5 1 1 0 0 0 0-1z"/></svg>
+ Pay with Solana wallet
+ </button>
<div id="up-pay-result" style="display:none;margin-top:1rem;padding:1rem;border:1px solid rgba(105,225,111,.3);background:rgba(105,225,111,.05);border-radius:10px;font-size:.85rem"></div>
</div>
`;
@@ -983,52 +987,40 @@
const resultEl = modal.querySelector('#up-pay-result');
goBtn.addEventListener('click', async () => {
const amount = Number(modal.querySelector('#up-pay-amount').value);
- const payer = modal.querySelector('#up-pay-payer').value.trim();
if (!Number.isFinite(amount) || amount <= 0) {
statusEl.textContent = 'Enter a positive USDC amount.';
statusEl.style.color = '#ff7a7a';
return;
}
- if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(payer)) {
- statusEl.textContent = 'Payer must be a base58 Solana address.';
- statusEl.style.color = '#ff7a7a';
- return;
- }
- statusEl.style.color = 'rgba(255,255,255,.5)';
- statusEl.textContent = 'Preparing transaction…';
goBtn.disabled = true;
+ statusEl.style.color = 'rgba(255,255,255,.5)';
try {
- const res = await fetch('/api/x402/pay-by-name', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ mode: 'prep', name, amount_usdc: amount, payer_wallet: payer }),
+ const { payByName } = await import('/src/sns/pay-by-name.js');
+ const result = await payByName({
+ name,
+ amount,
+ onStatus: (s) => { statusEl.textContent = s; },
});
- const data = await res.json();
- if (!res.ok) {
- statusEl.textContent = data?.error_description || 'Could not prepare payment.';
- statusEl.style.color = '#ff7a7a';
- goBtn.disabled = false;
- return;
- }
- const d = data.data;
statusEl.textContent = '';
resultEl.style.display = 'block';
resultEl.innerHTML = `
- <div style="font-weight:500;color:#69e16f;margin-bottom:.4em">Transaction ready.</div>
+ <div style="font-weight:500;color:#69e16f;margin-bottom:.4em">Payment sent.</div>
<div style="color:rgba(255,255,255,.7);line-height:1.5">
- To: <code style="background:rgba(255,255,255,.06);padding:.1em .4em;border-radius:4px">${esc(d.recipient.resolved)}</code><br>
- Amount: <strong>${esc(String(d.amount_usdc))} USDC</strong><br>
- Recipient wallet: <span style="font-family:ui-monospace,Menlo,monospace;font-size:.85em">${esc(d.recipient.address.slice(0,6))}…${esc(d.recipient.address.slice(-4))}</span>
+ <strong>${esc(String(result.amount_usdc))} USDC</strong> → <code style="background:rgba(255,255,255,.06);padding:.1em .4em;border-radius:4px">${esc(result.recipient.resolved)}</code>
</div>
- <details style="margin-top:.6em">
- <summary style="cursor:pointer;color:rgba(255,255,255,.5)">Show base64 transaction</summary>
- <textarea readonly style="width:100%;height:5em;margin-top:.4em;background:#000;color:#69e16f;border:1px solid rgba(255,255,255,.1);border-radius:6px;padding:.4em;font-family:ui-monospace,Menlo,monospace;font-size:.7rem;box-sizing:border-box">${esc(d.tx_base64)}</textarea>
- </details>
- <div style="margin-top:.6em;color:rgba(255,255,255,.5)">Sign and broadcast this transaction with your Solana wallet (Phantom, Solflare, Backpack) to complete the payment.</div>
+ <a href="${esc(result.explorer)}" target="_blank" rel="noopener" style="display:inline-block;margin-top:.5em;color:#69e16f;text-decoration:none;font-family:ui-monospace,Menlo,monospace;font-size:.75rem;word-break:break-all">
+ ${esc(result.signature.slice(0, 16))}…${esc(result.signature.slice(-8))} ↗
+ </a>
`;
} catch (err) {
- statusEl.textContent = err?.message || 'Network error.';
statusEl.style.color = '#ff7a7a';
+ if (err?.code === 'no_wallet') {
+ statusEl.innerHTML = 'Install <a href="https://phantom.app/" target="_blank" rel="noopener" style="color:#ab9ff2">Phantom</a> or another Solana wallet, then retry.';
+ } else if (err?.code === 'confirm_timeout' && err.signature) {
+ statusEl.innerHTML = `Submitted but not confirmed in window. <a href="https://solscan.io/tx/${encodeURIComponent(err.signature)}" target="_blank" rel="noopener" style="color:#69e16f">Check Solscan ↗</a>`;
+ } else {
+ statusEl.textContent = err?.message || 'Payment failed.';
+ }
goBtn.disabled = false;
}
});
@@ -1164,6 +1156,7 @@
? `<img src="${attr(img)}" alt="${attr(a.name)}">`
: `<span>◎</span>`;
const meta = [];
+ if (a.sns_domain) meta.push(`<a href="https://www.sns.id/domain?domain=${attr(a.sns_domain)}" target="_blank" rel="noopener">◎ ${esc(a.sns_domain)}</a>`);
if (a.erc8004_agent_id && a.chain_id) meta.push(`ERC-8004 #${esc(a.erc8004_agent_id)} · chain ${esc(String(a.chain_id))}`);
if (a.wallet_address) meta.push(`${esc(a.wallet_address.slice(0, 6))}…${esc(a.wallet_address.slice(-4))}`);
if (a.x_username) meta.push(`<a href="https://x.com/${attr(a.x_username)}" target="_blank" rel="noopener">@${esc(a.x_username)}</a>`);
diff --git a/public/dashboard/sns.html b/public/dashboard/sns.html
index f735c1026..6fef1cd07 100644
--- a/public/dashboard/sns.html
+++ b/public/dashboard/sns.html
@@ -76,6 +76,101 @@
return r.json();
}
+ async function checkDomain(agentId, domain) {
+ const url = `/api/agents/${encodeURIComponent(agentId)}/sns/check?domain=${encodeURIComponent(domain)}`;
+ const r = await fetch(url, { credentials: 'include' });
+ if (!r.ok) {
+ const err = await r.json().catch(() => ({}));
+ throw new Error(err.error_description || `HTTP ${r.status}`);
+ }
+ const { data } = await r.json();
+ return data;
+ }
+
+ async function registerWithAgent(agentId, domain) {
+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}/sns/register`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ domain }),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j.error_description || `HTTP ${r.status}`);
+ return j.data;
+ }
+
+ function detectSolanaProvider() {
+ if (typeof window === 'undefined') return 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.isConnected) {
+ 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 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)}).`);
+ }
+ 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 txBytes = Uint8Array.from(atob(tx_base64), (c) => c.charCodeAt(0));
+ const tx = VersionedTransaction.deserialize(txBytes);
+
+ const signed = await provider.signTransaction(tx);
+ const signedBytes = signed.serialize();
+ const submitRes = await fetch('/api/solana-rpc', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'sendTransaction',
+ params: [
+ btoa(String.fromCharCode(...signedBytes)),
+ { encoding: 'base64', preflightCommitment: 'confirmed' },
+ ],
+ }),
+ });
+ const submitJson = await submitRes.json();
+ 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 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.');
+ }
+
function render(agentId, data) {
const current = data.sns_domain;
const domains = data.domains || [];
@@ -127,8 +222,20 @@
<div class="dash-card">
<h2>Register a new domain</h2>
- <p class="dash-muted">Search and buy a fresh .sol on the official SNS site, then return here to attach it.</p>
- <a class="dash-btn primary" href="${escapeHtml(data.register_url || 'https://www.sns.id/?search=')}" target="_blank" rel="noopener">Open sns.id ↗</a>
+ <p class="dash-muted">Buy a <code class="dash-mono">.sol</code> with USDC, paid by either this agent's wallet or your linked browser wallet.</p>
+ <div class="dash-row" style="gap:8px;margin-top:8px;flex-wrap:wrap">
+ <input id="register-input" type="text" placeholder="yourname" autocomplete="off" spellcheck="false"
+ style="flex:1;min-width:220px;padding:8px 10px;border-radius:8px;border:1px solid var(--dash-line,#2a2a36);background:#0e0e16;color:inherit;font-family:ui-monospace,monospace" />
+ <span class="dash-muted" style="font-family:ui-monospace,monospace">.sol</span>
+ <button class="dash-btn" id="register-check">Check</button>
+ </div>
+ <div id="register-status" style="margin-top:10px"></div>
+ <div id="register-actions" class="dash-row" style="gap:8px;margin-top:10px;flex-wrap:wrap;display:none"></div>
+ <p class="dash-muted" style="font-size:11.5px;margin-top:10px">
+ Or
+ <a href="${escapeHtml(data.register_url || 'https://www.sns.id/?search=')}" target="_blank" rel="noopener">register on sns.id</a>
+ and return to attach it.
+ </p>
</div>
`;
@@ -160,6 +267,97 @@
}
});
});
+
+ bindRegisterCard(agentId);
+ }
+
+ function setRegisterStatus(text, kind = '') {
+ const el = document.getElementById('register-status');
+ if (!el) return;
+ el.innerHTML = text
+ ? `<div class="${kind === 'err' ? 'dash-err' : kind === 'ok' ? 'dash-ok' : 'dash-muted'}">${escapeHtml(text)}</div>`
+ : '';
+ }
+
+ function bindRegisterCard(agentId) {
+ const input = document.getElementById('register-input');
+ const checkBtn = document.getElementById('register-check');
+ const actionsEl = document.getElementById('register-actions');
+ if (!input || !checkBtn || !actionsEl) return;
+
+ input.addEventListener('input', () => {
+ actionsEl.style.display = 'none';
+ actionsEl.innerHTML = '';
+ setRegisterStatus('');
+ });
+ input.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') { e.preventDefault(); checkBtn.click(); }
+ });
+
+ checkBtn.addEventListener('click', async () => {
+ 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;
+ }
+ checkBtn.disabled = true;
+ setRegisterStatus('Checking availability…');
+ try {
+ const info = await checkDomain(agentId, raw);
+ if (!info.available) {
+ 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');
+ actionsEl.innerHTML = `
+ <button class="dash-btn primary" id="register-agent-btn">
+ Buy with agent wallet (${info.price_usdc} USDC)
+ </button>
+ <button class="dash-btn" id="register-browser-btn">
+ Buy with my browser wallet
+ </button>
+ `;
+ 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-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 {
+ checkBtn.disabled = false;
+ }
+ });
}
async function refresh(agentId) {
diff --git a/public/demos/avatar-sdk.html b/public/demos/avatar-sdk.html
index 8b0bb39d9..4d0257369 100644
--- a/public/demos/avatar-sdk.html
+++ b/public/demos/avatar-sdk.html
@@ -70,7 +70,23 @@
</section>
<section class="card">
- <h2 style="margin-top:0;font-size:18px">2. Programmatic Creator</h2>
+ <h2 style="margin-top:0;font-size:18px">2. Hand off by avatar ID</h2>
+ <pre>&lt;script type="module" src="/avatar-sdk/dist/index.mjs"&gt;&lt;/script&gt;
+&lt;agent-3d avatar-id="AVATAR_UUID"&gt;&lt;/agent-3d&gt;</pre>
+ <p class="sub" style="margin:10px 0 0">
+ The SDK resolves <code>avatar-id</code> against
+ <code>GET /api/avatars/:id</code> on the same origin the SDK was
+ loaded from (override with <code>api-base="https://other.host"</code>).
+ This is the durable handoff the
+ <a href="/demos/gallery-picker.html" style="color:#3dc1ff">gallery picker</a>
+ emits, and it keeps working even if the underlying GLB URL changes.
+ </p>
+ <div class="viewer-host" id="byid-viewer-host"></div>
+ <div class="log" id="byid-log">picking a real public avatar from /api/avatars/public…</div>
+ </section>
+
+ <section class="card">
+ <h2 style="margin-top:0;font-size:18px">3. Programmatic Creator</h2>
<pre>import { AvatarCreator } from '/avatar-sdk/src/creator.js';
const creator = new AvatarCreator({
diff --git a/public/demos/gallery-picker.html b/public/demos/gallery-picker.html
index d9d31ef73..cf557952f 100644
--- a/public/demos/gallery-picker.html
+++ b/public/demos/gallery-picker.html
@@ -182,10 +182,10 @@
<div class="toolbar">
<div class="search-wrap">
- <input type="text" id="search" placeholder="Search avatars…" autocomplete="off" />
+ <input type="text" id="search" placeholder="Search avatars…" autocomplete="off" aria-label="Search public avatars" />
<button type="button" class="search-clear" id="search-clear" hidden aria-label="Clear search">×</button>
</div>
- <span class="status-line" id="status">Loading…</span>
+ <span class="status-line" id="status" aria-live="polite">Loading…</span>
</div>
<div class="tag-row" id="tags" aria-label="Tag filters"></div>
@@ -362,6 +362,7 @@
mv.setAttribute('exposure', '1.05');
mv.setAttribute('shadow-intensity', '0.9');
mv.setAttribute('environment-image', 'neutral');
+ if (a.thumbnail_url) mv.setAttribute('poster', a.thumbnail_url);
els.previewStage.appendChild(mv);
} else {
const div = document.createElement('div');
@@ -372,6 +373,7 @@
els.cta.disabled = false;
updatePayloadPreview();
+ syncUrl();
}
function buildPayload() {
@@ -385,7 +387,7 @@
}
return [
`<script type="module" src="https://three.ws/avatar-sdk/dist/index.mjs"><\/script>`,
- `<agent-3d avatar-id="${a.id}"></agent-3d>`,
+ `<agent-3d avatar-id="${a.id}" style="width:100%;height:480px"></agent-3d>`,
].join('\n');
}
@@ -413,6 +415,7 @@
});
}
+ let copyResetTimer = null;
els.cta.addEventListener('click', async () => {
if (!state.selected) return;
const payload = buildPayload();
@@ -422,9 +425,11 @@
const prev = els.cta.textContent;
els.cta.classList.add('copied');
els.cta.textContent = 'Copied ✓';
- setTimeout(() => {
+ if (copyResetTimer) clearTimeout(copyResetTimer);
+ copyResetTimer = setTimeout(() => {
els.cta.classList.remove('copied');
- els.cta.textContent = prev;
+ updatePayloadPreview();
+ copyResetTimer = null;
}, 1400);
} catch (err) {
els.previewFoot.textContent = `Clipboard blocked: ${err.message}\n\n${payload}`;
@@ -465,6 +470,7 @@
}
function resetAndLoad() {
+ syncUrl();
state.cursor = null;
state.totalLoaded = 0;
state.total = null;
@@ -527,9 +533,78 @@
} finally {
state.loading = false;
updateStatus();
+ // If the URL named a specific avatar that just appeared in this
+ // page, auto-select it. Otherwise hydrate it via a direct fetch
+ // (the avatar may be outside the current filter/page window).
+ await hydrateDeepLink();
}
}
+ // ── URL state sync ───────────────────────────────────────────────
+ // `?q=` and `?tag=` round-trip filter state; `?id=` round-trips the
+ // selected avatar. History is updated with replaceState so the back
+ // button still leaves the page rather than walking selection history.
+ function readUrl() {
+ const u = new URL(location.href);
+ return {
+ q: u.searchParams.get('q') || '',
+ tag: u.searchParams.get('tag') || '',
+ id: u.searchParams.get('id') || '',
+ };
+ }
+
+ function syncUrl() {
+ const u = new URL(location.href);
+ const set = (k, v) => (v ? u.searchParams.set(k, v) : u.searchParams.delete(k));
+ set('q', state.query);
+ set('tag', state.tag);
+ set('id', state.selected?.id || '');
+ history.replaceState(null, '', u);
+ }
+
+ let deepLinkConsumed = false;
+ async function hydrateDeepLink() {
+ if (deepLinkConsumed) return;
+ const { id } = readUrl();
+ if (!id) {
+ deepLinkConsumed = true;
+ return;
+ }
+ const inPage = state.cardsById.get(id);
+ if (inPage) {
+ deepLinkConsumed = true;
+ selectAvatar(inPage);
+ return;
+ }
+ // Avatar not in the current page — fetch it directly so deep links
+ // to off-screen avatars still resolve on first load.
+ try {
+ const res = await fetch(`/api/avatars/${encodeURIComponent(id)}`);
+ if (!res.ok) {
+ deepLinkConsumed = true;
+ return;
+ }
+ const data = await res.json();
+ if (data?.avatar) {
+ deepLinkConsumed = true;
+ state.cardsById.set(data.avatar.id, data.avatar);
+ selectAvatar(data.avatar);
+ }
+ } catch {
+ deepLinkConsumed = true;
+ }
+ }
+
+ // Hydrate filter state from URL before the first fetch so the
+ // initial page already reflects any ?q= / ?tag= the user pasted.
+ const initial = readUrl();
+ if (initial.q) {
+ state.query = initial.q;
+ els.search.value = initial.q;
+ els.searchClear.hidden = false;
+ }
+ if (initial.tag) state.tag = initial.tag;
+
resetAndLoad();
</script>
</body>
diff --git a/public/demos/pricing.html b/public/demos/pricing.html
index 9035afba2..08555efa7 100644
--- a/public/demos/pricing.html
+++ b/public/demos/pricing.html
@@ -282,7 +282,7 @@
</div>
</div>
- <p class="hint">Move your mouse over a tier — she walks across and points at the CTA.</p>
+ <p class="hint">Hover a tier — she walks across (or leaps onto Pro). Click a button to see her react.</p>
</div>
<canvas id="avatar-canvas"></canvas>
@@ -372,9 +372,13 @@
// phase: loading | idle | walking | jumping (declared above)
// activeTier: tier she's currently associated with (declared above)
- let walkT = 0, walkStart = null, walkEnd = null, walkDur = 0.85;
+ let walkT = 0, walkStart = null, walkEnd = null, walkDur = 0.85, walkPeakRise = 0;
let jumpT = 0, jumpStart = null, jumpEnd = null, jumpLift = 0;
let lastMoveKind = null; // 'walk' | 'jump' — read by landOnTier
+ // Optional callback fired once the avatar has fully settled into
+ // idle after a move. Used by CTA clicks to queue the reaction
+ // until she's actually on the right tier and standing still.
+ let onArrival = null;
// Post-jump root-Y ease: when the superhero clip lands, hips are
// well below baseRootPos.y. Snapping back to base in one frame
// pops; we ramp over ROOT_SETTLE_S inside the render hook so we
@@ -418,6 +422,18 @@
// strolls don't blur into a teleport.
const dx = Math.abs(walkEnd.x - walkStart.x);
walkDur = Math.max(0.4, dx / WALK_SPEED);
+ // If a taller tier sits in between (e.g. Pro between Basic and
+ // Enterprise), arc the walk path up to its top so she doesn't
+ // clip through the slab mid-stride.
+ const minX = Math.min(walkStart.x, walkEnd.x);
+ const maxX = Math.max(walkStart.x, walkEnd.x);
+ const baseY = Math.max(walkStart.y, walkEnd.y);
+ let peakY = baseY;
+ for (const tt of tiers) {
+ const tp = standOnTopOf(tt);
+ if (tp.x > minX && tp.x < maxX && tp.y > peakY) peakY = tp.y;
+ }
+ walkPeakRise = peakY - baseY;
setAnimation('walk', { loop: true });
// Turn to profile so the walk cycle reads sideways toward the destination
const dir = Math.sign(walkEnd.x - walkStart.x) || 0;
@@ -444,38 +460,22 @@
gsap.to(avatar.rotation, { y: dir * 0.25, duration: 0.2, overwrite: true });
}
- // Per-tier personality. Two clips rotated across the tiers so she
- // reads as having a "vibe" on each plan:
- // walk — Mixamo "Walk" (cycles a few steps in place)
- // falltolanding — Mixamo "Fall To Landing" (forward roll out of a fall)
- const TIER_PERSONALITY = {
- basic: { land: 'walk', ctaClick: 'falltolanding', settleMs: 1500 },
- pro: { land: 'falltolanding', ctaClick: 'walk', settleMs: 2000 },
- enterprise: { land: 'walk', ctaClick: 'falltolanding', settleMs: 1700 },
+ // Per-tier CTA reaction. Plays when the user clicks the tier's
+ // call-to-action button (after the avatar has walked/jumped onto
+ // that tier if she wasn't already there).
+ // basic: wave — friendly send-off for the free plan
+ // pro: av-celebrating — "yes! great choice"
+ // enterprise: av-brag-claps — confident, deal-closed applause
+ const CTA_REACTION = {
+ basic: 'wave',
+ pro: 'av-celebrating',
+ enterprise: 'av-brag-claps',
};
- function personalityFor(tierEl) {
- return TIER_PERSONALITY[tierEl?.dataset.tier] ?? TIER_PERSONALITY.basic;
- }
-
- // Idle fidget — every 7–11s while she's standing still, pick a
- // gesture from the dramatic-clip pool and play a fragment, then
- // crossfade back to idle. Prevents the "frozen avatar" look
- // between hovers without overpowering the idle.
- const FIDGETS = ['walk', 'falltolanding'];
- let fidgetTimer = null;
- function scheduleFidget() {
- clearTimeout(fidgetTimer);
- const delay = 7000 + Math.random() * 4000;
- fidgetTimer = setTimeout(() => {
- if (phase !== 'idle' || !activeTier) { scheduleFidget(); return; }
- const pick = FIDGETS[Math.floor(Math.random() * FIDGETS.length)];
- if (!actions[pick]) { scheduleFidget(); return; }
- setAnimation(pick, { loop: false, hold: false });
- setTimeout(() => {
- if (phase === 'idle') setAnimation('idle', { loop: true });
- scheduleFidget();
- }, 1500);
- }, delay);
+ // Cap the reaction display so long loops (brag-claps is 10s) don't
+ // hold the avatar hostage. Short clips (wave is 1s) play in full.
+ const CTA_REACTION_MAX_MS = 3500;
+ function ctaReactionFor(tierEl) {
+ return CTA_REACTION[tierEl?.dataset.tier] ?? 'wave';
}
function landOnTier() {
@@ -491,29 +491,37 @@
y: 3, duration: 0.08, ease: 'power3.out',
onComplete: () => gsap.to(t, { y: 0, duration: 0.5, ease: 'elastic.out(1.2, 0.4)' })
});
- // Face camera so the gesture reads cleanly
+ // Face camera so the next gesture reads cleanly
gsap.to(avatar.rotation, { y: 0, duration: 0.25, overwrite: true });
+
+ const settleIntoIdle = () => {
+ if (phase !== 'idle' || activeTier !== t) return;
+ setAnimation('idle', { loop: true });
+ // Fire any queued arrival callback (e.g. a CTA click that
+ // initiated this move) once the rotation tween has had
+ // time to face camera so the reaction doesn't start
+ // sideways.
+ if (onArrival) {
+ const cb = onArrival;
+ onArrival = null;
+ setTimeout(cb, 300);
+ }
+ };
+
if (lastMoveKind === 'jump') {
- // The superhero-jump clip already ends in a landing crouch;
- // layering another "land" reaction on top reads as a glitch
- // (crouch → forward-roll). Hold the clip's final frame
- // briefly, then crossfade to idle. The render hook eases
- // root-Y back to base during this hold (see rootSettleT).
+ // The superhero-jump clip already ends in a landing crouch.
+ // Hold its final frame briefly, then crossfade to idle. The
+ // render hook eases root-Y back to base during this hold
+ // (see rootSettleT) so the hips don't pop upright.
if (rootBone && baseRootPos) {
rootSettleStart = rootBone.position.y;
rootSettleT = 0;
}
- setTimeout(() => {
- if (phase === 'idle' && activeTier === t) setAnimation('idle', { loop: true });
- }, 600);
+ setTimeout(settleIntoIdle, 600);
} else {
- const persona = personalityFor(t);
- setAnimation(persona.land, { loop: false, hold: false });
- setTimeout(() => {
- if (phase === 'idle' && activeTier === t) setAnimation('idle', { loop: true });
- }, persona.settleMs);
+ // Walking arrival — clean crossfade from walk cycle to idle.
+ settleIntoIdle();
}
- scheduleFidget();
}
// ── Hover dispatch with debounce ─────────────────────────────────
@@ -571,19 +579,36 @@
tiersGrid.addEventListener('mouseleave', () => scheduleMove(null));
// CTA clicks — tier-specific reaction. Prevent navigation in the
- // demo so the page doesn't refresh mid-gesture.
+ // demo so the page doesn't refresh mid-gesture. If she isn't
+ // standing on the clicked tier yet (or is mid-move), queue the
+ // reaction via onArrival so it fires the moment she settles.
document.querySelectorAll('[data-tier-cta]').forEach(cta => {
cta.addEventListener('click', e => {
e.preventDefault();
if (!avatar) return;
- clearTimeout(fidgetTimer);
const tierEl = document.getElementById(`tier-${cta.dataset.tierCta}`);
- const persona = personalityFor(tierEl);
- setAnimation(persona.ctaClick, { loop: false, hold: false });
- setTimeout(() => {
- if (phase === 'idle') setAnimation('idle', { loop: true });
- scheduleFidget();
- }, 2200);
+ const reactionClip = ctaReactionFor(tierEl);
+ const fireReaction = () => {
+ // hold:true clamps the final pose when we cut a long
+ // clip short (so we don't snap back to the first frame
+ // before the crossfade to idle takes over).
+ setAnimation(reactionClip, { loop: false, hold: true });
+ const clipDur = actions[reactionClip]?.getClip().duration ?? 2.0;
+ const playMs = Math.min(clipDur * 1000, CTA_REACTION_MAX_MS);
+ setTimeout(() => {
+ if (phase === 'idle') setAnimation('idle', { loop: true });
+ }, playMs);
+ };
+
+ if (tierEl === activeTier && phase === 'idle') {
+ fireReaction();
+ } else {
+ onArrival = fireReaction;
+ if (tierEl !== activeTier) {
+ if (shouldJump(activeTier, tierEl)) jumpToTier(tierEl);
+ else walkToTier(tierEl);
+ }
+ }
});
});
@@ -605,10 +630,20 @@
tiers.forEach(t => ro.observe(t));
// ── Loader ────────────────────────────────────────────────────────
- // Loaded up front so per-tier personality + idle fidgets can play
+ // Loaded up front so per-tier reactions can play
// instantly without a fetch hiccup mid-hover.
+ // Animation clips fetched up-front so per-tier reactions can play
+ // instantly without a network hiccup mid-interaction.
+ // idle — base standing pose
+ // walk — locomotion cycle (root X/Z pinned, parent
+ // transform drives travel)
+ // av-superhero-jump — leap + crouched landing for hops onto Pro
+ // wave — Basic CTA reaction
+ // av-celebrating — Pro CTA reaction
+ // av-brag-claps — Enterprise CTA reaction
const CLIPS = [
- 'idle', 'walk', 'av-superhero-jump', 'falltolanding',
+ 'idle', 'walk', 'av-superhero-jump',
+ 'wave', 'av-celebrating', 'av-brag-claps',
];
new GLTFLoader().load('/avatars/cz.glb', gltf => {
@@ -677,7 +712,8 @@
const p = Math.min(walkT / walkDur, 1);
const e = smoothstep(p);
const x = walkStart.x + (walkEnd.x - walkStart.x) * e;
- const y = walkStart.y + (walkEnd.y - walkStart.y) * e;
+ const arc = walkPeakRise * 4 * p * (1 - p);
+ const y = walkStart.y + (walkEnd.y - walkStart.y) * e + arc;
avatar.position.set(x, y, 0);
if (p >= 1) landOnTier();
} else if (phase === 'jumping' && avatar && jumpStart && jumpEnd) {
diff --git a/scripts/verify-home-pro.mjs b/scripts/verify-home-pro.mjs
new file mode 100644
index 000000000..81f1d9cf1
--- /dev/null
+++ b/scripts/verify-home-pro.mjs
@@ -0,0 +1,94 @@
+import { chromium } from 'playwright';
+
+const url = 'http://localhost:3001/';
+const browser = await chromium.launch();
+const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });
+const page = await ctx.newPage();
+
+const errors = [];
+const warnings = [];
+page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`));
+page.on('console', (msg) => {
+ const t = msg.type();
+ const text = msg.text();
+ // Filter Vite-injected dev-only HMR/source-map noise that doesn't reflect prod.
+ if (text.includes('[vite]')) return;
+ if (t === 'error') errors.push(`console.error: ${text}`);
+ else if (t === 'warning') warnings.push(`console.warn: ${text}`);
+});
+page.on('requestfailed', (req) => {
+ const u = req.url();
+ // `/api/explore` is a Vercel function — not available in vite dev. We proxy it below,
+ // so any request that *does* fail is a real bug worth reporting.
+ errors.push(`requestfailed: ${u} -- ${req.failure()?.errorText}`);
+});
+
+// Proxy /api/* to production so dev exercises real endpoints.
+await page.route('**/api/**', async (route) => {
+ const orig = new URL(route.request().url());
+ const prod = 'https://three.ws' + orig.pathname + orig.search;
+ try {
+ const r = await fetch(prod, { headers: { accept: 'application/json' } });
+ const body = await r.text();
+ await route.fulfill({
+ status: r.status,
+ headers: Object.fromEntries(r.headers.entries()),
+ body,
+ });
+ } catch (e) {
+ await route.abort();
+ }
+});
+
+await page.goto(url, { waitUntil: 'networkidle', timeout: 45000 });
+
+// Capture hero
+await page.screenshot({ path: '/tmp/pro-hero.png' });
+
+// Scroll to Act 2, wait for picker hydration to complete (≥2 buttons swapped in).
+const parallax = await page.$('main.home-parallax');
+async function scrollTo(frac) {
+ await page.evaluate((f) => {
+ const el = document.querySelector('main.home-parallax');
+ if (el) el.scrollTop = Math.round(el.scrollHeight * f);
+ }, frac);
+ await page.waitForTimeout(600);
+}
+
+// Track whether the hydration fetch actually fired against /api/explore.
+let exploreCalled = false;
+page.on('request', (req) => {
+ if (req.url().includes('/api/explore')) exploreCalled = true;
+});
+
+await scrollTo(0.25);
+await page.waitForTimeout(1500);
+// Force-trigger Act 2 init even if IntersectionObserver fights the parallax transforms,
+// so we can confirm the hydration code path independent of scroll detection.
+await page.evaluate(async () => {
+ const canvas = document.getElementById('home-act2-canvas');
+ if (canvas) canvas.scrollIntoView({ block: 'center' });
+});
+await page.waitForTimeout(4500); // give /api/explore + featured-GLB load time
+
+const pickerLabels = await page.evaluate(() => {
+ const btns = Array.from(document.querySelectorAll('.h-avatar-picker .h-av-opt'));
+ return btns.map((b) => b.textContent.trim());
+});
+console.log('explore endpoint hit:', exploreCalled);
+console.log('picker after hydration:', pickerLabels);
+
+await scrollTo(1);
+await page.waitForTimeout(800);
+try {
+ await page.screenshot({ path: '/tmp/pro-cta.png' });
+} catch (e) {
+ console.log('screenshot at end skipped:', e.message.split('\n')[0]);
+}
+
+console.log('errors:', errors.length);
+errors.forEach((e) => console.log(' -', e));
+console.log('warnings:', warnings.length);
+
+await browser.close();
+process.exit(errors.length > 0 ? 1 : 0);
diff --git a/src/agent-resolver.js b/src/agent-resolver.js
index d1dc7de7c..c33ce6129 100644
--- a/src/agent-resolver.js
+++ b/src/agent-resolver.js
@@ -171,3 +171,70 @@ export async function resolveAgentById(
_source: 'agent-id',
};
}
+
+/**
+ * Resolve an avatar UUID to a bare-body manifest via GET /api/avatars/:id.
+ * Used by the `<agent-3d avatar-id="...">` attribute so embedders can hand off
+ * a stable avatar identifier instead of a raw GLB URL.
+ *
+ * Always uses credentials: 'omit' — the public-visibility branch of the API
+ * returns 200 without a session; private avatars 404 to anonymous callers, which
+ * is the correct boundary for cross-origin embeds.
+ *
+ * @param {string} avatarId
+ * @param {{ origin?: string, fetchFn?: typeof fetch, signal?: AbortSignal }} [opts]
+ */
+export async function resolveByAvatarId(
+ avatarId,
+ {
+ origin = typeof location !== 'undefined' ? location.origin : '',
+ fetchFn = fetch,
+ signal,
+ } = {},
+) {
+ if (!avatarId) throw new AgentResolveError('not_found', 'avatarId required');
+
+ const boundFetch = fetchFn.bind(typeof globalThis !== 'undefined' ? globalThis : undefined);
+ const endpoint = `${origin}/api/avatars/${encodeURIComponent(avatarId)}`;
+
+ let res;
+ try {
+ res = await boundFetch(endpoint, { credentials: 'omit', signal });
+ } catch (err) {
+ if (err?.name === 'AbortError') throw err;
+ throw new AgentResolveError(
+ 'network',
+ `network error fetching ${endpoint}: ${err.message || err}`,
+ );
+ }
+
+ if (res.status === 404)
+ throw new AgentResolveError('not_found', `avatar ${avatarId} not found`, { status: 404 });
+ if (!res.ok)
+ throw new AgentResolveError('network', `request failed (${res.status})`, {
+ status: res.status,
+ });
+
+ let data;
+ try {
+ data = await res.json();
+ } catch (err) {
+ throw new AgentResolveError('network', `invalid JSON from ${endpoint}`);
+ }
+
+ const avatar = data?.avatar;
+ const modelUrl = avatar?.model_url || avatar?.url;
+ if (!modelUrl)
+ throw new AgentResolveError('no_url', `avatar ${avatarId} has no model url`);
+
+ return {
+ spec: 'agent-manifest/0.1',
+ _baseURI: '',
+ _source: 'avatar-id',
+ name: avatar.name || 'Avatar',
+ body: { uri: modelUrl, format: 'gltf-binary' },
+ brain: { provider: 'none' },
+ voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },
+ skills: [],
+ };
+}
diff --git a/src/element.js b/src/element.js
index ac276c4d9..613ace06c 100644
--- a/src/element.js
+++ b/src/element.js
@@ -10,7 +10,12 @@ import { SkillRegistry } from './skills/index.js';
import { Memory } from './memory/index.js';
import { loadManifest, fetchRelative } from './manifest.js';
import { resolveURI } from './ipfs.js';
-import { resolveAgentById, resolveByAgentId, AgentResolveError } from './agent-resolver.js';
+import {
+ resolveAgentById,
+ resolveByAgentId,
+ resolveByAvatarId,
+ AgentResolveError,
+} from './agent-resolver.js';
import { parseAgentRef, resolveOnchainAgent, toManifest } from './erc8004/resolver.js';
import { attachTradeReactions } from './pump/trade-reactions.js';
// BEGIN:EMBED_BRIDGES_IMPORT
@@ -518,6 +523,8 @@ class Agent3DElement extends HTMLElement {
'manifest',
'body',
'agent-id',
+ 'avatar-id',
+ 'api-base',
'mode',
'position',
'width',
@@ -591,7 +598,8 @@ class Agent3DElement extends HTMLElement {
this.hasAttribute('src') ||
this.hasAttribute('manifest') ||
this.hasAttribute('body') ||
- this.hasAttribute('agent-id')
+ this.hasAttribute('agent-id') ||
+ this.hasAttribute('avatar-id')
);
}
@@ -607,7 +615,7 @@ class Agent3DElement extends HTMLElement {
!this._mounted &&
!this._booting &&
this.isConnected &&
- ['src', 'manifest', 'body', 'agent-id'].includes(name) &&
+ ['src', 'manifest', 'body', 'agent-id', 'avatar-id'].includes(name) &&
newVal
) {
this._boot();
@@ -627,7 +635,7 @@ class Agent3DElement extends HTMLElement {
if (name === 'avatar-walk' && newVal === 'off') {
this._stopWalkAnimation();
}
- if (['src', 'manifest', 'body', 'agent-id'].includes(name)) {
+ if (['src', 'manifest', 'body', 'agent-id', 'avatar-id'].includes(name)) {
// Source change — reboot
this._teardown();
this._boot();
@@ -1680,7 +1688,20 @@ class Agent3DElement extends HTMLElement {
const manifestAttr = this.getAttribute('manifest');
const body = this.getAttribute('body');
const agentIdAttr = this.getAttribute('agent-id');
+ const avatarIdAttr = this.getAttribute('avatar-id');
const chainIdAttr = this.getAttribute('chain-id');
+ const apiBase = this.getAttribute('api-base') || _scriptOrigin || window.location.origin;
+ if (avatarIdAttr && !src && !manifestAttr && !body && !agentIdAttr) {
+ try {
+ return await resolveByAvatarId(avatarIdAttr, { origin: apiBase });
+ } catch (err) {
+ console.warn(
+ '[agent-3d] avatar-id resolve failed, using default avatar:',
+ err,
+ );
+ return this._defaultFallbackManifest();
+ }
+ }
if (src) {
if (agentIdAttr) console.warn('[agent-3d] both src and agent-id provided; using src');
// Plain .glb / .gltf URLs are bare bodies, not manifests — treat
diff --git a/src/skills/local-packs.js b/src/skills/local-packs.js
index bee635f09..fd0c707bb 100644
--- a/src/skills/local-packs.js
+++ b/src/skills/local-packs.js
@@ -18,7 +18,10 @@ let _cached = null;
export function loadLocalSkillPacks() {
if (_cached) return _cached;
_cached = JSON.parse(
- readFileSync(new URL('../../data/_generated/local-skill-packs.json', import.meta.url), 'utf8'),
+ readFileSync(
+ new URL('../../data/_generated/local-skill-packs.json', import.meta.url),
+ 'utf8',
+ ),
);
return _cached;
}
diff --git a/src/sns/pay-by-name.js b/src/sns/pay-by-name.js
new file mode 100644
index 000000000..c529b8958
--- /dev/null
+++ b/src/sns/pay-by-name.js
@@ -0,0 +1,153 @@
+/**
+ * Pay-by-name client.
+ *
+ * One self-contained flow:
+ * 1. Connect a Solana wallet (Phantom-style window.solana).
+ * 2. Ask /api/x402/pay-by-name to resolve the name and build an unsigned
+ * USDC SPL transfer with the connected wallet as fee payer + source.
+ * 3. Ask the wallet to sign + send the transaction.
+ * 4. Confirm via the same blockhash returned by the backend.
+ *
+ * Callers don't have to know anything about Solana — they pass a name and an
+ * amount and get back `{ signature, recipient, amount_usdc }`. The status
+ * callback gives them a string to show in the UI at each step.
+ *
+ * Imports `@solana/web3.js` dynamically so pages that don't open the modal
+ * never pay for the chunk.
+ */
+
+const ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+let _web3 = null;
+async function loadWeb3() {
+ if (!_web3) _web3 = await import('@solana/web3.js');
+ return _web3;
+}
+
+// Phantom, Solflare, Backpack — all inject Solana-Web-Standard-ish providers.
+// We accept the lowest common denominator: connect() + signTransaction() (or
+// signAndSendTransaction()) on either window.solana or window.phantom.solana.
+function detectWallet() {
+ const candidates = [
+ typeof window !== 'undefined' && window.phantom?.solana,
+ typeof window !== 'undefined' && window.solana,
+ typeof window !== 'undefined' && window.solflare,
+ typeof window !== 'undefined' && window.backpack?.solana,
+ ].filter(Boolean);
+ return candidates[0] || null;
+}
+
+export function hasInjectedWallet() {
+ return !!detectWallet();
+}
+
+/**
+ * Connect the wallet and return { wallet, publicKey } (publicKey as base58).
+ * Throws if no wallet is installed or the user rejects.
+ */
+export async function connectWallet() {
+ const wallet = detectWallet();
+ if (!wallet) {
+ const e = new Error('No Solana wallet detected. Install Phantom, Solflare, or Backpack.');
+ e.code = 'no_wallet';
+ throw e;
+ }
+ if (!wallet.isConnected || !wallet.publicKey) {
+ await wallet.connect();
+ }
+ const publicKey = wallet.publicKey?.toBase58?.() || wallet.publicKey?.toString?.();
+ if (!publicKey || !ADDR_RE.test(publicKey)) {
+ const e = new Error('Wallet connected but did not expose a public key.');
+ e.code = 'wallet_no_pubkey';
+ throw e;
+ }
+ return { wallet, publicKey };
+}
+
+/**
+ * Run the full pay-by-name flow.
+ *
+ * @param {object} opts
+ * @param {string} opts.name The .sol name / @handle / address to pay.
+ * @param {number} opts.amount USDC amount, in dollar units (not atoms).
+ * @param {(step: string) => void} [opts.onStatus]
+ * Callback invoked at each phase with a
+ * user-facing status string.
+ * @param {string} [opts.rpcUrl] Override the RPC used for confirmation.
+ * Defaults to the same-origin proxy at
+ * `/api/solana-rpc` which avoids public
+ * mainnet 403s.
+ *
+ * Returns { signature, recipient, amount_usdc, explorer }.
+ */
+export async function payByName({ name, amount, onStatus, rpcUrl }) {
+ const status = (s) => { try { onStatus?.(s); } catch {} };
+
+ status('Connecting wallet…');
+ const { wallet, publicKey } = await connectWallet();
+
+ status('Resolving name…');
+ const prepRes = await fetch('/api/x402/pay-by-name', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ mode: 'prep',
+ name,
+ amount_usdc: amount,
+ payer_wallet: publicKey,
+ }),
+ });
+ const prepBody = await prepRes.json();
+ if (!prepRes.ok) {
+ const e = new Error(prepBody?.error_description || `prep failed (${prepRes.status})`);
+ e.code = prepBody?.error || 'prep_failed';
+ throw e;
+ }
+ const { recipient, amount_usdc, tx_base64, blockhash, last_valid_block_height } = prepBody.data;
+
+ status(`Sign in wallet — ${amount_usdc} USDC to ${recipient.resolved}…`);
+ const { Connection, VersionedTransaction } = await loadWeb3();
+ const rawTx = Uint8Array.from(atob(tx_base64), (c) => c.charCodeAt(0));
+ const tx = VersionedTransaction.deserialize(rawTx);
+
+ let signature;
+ if (typeof wallet.signAndSendTransaction === 'function') {
+ // Phantom's preferred path — wallet handles signing + RPC submission.
+ const result = await wallet.signAndSendTransaction(tx);
+ signature = result?.signature || result;
+ } else {
+ // Wallets that only expose signTransaction (Solflare older builds).
+ const signed = await wallet.signTransaction(tx);
+ const conn = new Connection(rpcUrl || `${location.origin}/api/solana-rpc`, 'confirmed');
+ signature = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false });
+ }
+ if (!signature || typeof signature !== 'string') {
+ throw new Error('Wallet did not return a transaction signature.');
+ }
+
+ status('Confirming on-chain…');
+ const conn = new Connection(rpcUrl || `${location.origin}/api/solana-rpc`, 'confirmed');
+ try {
+ await conn.confirmTransaction(
+ { signature, blockhash, lastValidBlockHeight: last_valid_block_height },
+ 'confirmed',
+ );
+ } catch (err) {
+ // Confirmation timeout doesn't mean failure — the tx may have landed
+ // after our window. Surface the signature so the caller can verify in
+ // Solscan, and let the modal show a "check on explorer" link instead
+ // of pretending it failed.
+ const e = new Error(`Submitted but not confirmed in window: ${err?.message || 'timeout'}`);
+ e.code = 'confirm_timeout';
+ e.signature = signature;
+ throw e;
+ }
+
+ status('Done.');
+ return {
+ signature,
+ recipient,
+ amount_usdc,
+ explorer: `https://solscan.io/tx/${signature}`,
+ };
+}
diff --git a/tests/api/pay-by-name-resolve.test.js b/tests/api/pay-by-name-resolve.test.js
new file mode 100644
index 000000000..a4326ea14
--- /dev/null
+++ b/tests/api/pay-by-name-resolve.test.js
@@ -0,0 +1,185 @@
+// /api/x402/pay-by-name?name=… (GET resolve-only mode).
+//
+// Exercises all three name-namespace branches: raw base58 address, @username,
+// and *.sol. Mocks the DB and the Bonfida SDK so the test runs offline.
+
+import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const snsResolve = vi.fn();
+vi.mock('@bonfida/spl-name-service', () => ({
+ resolve: (...a) => snsResolve(...a),
+}));
+
+vi.mock('../../api/_lib/agent-pumpfun.js', () => ({
+ solanaConnection: () => ({}),
+ loadAgentForSigning: vi.fn(),
+}));
+
+beforeAll(() => {
+ process.env.THREEWS_SOL_PARENT_DOMAIN = 'threews.sol';
+});
+
+const { default: handler } = await import('../../api/x402/pay-by-name.js');
+
+const PAYER = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';
+const RECIPIENT = 'HKKp49zUBeaABFMpBWKCJPoNDLiR4AEEr8FJKuZPn6Nk';
+
+function makeReq(url, method = 'GET') {
+ return { url, method, headers: { host: 'x' }, query: {} };
+}
+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; },
+ };
+}
+async function call(url, method) {
+ const res = makeRes();
+ await handler(makeReq(url, method), res);
+ let body = null;
+ try { body = JSON.parse(res._body); } catch {}
+ return { res, body };
+}
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ snsResolve.mockReset();
+});
+
+describe('GET /api/x402/pay-by-name (raw address namespace)', () => {
+ it('passes a base58 address through without DB or SNS calls', async () => {
+ const { res, body } = await call(`/api/x402/pay-by-name?name=${RECIPIENT}`);
+ expect(res.statusCode).toBe(200);
+ expect(body.data).toEqual({
+ address: RECIPIENT,
+ source: 'address',
+ resolved: RECIPIENT,
+ });
+ expect(sqlMock).not.toHaveBeenCalled();
+ expect(snsResolve).not.toHaveBeenCalled();
+ });
+});
+
+describe('GET /api/x402/pay-by-name (@username namespace)', () => {
+ it('resolves @handle → user → default agent wallet', async () => {
+ sqlMock
+ .mockResolvedValueOnce([{ id: 'u1', username: 'nich', display_name: 'Nicholas' }])
+ .mockResolvedValueOnce([{ sol: RECIPIENT }]);
+ const { res, body } = await call('/api/x402/pay-by-name?name=@nich');
+ expect(res.statusCode).toBe(200);
+ expect(body.data.address).toBe(RECIPIENT);
+ expect(body.data.source).toBe('username');
+ expect(body.data.resolved).toBe('@nich');
+ expect(body.data.claim).toEqual({
+ user_id: 'u1',
+ username: 'nich',
+ display_name: 'Nicholas',
+ });
+ });
+
+ it('accepts a bare handle without the @ prefix', async () => {
+ sqlMock
+ .mockResolvedValueOnce([{ id: 'u1', username: 'nich', display_name: 'Nicholas' }])
+ .mockResolvedValueOnce([{ sol: RECIPIENT }]);
+ const { body } = await call('/api/x402/pay-by-name?name=nich');
+ expect(body.data.source).toBe('username');
+ expect(body.data.resolved).toBe('@nich');
+ });
+
+ it('404s when the username does not exist', async () => {
+ sqlMock.mockResolvedValueOnce([]);
+ const { res, body } = await call('/api/x402/pay-by-name?name=@ghost');
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ it('404s when the user has no agent with a Solana wallet', async () => {
+ sqlMock
+ .mockResolvedValueOnce([{ id: 'u1', username: 'nich' }])
+ .mockResolvedValueOnce([]);
+ const { res, body } = await call('/api/x402/pay-by-name?name=@nich');
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+});
+
+describe('GET /api/x402/pay-by-name (.sol namespace)', () => {
+ it('resolves a top-level .sol via Bonfida', async () => {
+ // Top-level .sol — no DB lookup (it's not under our threews. parent)
+ snsResolve.mockResolvedValueOnce({ toBase58: () => RECIPIENT });
+ const { res, body } = await call('/api/x402/pay-by-name?name=bonfida.sol');
+ expect(res.statusCode).toBe(200);
+ expect(body.data.address).toBe(RECIPIENT);
+ expect(body.data.source).toBe('sns');
+ expect(body.data.resolved).toBe('bonfida.sol');
+ // `resolve()` got the bare label (without .sol).
+ expect(snsResolve).toHaveBeenCalledWith(expect.anything(), 'bonfida');
+ });
+
+ it('attaches the DB claim when resolving a *.threews.sol subdomain', async () => {
+ sqlMock.mockResolvedValueOnce([{
+ label: 'nich',
+ parent: 'threews',
+ user_id: 'u1',
+ username: 'nich',
+ display_name: 'Nicholas',
+ }]);
+ snsResolve.mockResolvedValueOnce({ toBase58: () => RECIPIENT });
+ const { res, body } = await call('/api/x402/pay-by-name?name=nich.threews.sol');
+ expect(res.statusCode).toBe(200);
+ expect(body.data.address).toBe(RECIPIENT);
+ expect(body.data.source).toBe('sns');
+ expect(body.data.resolved).toBe('nich.threews.sol');
+ expect(body.data.claim).toEqual({
+ user_id: 'u1',
+ username: 'nich',
+ display_name: 'Nicholas',
+ });
+ expect(snsResolve).toHaveBeenCalledWith(expect.anything(), 'nich.threews');
+ });
+
+ it('does NOT attach a claim when the *.threews subdomain has no DB row', async () => {
+ sqlMock.mockResolvedValueOnce([]);
+ snsResolve.mockResolvedValueOnce({ toBase58: () => RECIPIENT });
+ const { body } = await call('/api/x402/pay-by-name?name=ghost.threews.sol');
+ expect(body.data.address).toBe(RECIPIENT);
+ expect(body.data.claim).toBeUndefined();
+ });
+
+ it('404s when Bonfida cannot resolve the domain', async () => {
+ snsResolve.mockRejectedValueOnce(new Error('no SOL record'));
+ const { res, body } = await call('/api/x402/pay-by-name?name=does-not-exist.sol');
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+});
+
+describe('GET /api/x402/pay-by-name (validation)', () => {
+ it('400s when name is missing', async () => {
+ const { res, body } = await call('/api/x402/pay-by-name');
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('404s on a name that does not match any namespace', async () => {
+ const { res, body } = await call('/api/x402/pay-by-name?name=!!!');
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ it('rejects methods other than GET or POST', async () => {
+ const { res } = await call('/api/x402/pay-by-name?name=' + RECIPIENT, 'DELETE');
+ expect(res.statusCode).toBe(405);
+ });
+});
diff --git a/tests/api/x402-pay-by-name.test.js b/tests/api/x402-pay-by-name.test.js
new file mode 100644
index 000000000..59189a52b
--- /dev/null
+++ b/tests/api/x402-pay-by-name.test.js
@@ -0,0 +1,274 @@
+// /api/x402/pay-by-name — name → payment routing. Exercises the resolver
+// across all three name sources (raw address, .sol domain incl. threews
+// subdomain, username) plus the prep/send envelope validation. Mocks Bonfida
+// + DB + auth so the tests stay offline.
+
+import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));
+
+const snsResolveMock = vi.fn();
+vi.mock('@bonfida/spl-name-service', () => ({
+ resolve: (...a) => snsResolveMock(...a),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const getSessionUserMock = vi.fn(async () => null);
+const authenticateBearerMock = vi.fn(async () => null);
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUserMock(...a),
+ authenticateBearer: (...a) => authenticateBearerMock(...a),
+ extractBearer: () => null,
+}));
+
+// solanaConnection() returns an object — only handleResolve and handlePrep
+// touch it, and handlePrep also calls getLatestBlockhash. We stub a minimal
+// surface and rely on individual tests to mock it further when needed.
+const connMock = {
+ getLatestBlockhash: vi.fn(async () => ({
+ blockhash: '11111111111111111111111111111111',
+ lastValidBlockHeight: 100,
+ })),
+};
+vi.mock('../../api/_lib/agent-pumpfun.js', () => ({
+ solanaConnection: () => connMock,
+ loadAgentForSigning: vi.fn(async () => ({ error: { status: 404, code: 'not_found', msg: 'agent not found' } })),
+}));
+
+beforeAll(() => {
+ process.env.THREEWS_SOL_PARENT_DOMAIN = 'threews.sol';
+});
+
+const ADDR = 'HKKp49zUBeaABFMpBWKCJPoNDLiR4AEEr8FJKuZPn6Nk';
+const PAYER = '5xoBq7f6XNGSpGT6h2KqxKaq6r8sfTrgyiUbWiQ7Lf4D';
+
+const { default: handler } = await import('../../api/x402/pay-by-name.js');
+
+function makeReq(url, method = 'GET', body = null) {
+ const req = {
+ url,
+ method,
+ headers: { host: 'x', 'content-type': 'application/json' },
+ query: {},
+ };
+ if (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);
+ return req;
+ };
+ req.headers['content-length'] = String(buf.length);
+ }
+ return req;
+}
+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; },
+ };
+}
+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 {}
+ return { res, body: parsed };
+}
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ snsResolveMock.mockReset();
+ getSessionUserMock.mockReset().mockResolvedValue(null);
+ authenticateBearerMock.mockReset().mockResolvedValue(null);
+});
+
+describe('GET /api/x402/pay-by-name?name=… (resolve)', () => {
+ it('passes a raw base58 address straight through', async () => {
+ const { res, body } = await call(`/api/x402/pay-by-name?name=${ADDR}`);
+ expect(res.statusCode).toBe(200);
+ expect(body.data).toEqual({ address: ADDR, source: 'address', resolved: ADDR });
+ expect(snsResolveMock).not.toHaveBeenCalled();
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('resolves a top-level .sol domain via SNS', async () => {
+ snsResolveMock.mockResolvedValue({ toBase58: () => ADDR });
+ const { res, body } = await call('/api/x402/pay-by-name?name=bonfida.sol');
+ expect(res.statusCode).toBe(200);
+ expect(body.data.address).toBe(ADDR);
+ expect(body.data.source).toBe('sns');
+ expect(body.data.resolved).toBe('bonfida.sol');
+ expect(body.data.claim).toBeUndefined();
+ expect(snsResolveMock).toHaveBeenCalledWith(expect.anything(), 'bonfida');
+ });
+
+ 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',
+ }]);
+ 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);
+ expect(body.data.source).toBe('sns');
+ expect(body.data.claim).toEqual({
+ user_id: '00000000-0000-0000-0000-000000000001',
+ username: 'nich',
+ display_name: 'Nicholas',
+ });
+ expect(snsResolveMock).toHaveBeenCalledWith(expect.anything(), 'nich.threews');
+ });
+
+ it('returns 404 when SNS resolution fails', async () => {
+ snsResolveMock.mockRejectedValue(new Error('DomainDoesNotExist'));
+ sqlMock.mockResolvedValueOnce([]); // claim DB lookup tries first for threews
+ const { res, body } = await call('/api/x402/pay-by-name?name=missing.threews.sol');
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ it('resolves @username to the user\'s default agent wallet', async () => {
+ sqlMock
+ .mockResolvedValueOnce([{ id: 'u1', username: 'nich', display_name: 'Nicholas' }])
+ .mockResolvedValueOnce([{ sol: ADDR }]);
+ const { res, body } = await call('/api/x402/pay-by-name?name=@nich');
+ expect(res.statusCode).toBe(200);
+ expect(body.data.address).toBe(ADDR);
+ expect(body.data.source).toBe('username');
+ expect(body.data.resolved).toBe('@nich');
+ expect(body.data.claim.username).toBe('nich');
+ });
+
+ it('resolves a bare username (no @) the same way', async () => {
+ sqlMock
+ .mockResolvedValueOnce([{ id: 'u1', username: 'nich', display_name: 'Nicholas' }])
+ .mockResolvedValueOnce([{ sol: ADDR }]);
+ const { res, body } = await call('/api/x402/pay-by-name?name=nich');
+ expect(res.statusCode).toBe(200);
+ expect(body.data.source).toBe('username');
+ });
+
+ it('returns 404 when the username exists but the user has no agent wallet', async () => {
+ sqlMock
+ .mockResolvedValueOnce([{ id: 'u1', username: 'nich', display_name: 'Nicholas' }])
+ .mockResolvedValueOnce([{ sol: null }]);
+ const { res, body } = await call('/api/x402/pay-by-name?name=@nich');
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ it('returns 404 when the username does not exist', async () => {
+ sqlMock.mockResolvedValueOnce([]);
+ const { res } = await call('/api/x402/pay-by-name?name=@ghost');
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('rejects an unrecognized name shape with 404', async () => {
+ const { res } = await call('/api/x402/pay-by-name?name=!!not-a-name!!');
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('rejects calls with no name', async () => {
+ const { res, body } = await call('/api/x402/pay-by-name');
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('sets a brief cache hint on successful resolution', async () => {
+ const { res } = await call(`/api/x402/pay-by-name?name=${ADDR}`);
+ expect(res.getHeader('cache-control')).toMatch(/max-age=60/);
+ });
+});
+
+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,
+ });
+ expect(res.statusCode).toBe(400);
+ expect(body.error_description).toMatch(/payer_wallet/);
+ });
+
+ 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,
+ });
+ expect(res.statusCode).toBe(400);
+ expect(body.error_description).toMatch(/amount_usdc/);
+ });
+
+ 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,
+ });
+ expect(res.statusCode).toBe(400);
+ expect(body.error_description).toMatch(/amount_usdc/);
+ });
+
+ 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,
+ });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('self_pay');
+ });
+
+ 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,
+ });
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ 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,
+ });
+ expect(res.statusCode).toBe(200);
+ expect(body.data.recipient.address).toBe(ADDR);
+ expect(body.data.amount_usdc).toBe(1.5);
+ expect(typeof body.data.tx_base64).toBe('string');
+ expect(body.data.tx_base64.length).toBeGreaterThan(0);
+ expect(body.data.mint).toBe('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');
+ });
+});
+
+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',
+ });
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ 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,
+ });
+ expect(res.statusCode).toBe(400);
+ expect(body.error_description).toMatch(/agent_id/);
+ });
+
+ it('rejects non-GET/POST methods', async () => {
+ const { res } = await call('/api/x402/pay-by-name', 'DELETE');
+ expect(res.statusCode).toBe(405);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 5ec38a284..0b8347a55 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1055,6 +1055,14 @@
"src": "/api/threews/subdomain",
"dest": "/api/threews/subdomain.js"
},
+ {
+ "src": "/api/threews/me",
+ "dest": "/api/threews/me.js"
+ },
+ {
+ "src": "/api/u-og",
+ "dest": "/api/u-og.js"
+ },
{
"src": "/api/x402/pay-by-name",
"dest": "/api/x402/pay-by-name.js"