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.

feat: add payment and trading processes

roundtrippedb37af3f01e99
diff --git a/api/_lib/avatars.js b/api/_lib/avatars.js
index 09c5f5740..6494f09af 100644
--- a/api/_lib/avatars.js
+++ b/api/_lib/avatars.js
@@ -38,10 +38,17 @@ export async function listAvatars({
a.size_bytes, a.content_type, a.source, a.source_meta, a.fork_count, a.visibility, a.tags, a.version,
a.model_category,
a.created_at, a.updated_at, a.parent_avatar_id,
- ai.id as agent_id, ai.wallet_address as agent_wallet_address
+ ai.id as agent_id, ai.wallet_address as agent_wallet_address,
+ ai.solana_address as agent_solana_address,
+ ai.solana_vanity_prefix as agent_solana_vanity_prefix,
+ ai.solana_vanity_suffix as agent_solana_vanity_suffix
from avatars a
left join lateral (
- select id, wallet_address from agent_identities
+ select id, wallet_address,
+ meta->>'solana_address' as solana_address,
+ meta->>'solana_vanity_prefix' as solana_vanity_prefix,
+ meta->>'solana_vanity_suffix' as solana_vanity_suffix
+ from agent_identities
where avatar_id = a.id and user_id = $1 and deleted_at is null
order by created_at asc limit 1
) ai on true
@@ -64,10 +71,17 @@ export async function getAvatar({ id, requesterId = null }) {
if (!isUuid(id)) return null;
const rows = await sql`
- select a.*, ai.id as agent_id, ai.wallet_address as agent_wallet_address
+ select a.*, ai.id as agent_id, ai.wallet_address as agent_wallet_address,
+ ai.solana_address as agent_solana_address,
+ ai.solana_vanity_prefix as agent_solana_vanity_prefix,
+ ai.solana_vanity_suffix as agent_solana_vanity_suffix
from avatars a
left join lateral (
- select id, wallet_address from agent_identities
+ select id, wallet_address,
+ meta->>'solana_address' as solana_address,
+ meta->>'solana_vanity_prefix' as solana_vanity_prefix,
+ meta->>'solana_vanity_suffix' as solana_vanity_suffix
+ from agent_identities
where avatar_id = a.id and user_id = ${requesterId} and deleted_at is null
order by created_at asc limit 1
) ai on true
@@ -430,6 +444,9 @@ function decorate(row) {
baked_at: row.baked_at || null,
agent_id: row.agent_id || null,
agent_wallet_address: row.agent_wallet_address || null,
+ agent_solana_address: row.agent_solana_address || null,
+ agent_solana_vanity_prefix: row.agent_solana_vanity_prefix || null,
+ agent_solana_vanity_suffix: row.agent_solana_vanity_suffix || null,
// On-chain block of the agent this avatar represents (public gallery only;
// null for callers whose query doesn't join it). Shape mirrors meta.onchain
// so the shared onchain badge can read it directly via `{ onchain }`.
diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.js
index b963e1d64..52df6b826 100644
--- a/api/agents/agent-trade.js
+++ b/api/agents/agent-trade.js
@@ -23,6 +23,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.
import { sql } from '../_lib/db.js';
import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { ensureAgentWallet, recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
import { getPumpTradeClient } from '../_lib/pump.js';
import { buildAmmSellInstructions, quoteAmmSell } from '../../workers/agent-sniper/amm-exit.js';
@@ -359,6 +360,11 @@ async function handleExecute(req, res, id) {
const { side, network, simulate, slippagePct } = input;
const idempotencyKey = input.idempotencyKey || randomUUID();
+ // CSRF on the real, fund-moving path only — `simulate` is a dry run that never
+ // signs or records. Bearer/API-key callers (the primary consumers of this flat
+ // trade endpoint) are exempt inside requireCsrf.
+ if (!simulate && !(await requireCsrf(req, res, auth.userId))) return;
+
// Guarantee the wallet exists (lazy provision) so a funded-but-unprovisioned
// agent can trade. ensureAgentWallet audits the provision and never returns
// the secret.
diff --git a/api/agents/solana-trade.js b/api/agents/solana-trade.js
index 6e9ad1942..1c5f9e36f 100644
--- a/api/agents/solana-trade.js
+++ b/api/agents/solana-trade.js
@@ -22,6 +22,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.
import { sql } from '../_lib/db.js';
import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
import { solanaConnection, solanaPublicConnection } from '../_lib/agent-pumpfun.js';
import { PublicKey, TransactionMessage, VersionedTransaction } from '@solana/web3.js';
@@ -253,6 +254,10 @@ export async function handleTrade(req, res, id) {
const network = netOf(body.network);
const preview = body.preview === true;
+ // CSRF on the state-changing path only — a live preview/quote moves no funds and
+ // would otherwise burn a single-use token on every keystroke. Bearer callers exempt.
+ if (!preview && !(await requireCsrf(req, res, auth.userId))) return;
+
let slippageBps = Number(body.slippage_bps ?? body.slippageBps);
if (!Number.isFinite(slippageBps)) slippageBps = DEFAULT_SLIPPAGE_BPS;
slippageBps = Math.max(0, Math.min(5_000, Math.round(slippageBps)));
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index 684d68381..1354df5f8 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -5,6 +5,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.
import { sql } from '../_lib/db.js';
import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { generateSolanaAgentWallet, recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
import { solanaConnection, solanaPublicConnection } from '../_lib/agent-pumpfun.js';
import { reverseLookupAddress } from '../../src/solana/sns.js';
@@ -26,7 +27,7 @@ import { logAudit } from '../_lib/audit.js';
import { explorerTxUrl } from '../_lib/avatar-wallet.js';
import {
validateSolanaAddress, enforceSpendLimit, SpendLimitError, lamportsToUsd,
- getSpendLimits, setSpendLimits, listCustodyEvents, updateCustodyEvent,
+ getSpendLimits, setSpendLimits, listCustodyEvents, updateCustodyEvent, recordCustodyEvent,
getDailySpendUsd, getTradeLimits, setTradeLimits, getDailySpendLamports,
} from '../_lib/agent-trade-guards.js';
@@ -489,6 +490,11 @@ async function handleWithdraw(req, res, id) {
if (owned.error) return;
const { auth, meta, address: fromAddress, encryptedSecret } = owned;
+ // CSRF: sweeping a custodial wallet is the single highest-stakes action on the
+ // platform — it must be at least as protected as message-signing. Bearer/API-key
+ // callers are exempt inside requireCsrf (the token is itself proof of intent).
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+
// Owner-only daily withdraw cap + per-IP burst guard.
const rlUser = await limits.withdrawalPerUser(auth.userId);
if (!rlUser.success) return rateLimited(res, rlUser);
@@ -1004,12 +1010,305 @@ async function handleLimits(req, res, id) {
return json(res, 200, { data: { limits: limitsOut, trade_limits: getTradeLimits(meta), spent_today_usd: spentUsd, spent_today_sol: Number(spentLamports) / 1e9 } });
}
+// ── vanity grind + custodial swap ──────────────────────────────────────────────
+// GET /api/agents/:id/solana/vanity — owner-only current vanity status.
+// POST /api/agents/:id/solana/vanity — owner-only: grind a vanity keypair
+// server-side (the secret never leaves the server) and make it the agent's
+// custodial Solana wallet. If the existing wallet holds funds, every asset is
+// swept to the new address FIRST, signed by the old key; the stored key is only
+// swapped after the sweep confirms, so funds can never be stranded. This is an
+// internal custody migration between two wallets the same owner controls — not a
+// third-party withdrawal — so it is exempt from the withdraw allowlist but fully
+// audited as a `vanity_swap` custody event.
+
+// Server-side grind is bounded so a serverless invocation can't hang. Patterns
+// harder than this are ground in the browser at /vanity-wallet (GPU + workers,
+// up to 8 chars) and assigned via POST /api/agents/:id/solana { secret_key }.
+const VANITY_MAX_CHARS = 3; // combined prefix+suffix length for server grind
+const VANITY_MAX_ITERATIONS = 4_000_000;
+
+// Move every asset (all SPL tokens + remaining SOL) from a custodial keypair to a
+// destination address, reclaiming token-account rent. Two-phase so the final SOL
+// figure is exact: (A) transfer + close each token account, (B) sweep all SOL.
+// Returns { signatures, sol, tokens }. Throws if any leg fails to confirm — the
+// caller must NOT discard the source key unless this resolves.
+async function sweepWalletToAddress({ conn, fromKeypair, toPubkey, network }) {
+ const fromPk = fromKeypair.publicKey;
+ const signatures = [];
+ const movedTokens = [];
+
+ // Phase A — collect every non-empty token account across both token programs.
+ const tokenLegs = [];
+ for (const programId of [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID]) {
+ let resp;
+ try {
+ resp = await conn.getParsedTokenAccountsByOwner(fromPk, { programId });
+ } catch {
+ continue;
+ }
+ for (const { account } of resp.value) {
+ const info = account.data?.parsed?.info;
+ const amt = info?.tokenAmount;
+ if (!info || !amt) continue;
+ const raw = BigInt(amt.amount || '0');
+ if (raw <= 0n) continue;
+ const mintPk = new PublicKey(info.mint);
+ const sourceAta = getAssociatedTokenAddressSync(mintPk, fromPk, false, programId, ASSOCIATED_TOKEN_PROGRAM_ID);
+ const destAta = getAssociatedTokenAddressSync(mintPk, toPubkey, false, programId, ASSOCIATED_TOKEN_PROGRAM_ID);
+ tokenLegs.push({ mintPk, programId, sourceAta, destAta, raw, decimals: amt.decimals });
+ movedTokens.push({ mint: info.mint, ui_amount: amt.uiAmount, amount_raw: amt.amount });
+ }
+ }
+
+ // Send token transfers + closes in chunks so each transaction stays under the
+ // size limit. Closing the source ATA returns its rent lamports to `fromPk`,
+ // which are then swept out in phase B.
+ const CHUNK = 4;
+ for (let i = 0; i < tokenLegs.length; i += CHUNK) {
+ const chunk = tokenLegs.slice(i, i + CHUNK);
+ const ixs = [];
+ for (const leg of chunk) {
+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(
+ fromPk, leg.destAta, toPubkey, leg.mintPk, leg.programId, ASSOCIATED_TOKEN_PROGRAM_ID,
+ ));
+ ixs.push(createTransferCheckedInstruction(
+ leg.sourceAta, leg.mintPk, leg.destAta, fromPk, leg.raw, leg.decimals, [], leg.programId,
+ ));
+ ixs.push(createCloseAccountInstruction(leg.sourceAta, fromPk, fromPk, [], leg.programId));
+ }
+ const sig = await sendV0({ conn, payer: fromKeypair, ixs });
+ signatures.push(sig);
+ }
+
+ // Phase B — sweep all remaining SOL, leaving only the network fee. The old
+ // account is intentionally abandoned (drained to ~0), so no rent is reserved.
+ let lamports = 0n;
+ try {
+ lamports = BigInt(await conn.getBalance(fromPk, 'confirmed'));
+ } catch {
+ lamports = 0n;
+ }
+ const spendable = lamports - SOL_FEE_RESERVE_LAMPORTS;
+ let solMoved = 0;
+ if (spendable > 0n) {
+ const sig = await sendV0({
+ conn,
+ payer: fromKeypair,
+ ixs: [SystemProgram.transfer({ fromPubkey: fromPk, toPubkey, lamports: spendable })],
+ });
+ signatures.push(sig);
+ solMoved = Number(spendable) / 1e9;
+ }
+
+ return { signatures, sol: solMoved, tokens: movedTokens };
+}
+
+// Build, sign, send and confirm a single v0 transaction. Throws on any failure or
+// an unconfirmed/erroring result so callers treat the leg as not-yet-final.
+async function sendV0({ conn, payer, ixs }) {
+ const bh = await conn.getLatestBlockhash('confirmed');
+ const msg = new TransactionMessage({
+ payerKey: payer.publicKey,
+ recentBlockhash: bh.blockhash,
+ instructions: ixs,
+ }).compileToV0Message();
+ const vtx = new VersionedTransaction(msg);
+ vtx.sign([payer]);
+ const sig = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false, maxRetries: 3 });
+ const r = await conn.confirmTransaction(
+ { signature: sig, blockhash: bh.blockhash, lastValidBlockHeight: bh.lastValidBlockHeight },
+ 'confirmed',
+ );
+ if (r?.value?.err) throw new Error(`transaction ${sig} failed: ${JSON.stringify(r.value.err)}`);
+ return sig;
+}
+
+function validateVanityPattern(raw, label) {
+ if (raw == null || raw === '') return null;
+ const s = String(raw);
+ if (s.length > 6) return { error: `${label} is too long (max 6 base58 chars)` };
+ for (const c of s) {
+ if (!BASE58_ALPHABET.includes(c)) return { error: `${label} has a non-base58 char '${c}' (0/O/I/l are not allowed)` };
+ }
+ return { value: s };
+}
+
+async function handleVanity(req, res, id) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const owned = await loadOwnedWallet(req, res, id);
+ if (owned.error) return;
+ const { auth, meta, address: currentAddress, encryptedSecret } = owned;
+
+ if (req.method === 'GET') {
+ const rl = await limits.walletRead(auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+ return json(res, 200, {
+ data: {
+ address: currentAddress,
+ vanity_prefix: meta.solana_vanity_prefix || null,
+ vanity_suffix: meta.solana_vanity_suffix || null,
+ source: meta.solana_wallet_source || (encryptedSecret ? 'generated' : null),
+ is_vanity: !!(meta.solana_vanity_prefix || meta.solana_vanity_suffix),
+ max_chars: VANITY_MAX_CHARS,
+ },
+ });
+ }
+
+ // POST — sensitive: gate behind the withdrawal per-user cap + per-IP burst.
+ const rlUser = await limits.withdrawalPerUser(auth.userId);
+ if (!rlUser.success) return rateLimited(res, rlUser);
+ const rlIp = await limits.authIp(clientIp(req));
+ if (!rlIp.success) return rateLimited(res, rlIp);
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (e) {
+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');
+ }
+
+ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
+ const ignoreCase = body.ignoreCase === true || body.ignore_case === true;
+
+ const pfx = validateVanityPattern(body.prefix, 'prefix');
+ const sfx = validateVanityPattern(body.suffix, 'suffix');
+ if (pfx?.error) return error(res, 400, 'validation_error', pfx.error);
+ if (sfx?.error) return error(res, 400, 'validation_error', sfx.error);
+ const prefix = pfx?.value || null;
+ const suffix = sfx?.value || null;
+ if (!prefix && !suffix) return error(res, 400, 'validation_error', 'provide a prefix and/or suffix');
+
+ const combinedLen = (prefix?.length || 0) + (suffix?.length || 0);
+ if (combinedLen > VANITY_MAX_CHARS) {
+ return error(res, 400, 'pattern_too_hard',
+ `server-side grinding supports up to ${VANITY_MAX_CHARS} combined characters. ` +
+ `Grind longer patterns in your browser at /vanity-wallet (GPU-accelerated, up to 8 chars) and assign the result.`);
+ }
+
+ // Grind the vanity keypair. The secret stays in process memory only.
+ let ground;
+ try {
+ const est = estimateAttempts({ prefix, suffix, ignoreCase });
+ const maxIterations = Math.min(VANITY_MAX_ITERATIONS, Math.max(200_000, Math.ceil(est * 25)));
+ ground = await grindMintKeypair({ prefix, suffix, ignoreCase, maxIterations });
+ } catch (e) {
+ if (e?.code === 'vanity_timeout') {
+ return error(res, 504, 'vanity_timeout', 'could not find a matching address in time — try a shorter pattern or grind it in the browser at /vanity-wallet');
+ }
+ if (e?.code === 'invalid_vanity') return error(res, 400, 'validation_error', e.message);
+ console.error('[agents/solana/vanity] grind failed', e?.message);
+ return error(res, 502, 'grind_failed', 'vanity grind failed — try again');
+ }
+
+ const newKp = ground.keypair;
+ const newAddress = newKp.publicKey.toBase58();
+
+ // If the agent already holds a funded custodial wallet, migrate the balance to
+ // the new address before swapping the stored key. This is the money-safe gate:
+ // a failed sweep throws and we keep the old wallet intact.
+ let swept = null;
+ if (currentAddress && encryptedSecret && currentAddress !== newAddress) {
+ const conn = solanaConnection(network);
+ let needsSweep = false;
+ try {
+ const lamports = BigInt(await conn.getBalance(new PublicKey(currentAddress), 'confirmed'));
+ needsSweep = lamports > SOL_FEE_RESERVE_LAMPORTS;
+ if (!needsSweep) {
+ // Any non-empty token account also requires a sweep.
+ for (const programId of [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID]) {
+ const resp = await conn.getParsedTokenAccountsByOwner(new PublicKey(currentAddress), { programId }).catch(() => ({ value: [] }));
+ if (resp.value.some((t) => Number(t.account.data?.parsed?.info?.tokenAmount?.uiAmount) > 0)) {
+ needsSweep = true;
+ break;
+ }
+ }
+ }
+ } catch (e) {
+ return error(res, 502, 'rpc_error', 'could not read the current wallet balance — try again before migrating funds');
+ }
+
+ if (needsSweep) {
+ let oldKp;
+ try {
+ oldKp = await recoverSolanaAgentKeypair(encryptedSecret, {
+ agentId: id, userId: auth.userId, reason: 'vanity_swap',
+ meta: { from: currentAddress, to: newAddress, network },
+ });
+ } catch (e) {
+ console.error('[agents/solana/vanity] key recovery failed', e?.message);
+ return error(res, 500, 'key_recover_failed', 'could not access the current wallet key — no funds were moved and the wallet is unchanged');
+ }
+ try {
+ swept = await sweepWalletToAddress({ conn, fromKeypair: oldKp, toPubkey: newKp.publicKey, network });
+ } catch (e) {
+ console.error('[agents/solana/vanity] sweep failed', e?.message);
+ return error(res, 502, 'sweep_failed',
+ 'funds could not be fully migrated to the new address — your existing wallet is unchanged and still holds the funds. Try again.');
+ }
+ await recordCustodyEvent({
+ agentId: id, userId: auth.userId, eventType: 'spend', category: 'vanity_swap',
+ network, asset: 'ALL', status: 'confirmed',
+ signature: swept.signatures[swept.signatures.length - 1] || null,
+ destination: newAddress,
+ meta: { from: currentAddress, to: newAddress, sol: swept.sol, tokens: swept.tokens, signatures: swept.signatures },
+ }).catch(() => {});
+ }
+ }
+
+ // Persist the new keypair as the agent's custodial wallet.
+ const encrypted_secret = await _encryptSecret(Buffer.from(newKp.secretKey).toString('base64'));
+ const history = Array.isArray(meta.solana_wallet_history) ? meta.solana_wallet_history : [];
+ const nextMeta = {
+ ...meta,
+ solana_address: newAddress,
+ encrypted_solana_secret: encrypted_secret,
+ solana_wallet_source: 'vanity_grind',
+ solana_vanity_prefix: prefix || null,
+ solana_vanity_suffix: suffix || null,
+ };
+ if (!prefix) delete nextMeta.solana_vanity_prefix;
+ if (!suffix) delete nextMeta.solana_vanity_suffix;
+ if (currentAddress && currentAddress !== newAddress) {
+ nextMeta.solana_wallet_history = [
+ ...history,
+ { address: currentAddress, replaced_at: new Date().toISOString(), reason: 'vanity_upgrade', swept: !!swept },
+ ].slice(-10);
+ }
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(nextMeta)}::jsonb WHERE id = ${id}`;
+
+ if (currentAddress) await cacheSet(`sol:bal:${currentAddress}:${network}`, null, 1).catch(() => {});
+ await cacheSet(`sol:bal:${newAddress}:${network}`, null, 1).catch(() => {});
+
+ recordEvent({
+ userId: auth.userId, agentId: id, kind: 'solana_vanity_grind', tool: 'server', status: 'ok',
+ meta: { address: newAddress, prefix, suffix, ignoreCase, iterations: ground.iterations, swept: swept ? { sol: swept.sol, tokens: swept.tokens.length } : null },
+ });
+ logAudit({ userId: auth.userId, action: 'custody.vanity_grind', resourceId: id, meta: { address: newAddress, prefix, suffix, replaced: currentAddress || null, swept: !!swept }, req });
+
+ return json(res, 201, {
+ data: {
+ address: newAddress,
+ vanity_prefix: prefix,
+ vanity_suffix: suffix,
+ network,
+ iterations: ground.iterations,
+ duration_ms: ground.durationMs,
+ replaced: currentAddress && currentAddress !== newAddress ? currentAddress : null,
+ swept,
+ source: 'vanity_grind',
+ },
+ });
+}
+
// ── dispatcher ────────────────────────────────────────────────────────────────
export default async function handler(req, res, id, action) {
if (action === 'activity') return handleActivity(req, res, id);
if (action === 'airdrop') return handleAirdrop(req, res, id);
if (action === 'withdraw') return handleWithdraw(req, res, id);
+ if (action === 'vanity') return handleVanity(req, res, id);
if (action === 'holdings') return handleHoldings(req, res, id);
if (action === 'custody') return handleCustody(req, res, id);
if (action === 'limits') return handleLimits(req, res, id);
diff --git a/api/x402-pay.js b/api/x402-pay.js
index 3653e4491..80fb69b87 100644
--- a/api/x402-pay.js
+++ b/api/x402-pay.js
@@ -33,6 +33,7 @@ import bs58 from 'bs58';
import { cors, json, readJson, wrap, rateLimited, setRateLimitHeaders } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
+import { requireCsrf } from './_lib/csrf.js';
import {
paymentRequirements,
verifyPayment,
@@ -942,6 +943,11 @@ async function handleExternalPay(req, res, input, ip) {
}
}
+ // CSRF on the settle path (funds move + the agent key signs). The preview branch
+ // above returns before this point, so a live price probe never burns a token.
+ // Bearer/API-key callers are exempt inside requireCsrf.
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+
const spendGuard = { agentId, userId: auth.userId, meta: loaded.meta, network: 'mainnet' };
const wantsStream =
(req.headers.accept || '').includes('text/event-stream') || input.stream === true;
@@ -1068,6 +1074,8 @@ export default wrap(async (req, res) => {
if (!auth) return json(res, 401, { error: 'authentication_required' });
const loaded = await loadAgentKeypairForUser(routing.agentId, auth.userId);
if (!loaded) return json(res, 403, { error: 'agent_not_found_or_no_solana_wallet' });
+ // CSRF: this tool call pays from the agent's own wallet. Bearer callers exempt.
+ if (!(await requireCsrf(req, res, auth.userId))) return;
buyer = loaded.keypair;
// Per-agent spend policy applies to x402 just like trade/snipe/withdraw.
spendGuard = { agentId: routing.agentId, userId: auth.userId, meta: loaded.meta, network: 'mainnet' };
diff --git a/data/changelog.json b/data/changelog.json
index feed09db9..fb6bbaf06 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-19",
+ "title": "AR agents hold their place and size when you rotate your phone",
+ "summary": "Camera AR used to assume you were holding your phone upright. Rotate to landscape — or just have the browser's toolbar slide away as you scroll — and a pinned agent could quietly change size or drift off the real-world spot you placed it on. IRL now re-reads your camera's lens and your screen's orientation the instant either changes, so the agent keeps its true scale and stays locked to its spot whether you hold the phone portrait or sideways. The motion-sensor lock that rotates the view as you turn now understands landscape too, so panning around the agent stays smooth and accurate, and the rapid resizing iPhone Safari does while scrolling no longer makes the scene stutter.",
+ "tags": [
+ "improvement",
+ "fix"
+ ],
+ "link": "/irl"
+ },
{
"date": "2026-06-19",
"title": "Pinning your agent holds up when GPS gets flaky",
diff --git a/public/avatar-actions.js b/public/avatar-actions.js
index e2b7d3a47..a4a9a4f42 100644
--- a/public/avatar-actions.js
+++ b/public/avatar-actions.js
@@ -219,6 +219,7 @@ class AvatarActions extends HTMLElement {
}
const evm = ag.wallet_address || null;
const sol = ag.meta?.solana_address || null;
+ const solVanity = !!(sol && (ag.meta?.solana_vanity_prefix || ag.meta?.solana_vanity_suffix));
const manage = `<a class="manage" href="/agent-edit.html?id=${ag.id}">Manage →</a>`;
if (!evm && !sol) {
diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.js
index 74ffcc5d3..c58f5763e 100644
--- a/src/agent-wallet-hub/index.js
+++ b/src/agent-wallet-hub/index.js
@@ -26,6 +26,7 @@ import './tabs/deposit.js';
import './tabs/trade.js';
import './tabs/snipe.js';
import './tabs/pay.js';
+import './tabs/vanity.js';
import './tabs/withdraw.js';
import { escapeHtml, shortAddress, copyToClipboard, toast } from './util.js';
diff --git a/src/agent-wallet-hub/tabs/vanity.js b/src/agent-wallet-hub/tabs/vanity.js
new file mode 100644
index 000000000..9b6d44963
--- /dev/null
+++ b/src/agent-wallet-hub/tabs/vanity.js
@@ -0,0 +1,275 @@
+/**
+ * Agent Wallet hub — Vanity tab.
+ *
+ * Owner-only. Opt-in: grind a custom vanity address for the agent's custodial
+ * Solana wallet, with a per-agent prefix/suffix the owner chooses. The grind runs
+ * server-side (the secret key never leaves the server) via
+ * POST /api/agents/:id/solana/vanity. If the wallet already holds funds, every
+ * asset is swept to the new address before the stored key is swapped — funds are
+ * never stranded (the swap is aborted if the sweep fails).
+ *
+ * Server-side grinding is bounded to short patterns (≤3 combined chars). Longer,
+ * harder patterns are ground in the browser at /vanity-wallet (GPU + workers, up
+ * to 8 chars) and assigned from there — this tab links out for that path.
+ */
+
+import { registerWalletTab } from '../registry.js';
+
+const MAX_CHARS = 3;
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]*$/;
+
+const VN_STYLE_ID = 'awh-vanity-style';
+const VN_STYLE = `
+.awh-vn-head{display:flex;align-items:center;gap:10px;margin-bottom:var(--space-4,16px);}
+.awh-vn-addr{font-family:var(--font-mono,ui-monospace,monospace);font-size:var(--text-md,.8125rem);color:var(--ink,#e8e8e8);word-break:break-all;}
+.awh-vn-addr b{color:#a78bfa;}
+.awh-vn-tag{font-size:var(--text-2xs,.6875rem);font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#a78bfa;background:rgba(139,92,246,.15);border:1px solid rgba(139,92,246,.4);border-radius:999px;padding:2px 8px;}
+.awh-vn-grid{display:flex;gap:10px;}
+.awh-vn-grid .awh-fld{flex:1;}
+.awh-vn-est{font-size:var(--text-sm,.764rem);color:var(--ink-dim,#888);margin:2px 0 var(--space-3,12px);}
+.awh-vn-est b{color:var(--ink,#e8e8e8);}
+.awh-vn-est.warn{color:var(--warn,#fbbf24);}
+.awh-vn-toggle{display:flex;align-items:center;gap:8px;font-size:var(--text-sm,.764rem);color:var(--ink-dim,#888);margin-bottom:var(--space-3,12px);cursor:pointer;}
+.awh-vn-warn{background:color-mix(in srgb, var(--warn,#fbbf24) 10%, transparent);border:1px solid color-mix(in srgb, var(--warn,#fbbf24) 28%, transparent);color:var(--warn,#fbbf24);border-radius:var(--radius-md,10px);padding:10px 12px;font-size:var(--text-sm,.764rem);margin-bottom:var(--space-3,12px);line-height:1.45;}
+.awh-vn-out{font-family:var(--font-mono,ui-monospace,monospace);font-size:var(--text-2xs,.6875rem);color:var(--ink-dim,#888);}
+`;
+
+function injectStyle() {
+ if (typeof document === 'undefined' || document.getElementById(VN_STYLE_ID)) return;
+ const tag = document.createElement('style');
+ tag.id = VN_STYLE_ID;
+ tag.textContent = VN_STYLE;
+ document.head.appendChild(tag);
+}
+
+async function call(url, { method = 'GET', body = null } = {}) {
+ try {
+ const opts = { method, credentials: 'include', headers: {} };
+ if (body != null) {
+ opts.headers['content-type'] = 'application/json';
+ opts.body = JSON.stringify(body);
+ }
+ const r = await fetch(url, opts);
+ let j = null;
+ try { j = await r.json(); } catch { /* empty body */ }
+ if (!r.ok) return { ok: false, status: r.status, code: j?.error || 'error', message: j?.error_description || `request failed (${r.status})` };
+ return { ok: true, status: r.status, data: j?.data ?? j };
+ } catch (err) {
+ return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };
+ }
+}
+
+// Expected attempts ≈ alphabet^len. Matches the server estimate.
+function estimate(prefix, suffix, ignoreCase) {
+ const len = (prefix?.length || 0) + (suffix?.length || 0);
+ if (len === 0) return 1;
+ return Math.pow(ignoreCase ? 33 : 58, len);
+}
+
+registerWalletTab({
+ id: 'vanity',
+ label: 'Vanity',
+ order: 50,
+ ownerOnly: true,
+ mount({ panel, ctx }) {
+ injectStyle();
+ const esc = ctx.escapeHtml;
+ const { toast } = ctx;
+ const base = `/api/agents/${encodeURIComponent(ctx.agentId)}/solana/vanity`;
+
+ let destroyed = false;
+ const state = {
+ status: null, // { address, vanity_prefix, vanity_suffix, is_vanity } | { error }
+ prefix: '',
+ suffix: '',
+ ignoreCase: false,
+ phase: 'form', // 'form' | 'grinding' | 'success'
+ result: null,
+ err: null,
+ };
+
+ function currentAddrHTML() {
+ const s = state.status;
+ if (!s || s.error || !s.address) return '';
+ const a = s.address;
+ const p = s.vanity_prefix;
+ const sf = s.vanity_suffix;
+ let html = esc(a);
+ if (p && a.startsWith(p)) html = `<b>${esc(p)}</b>${esc(a.slice(p.length))}`;
+ if (sf && a.endsWith(sf)) {
+ const body = p && a.startsWith(p) ? a.slice(p.length) : a;
+ const mid = body.slice(0, body.length - sf.length);
+ const pre = p && a.startsWith(p) ? `<b>${esc(p)}</b>` : '';
+ html = `${pre}${esc(mid)}<b>${esc(sf)}</b>`;
+ }
+ return html;
+ }
+
+ function render() {
+ if (destroyed) return;
+ if (state.status === null) {
+ panel.innerHTML = `<div class="awh-card"><div class="awh-skel-line" style="width:45%"></div><div class="awh-skel-line"></div><div class="awh-skel-line" style="width:70%"></div></div>`;
+ return;
+ }
+ if (state.phase === 'success') { panel.innerHTML = renderSuccess(); wireSuccess(); return; }
+
+ const s = state.status;
+ const isVanity = !!(s && !s.error && s.is_vanity);
+ const combined = state.prefix.length + state.suffix.length;
+ const tooHard = combined > MAX_CHARS;
+ const est = estimate(state.prefix, state.suffix, state.ignoreCase);
+
+ panel.innerHTML = `
+ <div class="awh-card">
+ ${s?.error ? `<div class="awh-err">Couldn’t load wallet. <div class="why">${esc(s.error)}</div></div>` : `
+ <div class="awh-vn-head">
+ <div>
+ <div class="awh-card-h" style="margin-bottom:4px;">Current address ${isVanity ? '<span class="awh-vn-tag">vanity</span>' : ''}</div>
+ <div class="awh-vn-addr">${currentAddrHTML() || '<span class="awh-empty">No wallet yet — grinding one will provision it.</span>'}</div>
+ </div>
+ </div>`}
+
+ <p class="awh-empty" style="margin-top:0;">
+ Grind a custom address for this agent's wallet. You pick the pattern; the key is generated and stored server-side — it never leaves three.ws.
+ </p>
+
+ <div class="awh-vn-grid">
+ <div class="awh-fld">
+ <label for="awh-vn-prefix">Starts with</label>
+ <input class="awh-in awh-mono" id="awh-vn-prefix" autocomplete="off" spellcheck="false" maxlength="3" placeholder="e.g. ${esc((ctx.agent?.name || 'ag').toLowerCase().replace(/[^1-9a-hj-np-za-km-z]/gi, '').slice(0, 3) || 'ag')}" value="${esc(state.prefix)}">
+ </div>
+ <div class="awh-fld">
+ <label for="awh-vn-suffix">Ends with</label>
+ <input class="awh-in awh-mono" id="awh-vn-suffix" autocomplete="off" spellcheck="false" maxlength="3" placeholder="optional" value="${esc(state.suffix)}">
+ </div>
+ </div>
+
+ <label class="awh-vn-toggle">
+ <input type="checkbox" id="awh-vn-ic" ${state.ignoreCase ? 'checked' : ''}>
+ Case-insensitive (faster, matches any capitalization)
+ </label>
+
+ <div class="awh-vn-est ${tooHard ? 'warn' : ''}" id="awh-vn-est">
+ ${combined === 0
+ ? 'Enter a prefix and/or suffix (base58 — no 0, O, I or l).'
+ : tooHard
+ ? `Too hard for instant grinding (${combined} chars). <a href="/vanity-wallet" target="_blank" rel="noopener" style="color:var(--warn,#fbbf24);text-decoration:underline;">Grind up to 8 chars in your browser →</a> and assign it.`
+ : `≈ <b>${est.toLocaleString()}</b> attempts — usually a few seconds.`}
+ </div>
+
+ ${isVanity || (s && !s.error && s.address)
+ ? `<div class="awh-vn-warn">⚠ This replaces the agent's current address. Any SOL or tokens it holds are <b>automatically swept to the new address</b> first — the swap only completes once funds have moved. Apps pointed at the old address must be updated.</div>`
+ : ''}
+
+ <div class="awh-err" id="awh-vn-err" hidden></div>
+ <button class="awh-btn awh-btn--primary" id="awh-vn-go" type="button" style="width:100%;" ${state.phase === 'grinding' ? 'disabled' : ''}>
+ ${state.phase === 'grinding' ? '<span class="awh-spin"></span>Grinding & applying…' : 'Grind &amp; apply vanity address'}
+ </button>
+ </div>`;
+
+ wireForm();
+ }
+
+ function renderSuccess() {
+ const r = state.result || {};
+ const net = ctx.getNetwork();
+ const explorer = net === 'devnet'
+ ? `https://explorer.solana.com/address/${r.address}?cluster=devnet`
+ : `https://solscan.io/account/${r.address}`;
+ const sweptLine = r.swept
+ ? `<div class="awh-empty" style="padding:0 0 8px;">Migrated ${r.swept.sol ? `${r.swept.sol} SOL` : 'funds'}${r.swept.tokens?.length ? ` + ${r.swept.tokens.length} token${r.swept.tokens.length > 1 ? 's' : ''}` : ''} from the old address.</div>`
+ : '';
+ return `
+ <div class="awh-card awh-ok">
+ <div class="ic">✦</div>
+ <div style="font-size:var(--text-md,.8125rem);font-weight:600;color:var(--ink-bright,#fff);margin-bottom:6px;">Vanity address applied</div>
+ <div class="awh-vn-addr" style="margin-bottom:8px;">${(() => {
+ const a = r.address || '';
+ const p = r.vanity_prefix; const sf = r.vanity_suffix;
+ let h = esc(a);
+ if (p && a.startsWith(p)) h = `<b>${esc(p)}</b>${esc(a.slice(p.length))}`;
+ if (sf && a.endsWith(sf)) { const mid = (p && a.startsWith(p) ? a.slice(p.length) : a); h = `${p && a.startsWith(p) ? `<b>${esc(p)}</b>` : ''}${esc(mid.slice(0, mid.length - sf.length))}<b>${esc(sf)}</b>`; }
+ return h;
+ })()}</div>
+ ${sweptLine}
+ ${r.iterations != null ? `<div class="awh-vn-out">Found in ${Number(r.iterations).toLocaleString()} attempts${r.duration_ms != null ? ` · ${(r.duration_ms / 1000).toFixed(1)}s` : ''}</div>` : ''}
+ <div style="margin-top:14px;display:flex;gap:8px;justify-content:center;">
+ <a class="awh-btn awh-btn--primary" href="${esc(explorer)}" target="_blank" rel="noopener" style="text-decoration:none;">View on explorer ↗</a>
+ <button class="awh-btn" id="awh-vn-again" type="button">Change again</button>
+ </div>
+ </div>`;
+ }
+
+ function wireSuccess() {
+ panel.querySelector('#awh-vn-again')?.addEventListener('click', () => {
+ state.phase = 'form'; state.result = null; state.prefix = ''; state.suffix = '';
+ loadStatus();
+ });
+ }
+
+ function wireForm() {
+ const pIn = panel.querySelector('#awh-vn-prefix');
+ const sIn = panel.querySelector('#awh-vn-suffix');
+ const ic = panel.querySelector('#awh-vn-ic');
+ const errEl = panel.querySelector('#awh-vn-err');
+ const estEl = panel.querySelector('#awh-vn-est');
+
+ function clean(v) { return (v || '').replace(/[^1-9A-HJ-NP-Za-km-z]/g, '').slice(0, 3); }
+ function refreshEst() {
+ const combined = state.prefix.length + state.suffix.length;
+ const tooHard = combined > MAX_CHARS;
+ const est = estimate(state.prefix, state.suffix, state.ignoreCase);
+ estEl.className = `awh-vn-est ${tooHard ? 'warn' : ''}`;
+ estEl.innerHTML = combined === 0
+ ? 'Enter a prefix and/or suffix (base58 — no 0, O, I or l).'
+ : tooHard
+ ? `Too hard for instant grinding (${combined} chars). <a href="/vanity-wallet" target="_blank" rel="noopener" style="color:var(--warn,#fbbf24);text-decoration:underline;">Grind up to 8 chars in your browser →</a> and assign it.`
+ : `≈ <b>${est.toLocaleString()}</b> attempts — usually a few seconds.`;
+ }
+ pIn?.addEventListener('input', () => { const c = clean(pIn.value); if (c !== pIn.value) pIn.value = c; state.prefix = c; refreshEst(); });
+ sIn?.addEventListener('input', () => { const c = clean(sIn.value); if (c !== sIn.value) sIn.value = c; state.suffix = c; refreshEst(); });
+ ic?.addEventListener('change', () => { state.ignoreCase = ic.checked; refreshEst(); });
+
+ panel.querySelector('#awh-vn-go')?.addEventListener('click', async () => {
+ errEl.hidden = true;
+ const combined = state.prefix.length + state.suffix.length;
+ if (combined === 0) { errEl.hidden = false; errEl.textContent = 'Enter a prefix and/or suffix first.'; return; }
+ if (combined > MAX_CHARS) { errEl.hidden = false; errEl.textContent = `Server grinding supports up to ${MAX_CHARS} combined characters. Use the browser grinder for longer patterns.`; return; }
+ state.phase = 'grinding';
+ render();
+ const res = await call(base, {
+ method: 'POST',
+ body: { prefix: state.prefix || undefined, suffix: state.suffix || undefined, ignoreCase: state.ignoreCase, network: ctx.getNetwork() },
+ });
+ if (destroyed) return;
+ if (!res.ok) {
+ state.phase = 'form';
+ render();
+ const e = panel.querySelector('#awh-vn-err');
+ if (e) { e.hidden = false; e.textContent = res.message; }
+ return;
+ }
+ state.result = res.data;
+ state.phase = 'success';
+ toast('Vanity address applied');
+ render();
+ });
+ }
+
+ async function loadStatus() {
+ state.status = null;
+ render();
+ const res = await call(base);
+ if (destroyed) return;
+ state.status = res.ok ? res.data : { error: res.message };
+ render();
+ }
+
+ loadStatus();
+
+ return {
+ onShow() { if (state.status === null) loadStatus(); },
+ destroy() { destroyed = true; },
+ };
+ },
+});
diff --git a/src/agent-wallet-hub/tabs/withdraw.js b/src/agent-wallet-hub/tabs/withdraw.js
index 5496dfa5d..007d3fce5 100644
--- a/src/agent-wallet-hub/tabs/withdraw.js
+++ b/src/agent-wallet-hub/tabs/withdraw.js
@@ -20,6 +20,7 @@
import { registerWalletTab } from '../registry.js';
import { formatUsd, explorerTxUrl, explorerAddressUrl } from '../util.js';
+import { consumeCsrfToken } from '../../api.js';
const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
@@ -94,6 +95,12 @@ async function call(url, { method = 'GET', body = null } = {}) {
opts.headers['content-type'] = 'application/json';
opts.body = JSON.stringify(body);
}
+ // State-changing requests (withdraw POST, limits PUT) carry a single-use
+ // CSRF token; reads (GET) don't need one. The server burns the token on use.
+ if (method !== 'GET') {
+ const token = await consumeCsrfToken();
+ if (token) opts.headers['x-csrf-token'] = token;
+ }
const r = await fetch(url, opts);
let j = null;
try { j = await r.json(); } catch { /* empty body */ }
diff --git a/src/shared/agent-wallet-chip.js b/src/shared/agent-wallet-chip.js
new file mode 100644
index 000000000..ebb43120c
--- /dev/null
+++ b/src/shared/agent-wallet-chip.js
@@ -0,0 +1,226 @@
+/**
+ * Single source of truth for an agent's custodial Solana wallet chip.
+ *
+ * Every surface where an agent or avatar is visible — profile, marketplace card,
+ * directory row, avatar page, dashboards, trending, characters — renders the same
+ * wallet chip from this module, so the wallet (and its vanity styling) looks and
+ * behaves identically everywhere. There is no shared agent-card in this codebase
+ * (each surface rolls its own markup), so the consistency lives here.
+ *
+ * A wallet is owned per (user, agent): the creator of an avatar/agent controls its
+ * wallet, and a fork mints a brand-new wallet owned by the forker (see
+ * api/avatars/fork.js). The chip never exposes secret material — only the public
+ * address, its vanity prefix/suffix, a copy action, and an explorer link. For the
+ * owner it also surfaces a "Make it vanity" entry point that routes to the wallet
+ * hub where the grind + money-safe swap happens (POST /api/agents/:id/solana/vanity).
+ *
+ * Reads the address from any agent record shape:
+ * agent.solana_address | agent.meta.solana_address | agent.wallet (base58)
+ * and the vanity pattern from:
+ * agent.solana_vanity_prefix/suffix | agent.meta.solana_vanity_prefix/suffix
+ */
+
+const STYLE_ID = 'tws-agent-wallet-chip-styles';
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+function esc(s) {
+ return String(s == null ? '' : s).replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+/**
+ * Normalize any agent record into a wallet descriptor, or null when there is no
+ * custodial Solana wallet yet.
+ * @returns {null | { address, prefix, suffix, isVanity, explorerUrl, hubUrl, agentId }}
+ */
+export function getWalletStatus(agent) {
+ if (!agent || typeof agent !== 'object') return null;
+ const meta = agent.meta || {};
+ const address =
+ agent.solana_address || meta.solana_address ||
+ (typeof agent.wallet === 'string' && BASE58_RE.test(agent.wallet) ? agent.wallet : null) ||
+ null;
+ if (!address || !BASE58_RE.test(String(address))) return null;
+
+ const prefix = agent.solana_vanity_prefix || meta.solana_vanity_prefix || null;
+ const suffix = agent.solana_vanity_suffix || meta.solana_vanity_suffix || null;
+ const agentId = agent.id || agent.agentId || agent.agent_id || null;
+
+ return {
+ address: String(address),
+ prefix: prefix ? String(prefix) : null,
+ suffix: suffix ? String(suffix) : null,
+ isVanity: !!(prefix || suffix),
+ explorerUrl: `https://solscan.io/account/${address}`,
+ hubUrl: agentId ? `/agent/${agentId}/wallet` : null,
+ agentId,
+ };
+}
+
+/** True when the agent has a custodial Solana wallet. */
+export function hasWallet(agent) {
+ return getWalletStatus(agent) != null;
+}
+
+/** Render the short, vanity-aware address label (prefix/suffix highlighted). */
+function addressLabelHTML(status) {
+ const { address, prefix, suffix } = status;
+ const head = prefix && address.startsWith(prefix) ? prefix : address.slice(0, 4);
+ const tail = suffix && address.endsWith(suffix) ? suffix : address.slice(-4);
+ const headHi = !!(prefix && address.startsWith(prefix));
+ const tailHi = !!(suffix && address.endsWith(suffix));
+ return (
+ `<span class="twc-addr">` +
+ `<span class="${headHi ? 'twc-hi' : ''}">${esc(head)}</span>` +
+ `<span class="twc-dots">…</span>` +
+ `<span class="${tailHi ? 'twc-hi' : ''}">${esc(tail)}</span>` +
+ `</span>`
+ );
+}
+
+/** Inject the shared chip stylesheet once. Idempotent and SSR-safe. */
+export function ensureWalletChipStyles() {
+ if (typeof document === 'undefined') return;
+ if (document.getElementById(STYLE_ID)) return;
+ const style = document.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = `
+.twc{display:inline-flex;align-items:center;gap:7px;padding:3px 9px;border-radius:999px;
+ font:600 11px/1 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;
+ color:#c4b5fd;background:rgba(139,92,246,.1);border:1px solid rgba(139,92,246,.3);
+ white-space:nowrap;vertical-align:middle;max-width:100%;}
+.twc[data-vanity="true"]{color:#a78bfa;background:rgba(139,92,246,.15);border-color:rgba(139,92,246,.5);}
+.twc-ico{width:11px;height:11px;flex:none;opacity:.8;}
+.twc-addr{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.01em;display:inline-flex;gap:1px;}
+.twc-hi{color:#fff;font-weight:700;}
+.twc-dots{opacity:.5;}
+.twc-act{appearance:none;background:none;border:none;padding:0 2px;margin:0;cursor:pointer;color:inherit;
+ opacity:.65;display:inline-flex;align-items:center;transition:opacity .15s ease,transform .12s ease;}
+.twc-act:hover{opacity:1;}
+.twc-act:active{transform:scale(.9);}
+.twc-act:focus-visible{outline:2px solid rgba(139,92,246,.7);outline-offset:2px;border-radius:4px;}
+.twc-act svg{width:12px;height:12px;}
+a.twc-link{color:inherit;text-decoration:none;display:inline-flex;align-items:center;}
+.twc-make{font-weight:600;font-size:10px;color:#a78bfa;text-decoration:none;border-left:1px solid rgba(139,92,246,.3);
+ padding-left:7px;margin-left:1px;white-space:nowrap;transition:color .15s ease;}
+.twc-make:hover{color:#fff;}
+.twc-vanity-tag{font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;opacity:.8;}
+.twc-pending{color:#888;background:rgba(255,255,255,.04);border-color:rgba(255,255,255,.1);}
+.twc-copied{color:#4ade80!important;}
+@media (prefers-reduced-motion: reduce){.twc-act{transition:none;}}
+`;
+ (document.head || document.documentElement).appendChild(style);
+}
+
+const COPY_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
+const LINK_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>';
+const WALLET_SVG = '<svg class="twc-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><path d="M18 12a2 2 0 0 0 0 4h4v-4Z"/></svg>';
+
+/**
+ * Render the wallet chip as an HTML string for template-string render sites
+ * (card grids). Returns a "wallet pending" chip when no address is present yet so
+ * the surface still communicates that every agent has a wallet.
+ *
+ * @param {object} agent Any supported agent record shape.
+ * @param {object} [opts]
+ * @param {boolean} [opts.isOwner=false] Show the "Make it vanity" entry point.
+ * @param {boolean} [opts.showPending=true] Render a pending chip when no wallet.
+ * @param {boolean} [opts.link=true] Make the address a copy/explorer affordance.
+ */
+export function walletChipHTML(agent, opts = {}) {
+ ensureWalletChipStyles();
+ const { isOwner = false, showPending = true, link = true } = opts;
+ const status = getWalletStatus(agent);
+
+ if (!status) {
+ if (!showPending) return '';
+ return `<span class="twc twc-pending" title="Wallet provisioning">${WALLET_SVG}<span>Wallet pending</span></span>`;
+ }
+
+ const vanityTag = status.isVanity ? '<span class="twc-vanity-tag">vanity</span>' : '';
+ const copyBtn = link
+ ? `<button type="button" class="twc-act" data-twc-copy="${esc(status.address)}" title="Copy address" aria-label="Copy wallet address">${COPY_SVG}</button>`
+ : '';
+ const explorerLink = link
+ ? `<a class="twc-act twc-link" href="${esc(status.explorerUrl)}" target="_blank" rel="noopener noreferrer" title="View on Solscan" aria-label="View wallet on Solscan" data-twc-stop>${LINK_SVG}</a>`
+ : '';
+ const makeVanity =
+ isOwner && !status.isVanity && status.hubUrl
+ ? `<a class="twc-make" href="${esc(status.hubUrl)}#vanity" title="Grind a custom vanity address" data-twc-stop>✦ Vanity</a>`
+ : '';
+
+ const title = `Agent wallet ${status.address}${status.isVanity ? ' (vanity)' : ''}`;
+ return (
+ `<span class="twc" data-vanity="${status.isVanity}" title="${esc(title)}">` +
+ WALLET_SVG +
+ addressLabelHTML(status) +
+ vanityTag +
+ copyBtn +
+ explorerLink +
+ makeVanity +
+ `</span>`
+ );
+}
+
+/**
+ * Render the wallet chip as a wired DOM node (copy button works, links don't
+ * bubble to a parent card handler). Returns null only when there's no wallet and
+ * showPending is false.
+ */
+export function walletChipEl(agent, opts = {}) {
+ const html = walletChipHTML(agent, opts);
+ if (!html) return null;
+ const tpl = document.createElement('template');
+ tpl.innerHTML = html.trim();
+ const node = tpl.content.firstElementChild;
+ if (node) wireWalletChip(node);
+ return node;
+}
+
+/**
+ * Wire copy buttons and stop-propagation links inside a container that holds one
+ * or more chips rendered as HTML strings. Call this once after injecting card
+ * markup that used walletChipHTML(). Idempotent per element.
+ */
+export function wireWalletChips(root) {
+ if (!root || typeof root.querySelectorAll !== 'function') return;
+ for (const el of root.querySelectorAll('[data-twc-copy],[data-twc-stop]')) {
+ wireWalletChip(el.closest('.twc') || el);
+ }
+}
+
+function wireWalletChip(node) {
+ if (!node || node.__twcWired) return;
+ node.__twcWired = true;
+ for (const stop of node.querySelectorAll?.('[data-twc-stop]') || []) {
+ stop.addEventListener('click', (e) => e.stopPropagation());
+ }
+ const btn = node.matches?.('[data-twc-copy]') ? node : node.querySelector?.('[data-twc-copy]');
+ if (btn) {
+ btn.addEventListener('click', async (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const addr = btn.getAttribute('data-twc-copy');
+ try {
+ await navigator.clipboard.writeText(addr);
+ const prev = btn.innerHTML;
+ btn.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>';
+ btn.classList.add('twc-copied');
+ setTimeout(() => {
+ btn.innerHTML = prev;
+ btn.classList.remove('twc-copied');
+ }, 1400);
+ } catch {
+ /* clipboard denied — no-op, the address is visible in the chip */
+ }
+ });
+ }
+}
+
+if (typeof window !== 'undefined') {
+ window.twsAgentWalletChip = {
+ getWalletStatus, hasWallet, walletChipHTML, walletChipEl, wireWalletChips, ensureWalletChipStyles,
+ };
+}
diff --git a/tasks/irl-production/04-webxr-session-lifecycle.md b/tasks/irl-production/04-webxr-session-lifecycle.md
deleted file mode 100644
index 23d2dac98..000000000
--- a/tasks/irl-production/04-webxr-session-lifecycle.md
+++ /dev/null
@@ -1,67 +0,0 @@
-# Task 04 — WebXR session lifecycle and camera contention
-
-**Phase:** 1 (AR correctness) · **Effort:** M · **Files:** `src/irl.js`, `src/ar/webxr.js`, `pages/irl.html`
-
-## Why
-On WebXR-capable devices (mainly Android Chrome) the "Place on floor" flow starts
-an immersive session that owns the camera and a separate animation loop, while the
-gyro+GPS path owns `getUserMedia` and the RAF tick. If these two overlap — double
-camera acquisition, RAF not paused/resumed, overlay left interactive — the user
-hits a black screen, a dangling camera track, or dead taps.
-
-## Read first (verify before fixing)
-- `enterFloorAnchor()` / XR start + the `WebXRSession` shim — `src/irl.js:~1475-1610`
-- `enableAR()` / `disableAR()` camera ownership — `src/irl.js:279-396`
-- The single RAF owner (`xrViewer._rafId`, `startTick`) — `src/irl.js:~1502-1513`, `tick()` end
-- XR overlay markup + z-index/pointer-events — `pages/irl.html` `#irl-xr-overlay`, `#irl-xr-error`
-- `src/ar/webxr.js` session start/end + clear-color restore
-
-## Scope — confirm, then fix
-
-1. **AR↔XR transition guard.** Entering the floor-anchor flow calls `disableAR()` to
- release `getUserMedia`; a fast tap on Camera AR during the async XR startup can
- re-acquire the camera and collide. Add a single `_arTransitioning` guard that
- blocks both `enableAR()` and the XR entry until the prior op fully settles
- (camera tracks stopped, session started/ended). Make teardown deterministic.
-
-2. **RAF pause/resume correctness.** Confirm the IRL `tick()` RAF is cancelled while
- the XR animation loop runs and is restarted exactly once on session end (no
- double-tick, no frozen scene). Verify `xrViewer._rafId` is the sole handle.
-
-3. **Overlay tap absorption.** Ensure `#irl-xr-overlay` is hidden immediately on
- session end and that its hit areas never sit above the canvas while AR/gyro mode
- is active. Add a guard in the tap handler to early-return when the overlay is
- visible.
-
-4. **Clear color / background restore.** `WebXRSession` restores an opaque clear
- color on exit; IRL must re-assert the transparent AR clear color and `groundShadow`
- visibility so passthrough resumes correctly.
-
-5. **Unsupported path stays clean.** iOS Safari (no `immersive-ar`) must never reveal
- the floor-anchor button or hit any XR code — confirm the support gate and that
- failures route to the designed "use Pin here instead" state, not a toast.
-
-## Out of scope
-Pin persistence schema (shipped); gyro/GPS math (tasks 01–03).
-
-## Definition of done
-- [ ] Rapidly toggling Camera AR ↔ Place on floor never double-acquires the camera,
- black-screens, or leaves a dangling track (manual, Android Chrome).
-- [ ] Scene resumes live (not frozen) after exiting an XR session; single RAF.
-- [ ] No dead taps after XR exit; overlay fully dismissed.
-- [ ] iOS Safari never sees or touches XR code.
-- [ ] esbuild clean; `npm test` green; changelog entry if user-visible.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/irl-production/04-webxr-session-lifecycle.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.