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: avatar wallet chat page + agent API, wallet gen/verify scripts

nirholasac64926afff0
diff --git a/api/_lib/avatar-wallet.js b/api/_lib/avatar-wallet.js
new file mode 100644
index 000000000..a43ed93bb
--- /dev/null
+++ b/api/_lib/avatar-wallet.js
@@ -0,0 +1,220 @@
+// Avatar demo wallet — a single custodial Solana wallet that an embeddable
+// 3D-avatar widget owns and can autonomously spend from (see
+// /api/agent/wallet, /api/agent/send-sol and pages/avatar-wallet-chat.html).
+//
+// Security model (deliberately scoped for a low-value demo wallet):
+// - The signing secret never leaves the server — it lives only in the
+// AVATAR_WALLET_SECRET env var and is loaded on demand to sign.
+// - Every send is hard-capped at AVATAR_MAX_SEND_USD (default $2) so a
+// compromised/abused widget can move at most a couple of dollars per call.
+// - The recipient is validated as a real base58 pubkey; an optional
+// AVATAR_DEFAULT_RECIPIENT is the "send me" target when none is given.
+// - Fund this wallet with only a few dollars of SOL. It is a demo wallet,
+// not a treasury.
+
+import {
+ Connection,
+ Keypair,
+ LAMPORTS_PER_SOL,
+ PublicKey,
+ SystemProgram,
+ Transaction,
+ TransactionInstruction,
+} from '@solana/web3.js';
+import bs58 from 'bs58';
+
+const bs58decode = bs58.default ? bs58.default.decode : bs58.decode;
+
+// SPL Memo program — used to stamp every avatar payment on-chain so the
+// transaction is self-describing in an explorer.
+const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');
+
+const DEFAULT_MAINNET_RPC = 'https://api.mainnet-beta.solana.com';
+const DEFAULT_DEVNET_RPC = 'https://api.devnet.solana.com';
+
+/**
+ * Parse a Solana secret key from any of the common encodings into a Keypair:
+ * - JSON byte array ("[12,34,...]")
+ * - base58 string (Phantom export format)
+ * - base64 string (64-byte secret)
+ * Throws a tagged error if no/invalid secret is supplied.
+ */
+export function loadAvatarKeypair(secret) {
+ const trimmed = (secret || '').trim();
+ if (!trimmed) {
+ throw Object.assign(new Error('avatar wallet not configured (set AVATAR_WALLET_SECRET)'), {
+ code: 'no_wallet',
+ });
+ }
+
+ let bytes = null;
+ if (trimmed.startsWith('[')) {
+ bytes = Uint8Array.from(JSON.parse(trimmed));
+ } else {
+ // Try base58 first (Phantom), then base64. A 64-byte result wins.
+ for (const decode of [() => bs58decode(trimmed), () => new Uint8Array(Buffer.from(trimmed, 'base64'))]) {
+ try {
+ const b = decode();
+ if (b && b.length === 64) {
+ bytes = b;
+ break;
+ }
+ } catch {
+ /* try next encoding */
+ }
+ }
+ }
+
+ if (!bytes || bytes.length !== 64) {
+ throw Object.assign(new Error('invalid AVATAR_WALLET_SECRET (expected a 64-byte base58/base64/json secret key)'), {
+ code: 'bad_wallet',
+ });
+ }
+ return Keypair.fromSecretKey(Uint8Array.from(bytes));
+}
+
+/** Resolve the avatar wallet configuration from the environment. */
+export function avatarWalletConfig() {
+ const secret = process.env.AVATAR_WALLET_SECRET || '';
+ const network = (process.env.AVATAR_NETWORK || 'mainnet').toLowerCase() === 'devnet' ? 'devnet' : 'mainnet';
+ const rpcUrl =
+ network === 'devnet'
+ ? process.env.SOLANA_RPC_URL_DEVNET || DEFAULT_DEVNET_RPC
+ : process.env.SOLANA_RPC_URL || DEFAULT_MAINNET_RPC;
+
+ const maxSendUsd = clampNumber(parseFloat(process.env.AVATAR_MAX_SEND_USD || '2'), 0.01, 100);
+ const defaultRecipient = (process.env.AVATAR_DEFAULT_RECIPIENT || '').trim() || null;
+ const demoToken = (process.env.AVATAR_DEMO_TOKEN || '').trim() || null;
+
+ let address = null;
+ let configured = false;
+ if (secret) {
+ try {
+ address = loadAvatarKeypair(secret).publicKey.toBase58();
+ configured = true;
+ } catch {
+ configured = false;
+ }
+ }
+
+ return { configured, address, network, rpcUrl, maxSendUsd, defaultRecipient, demoToken };
+}
+
+/** True when `s` is a parseable Solana public key. */
+export function isValidPubkey(s) {
+ try {
+ // eslint-disable-next-line no-new
+ new PublicKey(String(s));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+let _connByUrl = new Map();
+export function getConnection(rpcUrl) {
+ const url = rpcUrl || DEFAULT_MAINNET_RPC;
+ if (!_connByUrl.has(url)) _connByUrl.set(url, new Connection(url, 'confirmed'));
+ return _connByUrl.get(url);
+}
+
+/** Live SOL/USD price (Jupiter Lite primary, CoinGecko fallback). */
+export async function solUsdPrice() {
+ const SOL_MINT = 'So11111111111111111111111111111111111111112';
+ try {
+ const r = await fetch(`https://lite-api.jup.ag/price/v3?ids=${SOL_MINT}`);
+ if (r.ok) {
+ const data = await r.json();
+ const usd = data?.[SOL_MINT]?.usdPrice ?? data?.[SOL_MINT]?.price ?? 0;
+ if (Number(usd) > 0) return Number(usd);
+ }
+ } catch {
+ /* fall through */
+ }
+ const cg = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd');
+ if (!cg.ok) throw Object.assign(new Error('SOL price unavailable'), { code: 'price_unavailable' });
+ const j = await cg.json();
+ const usd = j?.solana?.usd ?? 0;
+ if (!(Number(usd) > 0)) throw Object.assign(new Error('SOL price unavailable'), { code: 'price_unavailable' });
+ return Number(usd);
+}
+
+/** Native SOL balance (lamports + SOL) for a pubkey on the given connection. */
+export async function getSolBalance(connection, pubkey) {
+ const pk = pubkey instanceof PublicKey ? pubkey : new PublicKey(pubkey);
+ const lamports = await connection.getBalance(pk, 'confirmed');
+ return { lamports, sol: lamports / LAMPORTS_PER_SOL };
+}
+
+/**
+ * Build and locally sign a native SOL transfer (with an optional memo) against
+ * the given recent blockhash. Returns the signed Transaction without
+ * broadcasting — split out from sendSol so the exact tx the endpoint submits
+ * can be verified offline (see scripts/verify-send-sol.mjs).
+ */
+export function buildSignedSolTransfer({ fromKeypair, to, lamports, memo, blockhash }) {
+ const toPubkey = to instanceof PublicKey ? to : new PublicKey(to);
+ const lamportsInt = Math.round(Number(lamports));
+ if (!Number.isFinite(lamportsInt) || lamportsInt <= 0) {
+ throw Object.assign(new Error('transfer amount must be a positive number of lamports'), { code: 'bad_amount' });
+ }
+
+ const tx = new Transaction();
+ tx.add(
+ SystemProgram.transfer({
+ fromPubkey: fromKeypair.publicKey,
+ toPubkey,
+ lamports: lamportsInt,
+ }),
+ );
+ if (memo) {
+ tx.add(
+ new TransactionInstruction({
+ programId: MEMO_PROGRAM_ID,
+ keys: [],
+ data: Buffer.from(String(memo).slice(0, 180), 'utf8'),
+ }),
+ );
+ }
+
+ tx.feePayer = fromKeypair.publicKey;
+ tx.recentBlockhash = blockhash;
+ tx.sign(fromKeypair);
+ return tx;
+}
+
+/**
+ * Sign and submit a native SOL transfer, waiting for `confirmed` commitment.
+ * Returns the transaction signature. This is the single money-moving primitive
+ * shared by the /api/agent/send-sol endpoint and the verification script.
+ */
+export async function sendSol({ connection, fromKeypair, to, lamports, memo }) {
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
+ const tx = buildSignedSolTransfer({ fromKeypair, to, lamports, memo, blockhash });
+
+ const signature = await connection.sendRawTransaction(tx.serialize(), {
+ skipPreflight: false,
+ maxRetries: 3,
+ });
+ await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');
+ return signature;
+}
+
+/** Build the Solscan URL for a signature on the active network. */
+export function explorerTxUrl(signature, network) {
+ const cluster = network === 'devnet' ? '?cluster=devnet' : '';
+ return `https://solscan.io/tx/${signature}${cluster}`;
+}
+
+/** Build the Solscan account URL for an address on the active network. */
+export function explorerAccountUrl(address, network) {
+ const cluster = network === 'devnet' ? '?cluster=devnet' : '';
+ return `https://solscan.io/account/${address}${cluster}`;
+}
+
+function clampNumber(n, min, max) {
+ if (!Number.isFinite(n)) return min;
+ return Math.min(max, Math.max(min, n));
+}
+
+export { LAMPORTS_PER_SOL, PublicKey };
diff --git a/api/agent/send-sol.js b/api/agent/send-sol.js
new file mode 100644
index 000000000..ba6700bf1
--- /dev/null
+++ b/api/agent/send-sol.js
@@ -0,0 +1,145 @@
+// POST /api/agent/send-sol — the avatar widget's autonomous payout.
+//
+// The avatar holds a custodial Solana wallet (AVATAR_WALLET_SECRET). When the
+// chat brain decides to pay (the `sendSol` tool) or a user clicks "send", the
+// widget calls this endpoint. It converts a USD amount to SOL at the live
+// price, signs with the avatar's key server-side, submits on-chain, and returns
+// the confirmed signature.
+//
+// Body: { usd?: number, sol?: number, to?: string, memo?: string }
+// - Exactly one of `usd` / `sol` is required (USD preferred).
+// - `to` omitted → AVATAR_DEFAULT_RECIPIENT ("send me").
+// Guardrails: per-call USD cap (AVATAR_MAX_SEND_USD), pubkey validation,
+// IP rate-limit, optional shared-secret header (AVATAR_DEMO_TOKEN).
+
+import { z } from 'zod';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { parse } from '../_lib/validate.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import {
+ avatarWalletConfig,
+ loadAvatarKeypair,
+ getConnection,
+ getSolBalance,
+ solUsdPrice,
+ sendSol,
+ isValidPubkey,
+ explorerTxUrl,
+ explorerAccountUrl,
+ LAMPORTS_PER_SOL,
+} from '../_lib/avatar-wallet.js';
+
+// A confirmed transfer leaves headroom for the signature fee (5000 lamports)
+// plus a small priority cushion so the avatar never drains itself below fees.
+const FEE_BUFFER_LAMPORTS = 15_000;
+
+const bodySchema = z
+ .object({
+ usd: z.number().positive().max(1000).optional(),
+ sol: z.number().positive().max(100).optional(),
+ to: z.string().trim().min(32).max(64).optional(),
+ memo: z.string().trim().max(160).optional(),
+ })
+ .refine((b) => b.usd != null || b.sol != null, {
+ message: 'provide `usd` or `sol`',
+ });
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const cfg = avatarWalletConfig();
+ if (!cfg.configured) {
+ return error(
+ res,
+ 503,
+ 'wallet_unconfigured',
+ 'avatar wallet is not configured — set AVATAR_WALLET_SECRET (run scripts/gen-avatar-wallet.mjs)',
+ );
+ }
+
+ // Optional shared-secret gate. When set, the widget must echo it.
+ if (cfg.demoToken) {
+ const provided = req.headers['x-avatar-token'];
+ if (provided !== cfg.demoToken) {
+ return error(res, 401, 'unauthorized', 'missing or invalid x-avatar-token');
+ }
+ }
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many payout requests, try again shortly');
+
+ const body = parse(bodySchema, await readJson(req));
+
+ const recipient = body.to || cfg.defaultRecipient;
+ if (!recipient) {
+ return error(res, 400, 'no_recipient', 'no recipient — pass `to` or set AVATAR_DEFAULT_RECIPIENT');
+ }
+ if (!isValidPubkey(recipient)) {
+ return error(res, 400, 'bad_recipient', 'recipient is not a valid Solana address');
+ }
+
+ let solPriceUsd;
+ try {
+ solPriceUsd = await solUsdPrice();
+ } catch {
+ return error(res, 502, 'price_unavailable', 'could not fetch the live SOL price, try again shortly');
+ }
+
+ // Resolve the amount in both USD and lamports, then enforce the USD cap.
+ const usd = body.usd != null ? body.usd : body.sol * solPriceUsd;
+ if (usd > cfg.maxSendUsd) {
+ return error(
+ res,
+ 400,
+ 'amount_too_large',
+ `amount $${usd.toFixed(2)} exceeds the per-send cap of $${cfg.maxSendUsd.toFixed(2)}`,
+ );
+ }
+ const solAmount = body.sol != null ? body.sol : usd / solPriceUsd;
+ const lamports = Math.round(solAmount * LAMPORTS_PER_SOL);
+ if (lamports <= 0) {
+ return error(res, 400, 'amount_too_small', 'amount rounds to zero lamports');
+ }
+
+ const connection = getConnection(cfg.rpcUrl);
+ const keypair = loadAvatarKeypair(process.env.AVATAR_WALLET_SECRET);
+
+ // Balance guard — fail clearly before signing if the wallet can't cover it.
+ const { lamports: balance } = await getSolBalance(connection, keypair.publicKey);
+ if (balance < lamports + FEE_BUFFER_LAMPORTS) {
+ return error(
+ res,
+ 409,
+ 'insufficient_funds',
+ `avatar wallet has ${(balance / LAMPORTS_PER_SOL).toFixed(5)} SOL — needs ~${((lamports + FEE_BUFFER_LAMPORTS) / LAMPORTS_PER_SOL).toFixed(5)} SOL. Fund ${cfg.address}.`,
+ { address: cfg.address, fundUrl: explorerAccountUrl(cfg.address, cfg.network) },
+ );
+ }
+
+ let signature;
+ try {
+ signature = await sendSol({
+ connection,
+ fromKeypair: keypair,
+ to: recipient,
+ lamports,
+ memo: body.memo || `three.ws avatar · $${usd.toFixed(2)} SOL`,
+ });
+ } catch (err) {
+ return error(res, 502, 'send_failed', `on-chain transfer failed: ${err?.message || 'unknown error'}`);
+ }
+
+ return json(res, 200, {
+ ok: true,
+ signature,
+ network: cfg.network,
+ from: cfg.address,
+ to: recipient,
+ lamports,
+ sol: solAmount,
+ usd,
+ solPriceUsd,
+ explorer: explorerTxUrl(signature, cfg.network),
+ });
+});
diff --git a/api/agent/wallet.js b/api/agent/wallet.js
new file mode 100644
index 000000000..16541cbbb
--- /dev/null
+++ b/api/agent/wallet.js
@@ -0,0 +1,53 @@
+// GET /api/agent/wallet — public read of the avatar's custodial wallet.
+//
+// Returns the avatar wallet address, network, live SOL balance and USD value,
+// the per-send cap and the default recipient. No secrets are exposed. The
+// widget polls this to render the wallet chip and refresh after a payout.
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import {
+ avatarWalletConfig,
+ getConnection,
+ getSolBalance,
+ solUsdPrice,
+ explorerAccountUrl,
+} from '../_lib/avatar-wallet.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const cfg = avatarWalletConfig();
+ if (!cfg.configured) {
+ return error(
+ res,
+ 503,
+ 'wallet_unconfigured',
+ 'avatar wallet is not configured — set AVATAR_WALLET_SECRET (run scripts/gen-avatar-wallet.mjs)',
+ );
+ }
+
+ const connection = getConnection(cfg.rpcUrl);
+ const [{ lamports, sol }, solPriceUsd] = await Promise.all([
+ getSolBalance(connection, cfg.address),
+ solUsdPrice().catch(() => 0),
+ ]);
+
+ return json(
+ res,
+ 200,
+ {
+ address: cfg.address,
+ network: cfg.network,
+ lamports,
+ sol,
+ usd: solPriceUsd ? sol * solPriceUsd : null,
+ solPriceUsd: solPriceUsd || null,
+ maxSendUsd: cfg.maxSendUsd,
+ defaultRecipient: cfg.defaultRecipient,
+ explorer: explorerAccountUrl(cfg.address, cfg.network),
+ },
+ // Short cache so the chip feels live without hammering the RPC.
+ { 'Cache-Control': 'public, max-age=10' },
+ );
+});
diff --git a/api/chat.js b/api/chat.js
index 23f317884..c6357e665 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -258,6 +258,29 @@ const ACTION_TOOLS = [
required: ['name'],
},
},
+ {
+ name: 'sendSol',
+ description:
+ 'Send a small amount of SOL from the avatar\'s own Solana wallet to a recipient, denominated in US dollars. ' +
+ 'Call this ONLY when the user explicitly asks the avatar to send, pay, or transfer SOL. ' +
+ 'If the user says "send me" (or gives no address), omit `to` — the configured default recipient is used. ' +
+ 'The host enforces a per-send dollar cap, so request the amount the user named.',
+ input_schema: {
+ type: 'object',
+ properties: {
+ usd: {
+ type: 'number',
+ description: 'US-dollar value of SOL to send, e.g. 1 for "$1 of SOL".',
+ },
+ to: {
+ type: 'string',
+ description:
+ 'Recipient Solana address (base58). Omit to send to the configured default recipient ("me").',
+ },
+ },
+ required: ['usd'],
+ },
+ },
];
const ACTION_NAMES = new Set(ACTION_TOOLS.map((t) => t.name));
@@ -843,6 +866,7 @@ function buildSystemPrompt(ctx = {}, personaPrompt = null) {
'You can control animations and the scene. When the user asks you to dance, wave, jump, celebrate, etc — call the playAnimation tool IMMEDIATELY. When asked to change the background, call setBgColor with a CSS hex. When asked to change lighting, call setEnvironment.',
'Available animations: wave, dance, capoeira, jump, thriller, pray, idle, celebrate, rumba, falling, kiss, taunt.',
'You can also show the latest trades from pump.fun by calling the getPumpFunTrades tool.',
+ 'You hold your own Solana wallet. When — and only when — the user explicitly asks you to send, pay, or transfer SOL, call the sendSol tool with the dollar amount they named (omit `to` for "send me"). Never offer or send SOL unprompted. After a send, react with a short, delighted confirmation.',
'When the user asks to change the viewer ("enable wireframe", "make the background dark blue", "turn on auto rotate", "load this model"), CALL the matching tool — do not just describe what would happen.',
'When asked about the loaded model, use the context below as ground truth. Do not invent stats.',
'Keep replies tight: 2–3 sentences. Plain text, no markdown headers, no emoji.',
diff --git a/packages/ibm-watsonx-mcp/src/index.js b/packages/ibm-watsonx-mcp/src/index.js
old mode 100644
new mode 100755
diff --git a/packages/pumpfun-mcp/src/index.js b/packages/pumpfun-mcp/src/index.js
old mode 100644
new mode 100755
diff --git a/pages/avatar-wallet-chat.html b/pages/avatar-wallet-chat.html
new file mode 100644
index 000000000..88ad956ca
--- /dev/null
+++ b/pages/avatar-wallet-chat.html
@@ -0,0 +1,617 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>three.ws — Avatar Wallet</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
+ <meta name="description" content="An embeddable 3D AI avatar that holds a Solana wallet, chats, and can autonomously send SOL." />
+ <meta name="robots" content="noindex" />
+ <style>
+ :root {
+ --accent: #7c5cff;
+ --accent-soft: rgba(124, 92, 255, 0.16);
+ --bg-0: #0a0a12;
+ --bg-1: #12101f;
+ --panel: rgba(255, 255, 255, 0.04);
+ --panel-border: rgba(255, 255, 255, 0.09);
+ --text: #f3f2fb;
+ --text-dim: #a4a2bd;
+ --text-faint: #6f6d86;
+ --ok: #3ad08a;
+ --err: #ff6b6b;
+ --radius: 16px;
+ --shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
+ }
+ * { box-sizing: border-box; }
+ html, body {
+ margin: 0;
+ height: 100%;
+ width: 100%;
+ overflow: hidden;
+ font-family: 'Inter', system-ui, -apple-system, sans-serif;
+ color: var(--text);
+ background:
+ radial-gradient(120% 90% at 50% -10%, rgba(124, 92, 255, 0.22), transparent 60%),
+ linear-gradient(180deg, var(--bg-1), var(--bg-0));
+ -webkit-font-smoothing: antialiased;
+ }
+ #app {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ width: 100%;
+ position: relative;
+ }
+
+ /* ── Stage (avatar) ─────────────────────────────────────────── */
+ #stage {
+ position: relative;
+ flex: 1 1 auto;
+ min-height: 0;
+ }
+ #avatar-frame {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ border: 0;
+ display: block;
+ }
+ #stage-fade {
+ position: absolute;
+ left: 0; right: 0; bottom: 0;
+ height: 110px;
+ background: linear-gradient(180deg, transparent, var(--bg-0));
+ pointer-events: none;
+ }
+
+ /* ── Wallet chip ────────────────────────────────────────────── */
+ #wallet {
+ position: absolute;
+ top: 14px;
+ left: 14px;
+ right: 14px;
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 10px 12px;
+ background: rgba(12, 11, 22, 0.62);
+ backdrop-filter: blur(14px);
+ -webkit-backdrop-filter: blur(14px);
+ border: 1px solid var(--panel-border);
+ border-radius: 14px;
+ box-shadow: var(--shadow);
+ z-index: 3;
+ }
+ #wallet .net {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--text-dim);
+ padding: 4px 8px;
+ border-radius: 999px;
+ background: var(--accent-soft);
+ white-space: nowrap;
+ }
+ #wallet .net .dot {
+ width: 7px; height: 7px; border-radius: 50%;
+ background: var(--accent);
+ box-shadow: 0 0 0 3px rgba(124, 92, 255, 0.25);
+ }
+ #wallet .net.mainnet .dot { background: var(--ok); box-shadow: 0 0 0 3px rgba(58, 208, 138, 0.22); }
+ #wallet .bal { display: flex; flex-direction: column; line-height: 1.25; min-width: 0; }
+ #wallet .bal .amt { font-size: 15px; font-weight: 700; font-variant-numeric: tabular-nums; }
+ #wallet .bal .usd { font-size: 12px; color: var(--text-dim); font-variant-numeric: tabular-nums; }
+ #wallet .skel {
+ display: inline-block; height: 14px; width: 96px; border-radius: 6px;
+ background: linear-gradient(90deg, rgba(255,255,255,0.06), rgba(255,255,255,0.14), rgba(255,255,255,0.06));
+ background-size: 200% 100%;
+ animation: shimmer 1.2s linear infinite;
+ }
+ @keyframes shimmer { to { background-position: -200% 0; } }
+ #wallet .addr {
+ margin-left: auto;
+ display: inline-flex; align-items: center; gap: 6px;
+ font-size: 12px; color: var(--text-dim);
+ font-variant-numeric: tabular-nums;
+ text-decoration: none;
+ }
+ #wallet .addr:hover { color: var(--text); }
+ #wallet .copy {
+ border: 1px solid var(--panel-border);
+ background: transparent;
+ color: var(--text-dim);
+ border-radius: 8px;
+ padding: 5px 7px;
+ cursor: pointer;
+ line-height: 0;
+ transition: background 0.15s, color 0.15s, border-color 0.15s;
+ }
+ #wallet .copy:hover { background: var(--panel); color: var(--text); border-color: var(--accent); }
+ #wallet .copy:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ #wallet .copy.done { color: var(--ok); border-color: var(--ok); }
+
+ /* ── Chat ───────────────────────────────────────────────────── */
+ #chat {
+ flex: 0 0 46%;
+ min-height: 220px;
+ display: flex;
+ flex-direction: column;
+ border-top: 1px solid var(--panel-border);
+ background: rgba(8, 8, 14, 0.72);
+ backdrop-filter: blur(8px);
+ }
+ #log {
+ flex: 1 1 auto;
+ overflow-y: auto;
+ padding: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ scrollbar-width: thin;
+ scrollbar-color: rgba(255,255,255,0.16) transparent;
+ }
+ #log::-webkit-scrollbar { width: 8px; }
+ #log::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.14); border-radius: 8px; }
+ .msg {
+ max-width: 84%;
+ padding: 10px 13px;
+ border-radius: 14px;
+ font-size: 14px;
+ line-height: 1.5;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ animation: rise 0.25s ease both;
+ }
+ @keyframes rise { from { opacity: 0; transform: translateY(6px); } }
+ .msg.user {
+ align-self: flex-end;
+ background: var(--accent);
+ color: #fff;
+ border-bottom-right-radius: 4px;
+ }
+ .msg.bot {
+ align-self: flex-start;
+ background: var(--panel);
+ border: 1px solid var(--panel-border);
+ border-bottom-left-radius: 4px;
+ }
+ .msg.bot .cursor { display: inline-block; width: 7px; animation: blink 1s steps(2) infinite; }
+ @keyframes blink { 50% { opacity: 0; } }
+
+ /* Empty state */
+ #empty {
+ margin: auto;
+ text-align: center;
+ color: var(--text-dim);
+ max-width: 320px;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ align-items: center;
+ }
+ #empty h2 { font-size: 16px; margin: 0; color: var(--text); font-weight: 700; }
+ #empty p { margin: 0; font-size: 13px; line-height: 1.5; }
+ .chips { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; }
+ .chip {
+ border: 1px solid var(--panel-border);
+ background: var(--panel);
+ color: var(--text);
+ border-radius: 999px;
+ padding: 8px 13px;
+ font-size: 13px;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s, transform 0.1s;
+ }
+ .chip:hover { background: var(--accent-soft); border-color: var(--accent); }
+ .chip:active { transform: scale(0.97); }
+ .chip:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+
+ /* Payment card */
+ .pay {
+ align-self: flex-start;
+ width: 84%;
+ max-width: 360px;
+ border-radius: 14px;
+ border: 1px solid var(--panel-border);
+ background: linear-gradient(160deg, rgba(124,92,255,0.14), rgba(255,255,255,0.03));
+ padding: 14px;
+ animation: rise 0.25s ease both;
+ }
+ .pay .head { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 700; }
+ .pay .head .ic { font-size: 16px; }
+ .pay .amt { font-size: 26px; font-weight: 800; margin: 8px 0 2px; font-variant-numeric: tabular-nums; }
+ .pay .sub { font-size: 12px; color: var(--text-dim); }
+ .pay .status {
+ margin-top: 10px; display: flex; align-items: center; gap: 7px;
+ font-size: 12px; font-weight: 600;
+ }
+ .pay .status .pip { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); }
+ .pay.pending .pip { animation: pulse 1s ease-in-out infinite; }
+ @keyframes pulse { 50% { opacity: 0.35; transform: scale(0.8); } }
+ .pay.ok .pip { background: var(--ok); animation: none; }
+ .pay.ok .status { color: var(--ok); }
+ .pay.fail .pip { background: var(--err); animation: none; }
+ .pay.fail .status { color: var(--err); }
+ .pay a.sig {
+ display: inline-flex; align-items: center; gap: 5px;
+ margin-top: 10px; font-size: 12px; color: var(--accent);
+ text-decoration: none; font-variant-numeric: tabular-nums;
+ }
+ .pay a.sig:hover { text-decoration: underline; }
+
+ /* Composer */
+ #composer {
+ display: flex;
+ gap: 8px;
+ padding: 12px;
+ border-top: 1px solid var(--panel-border);
+ }
+ #input {
+ flex: 1 1 auto;
+ background: var(--panel);
+ border: 1px solid var(--panel-border);
+ color: var(--text);
+ padding: 11px 14px;
+ border-radius: 12px;
+ font-size: 14px;
+ font-family: inherit;
+ outline: none;
+ transition: border-color 0.15s, background 0.15s;
+ }
+ #input::placeholder { color: var(--text-faint); }
+ #input:focus { border-color: var(--accent); background: rgba(124,92,255,0.07); }
+ #send {
+ flex: 0 0 auto;
+ background: var(--accent);
+ color: #fff;
+ border: none;
+ width: 44px;
+ border-radius: 12px;
+ cursor: pointer;
+ display: grid;
+ place-items: center;
+ transition: filter 0.15s, transform 0.1s;
+ }
+ #send:hover { filter: brightness(1.12); }
+ #send:active { transform: scale(0.94); }
+ #send:disabled { opacity: 0.45; cursor: not-allowed; }
+ #send:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+
+ /* Toast */
+ #toast {
+ position: absolute;
+ bottom: 84px;
+ left: 50%;
+ transform: translateX(-50%) translateY(12px);
+ background: var(--err);
+ color: #fff;
+ padding: 10px 16px;
+ border-radius: 12px;
+ font-size: 13px;
+ font-weight: 600;
+ box-shadow: var(--shadow);
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.25s, transform 0.25s;
+ z-index: 5;
+ max-width: 86%;
+ text-align: center;
+ }
+ #toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
+
+ @media (max-width: 520px) {
+ #chat { flex-basis: 52%; }
+ .msg { max-width: 90%; }
+ }
+ </style>
+ </head>
+ <body>
+ <div id="app">
+ <div id="stage">
+ <iframe id="avatar-frame" title="3D avatar" allow="autoplay; microphone; camera"></iframe>
+ <div id="stage-fade"></div>
+ <div id="wallet" aria-live="polite">
+ <span class="net" id="net"><span class="dot"></span><span id="net-label">…</span></span>
+ <span class="bal">
+ <span class="amt" id="bal-amt"><span class="skel"></span></span>
+ <span class="usd" id="bal-usd"></span>
+ </span>
+ <a class="addr" id="addr-link" href="#" target="_blank" rel="noopener" title="View on Solscan">
+ <span id="addr-short">—</span>
+ </a>
+ <button class="copy" id="copy-btn" title="Copy address" aria-label="Copy wallet address">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><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>
+ </button>
+ </div>
+ </div>
+
+ <section id="chat" aria-label="Chat with the avatar">
+ <div id="log">
+ <div id="empty">
+ <h2 id="empty-title">Talk to your avatar</h2>
+ <p id="empty-sub">It holds a Solana wallet and can send SOL when you ask.</p>
+ <div class="chips" id="chips"></div>
+ </div>
+ </div>
+ <form id="composer" autocomplete="off">
+ <input id="input" type="text" placeholder="Ask me anything…" aria-label="Message" />
+ <button id="send" type="submit" aria-label="Send message">
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4 20-7z"/></svg>
+ </button>
+ </form>
+ </section>
+
+ <div id="toast" role="alert"></div>
+ </div>
+
+ <script type="module">
+ const params = new URL(location.href).searchParams;
+ const accent = params.get('accent');
+ if (accent && /^#?[0-9a-fA-F]{3,8}$/.test(accent)) {
+ const hex = accent.startsWith('#') ? accent : '#' + accent;
+ document.documentElement.style.setProperty('--accent', hex);
+ }
+
+ // Optional shared-secret for the send endpoint (only needed if the
+ // deployment sets AVATAR_DEMO_TOKEN). Passed through as a header.
+ const sendToken = params.get('token') || '';
+
+ // ── Avatar iframe (reuses the embed's lipsync / idle / gestures) ──
+ const avatarFrame = document.getElementById('avatar-frame');
+ const avatarOrigin = location.origin;
+ const aq = new URLSearchParams();
+ if (params.get('id')) aq.set('id', params.get('id'));
+ else if (params.get('handle')) aq.set('handle', params.get('handle'));
+ else aq.set('model', params.get('model') || '/avatars/default.glb');
+ aq.set('bg', 'transparent');
+ aq.set('idle', 'on');
+ aq.set('name', '0');
+ aq.set('animPicker', '0');
+ aq.set('overlayMode', '1');
+ avatarFrame.src = `/avatar-embed.html?${aq.toString()}`;
+
+ let avatarReady = false;
+ const avatarQueue = [];
+ function toAvatar(msg) {
+ if (avatarReady) avatarFrame.contentWindow?.postMessage(msg, avatarOrigin);
+ else avatarQueue.push(msg);
+ }
+ function avatarSpeak(text) { if (text) toAvatar({ type: 'v1.avatar.speak', text: String(text).slice(0, 600) }); }
+ function avatarGesture(name) { toAvatar({ type: 'v1.avatar.animation', name }); }
+
+ window.addEventListener('message', (e) => {
+ if (e.source !== avatarFrame.contentWindow) return;
+ const t = e.data?.type;
+ if (t === 'v1.avatar.ready') {
+ avatarReady = true;
+ while (avatarQueue.length) avatarFrame.contentWindow?.postMessage(avatarQueue.shift(), avatarOrigin);
+ }
+ });
+ avatarFrame.addEventListener('load', () => {
+ avatarFrame.contentWindow?.postMessage({ type: 'v1.avatar.hello' }, avatarOrigin);
+ });
+
+ // ── Wallet chip ───────────────────────────────────────────────
+ const el = (id) => document.getElementById(id);
+ let wallet = null;
+ const fmtSol = (n) => (n >= 1 ? n.toFixed(3) : n.toFixed(5));
+ const short = (a) => (a ? `${a.slice(0, 4)}…${a.slice(-4)}` : '—');
+
+ async function refreshWallet() {
+ try {
+ const r = await fetch('/api/agent/wallet', { headers: { accept: 'application/json' } });
+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error_description || `wallet ${r.status}`);
+ wallet = await r.json();
+ renderWallet();
+ } catch (err) {
+ el('bal-amt').innerHTML = '<span style="font-size:13px;color:var(--text-dim)">wallet offline</span>';
+ el('bal-usd').textContent = '';
+ console.warn('[wallet]', err.message);
+ }
+ }
+ function renderWallet() {
+ if (!wallet) return;
+ const net = el('net');
+ net.classList.toggle('mainnet', wallet.network === 'mainnet');
+ el('net-label').textContent = wallet.network;
+ el('bal-amt').textContent = `${fmtSol(wallet.sol)} SOL`;
+ el('bal-usd').textContent = wallet.usd != null ? `$${wallet.usd.toFixed(2)}` : '';
+ el('addr-short').textContent = short(wallet.address);
+ el('addr-link').href = wallet.explorer;
+ }
+ el('copy-btn').addEventListener('click', async () => {
+ if (!wallet?.address) return;
+ try {
+ await navigator.clipboard.writeText(wallet.address);
+ const b = el('copy-btn');
+ b.classList.add('done');
+ setTimeout(() => b.classList.remove('done'), 1200);
+ } catch { /* clipboard blocked */ }
+ });
+
+ // ── Toast ─────────────────────────────────────────────────────
+ let toastTimer = null;
+ function toast(msg) {
+ const t = el('toast');
+ t.textContent = msg;
+ t.classList.add('show');
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => t.classList.remove('show'), 4200);
+ }
+
+ // ── Chat ──────────────────────────────────────────────────────
+ const log = el('log');
+ const input = el('input');
+ const sendBtn = el('send');
+ const history = [];
+ let busy = false;
+
+ function clearEmpty() { const e = el('empty'); if (e) e.remove(); }
+ function addMsg(text, who) {
+ clearEmpty();
+ const d = document.createElement('div');
+ d.className = `msg ${who}`;
+ d.textContent = text;
+ log.appendChild(d);
+ log.scrollTop = log.scrollHeight;
+ return d;
+ }
+
+ function paymentCard(usd, to) {
+ clearEmpty();
+ const card = document.createElement('div');
+ card.className = 'pay pending';
+ card.innerHTML = `
+ <div class="head"><span class="ic">◎</span> Sending SOL</div>
+ <div class="amt">$${Number(usd).toFixed(2)}</div>
+ <div class="sub">to ${to ? short(to) : 'you'}</div>
+ <div class="status"><span class="pip"></span><span class="label">Signing & broadcasting…</span></div>`;
+ log.appendChild(card);
+ log.scrollTop = log.scrollHeight;
+ return {
+ ok(res) {
+ card.className = 'pay ok';
+ card.querySelector('.amt').textContent = `${fmtSol(res.sol)} SOL`;
+ card.querySelector('.sub').textContent = `≈ $${res.usd.toFixed(2)} · to ${short(res.to)}`;
+ card.querySelector('.label').textContent = 'Confirmed on-chain';
+ const a = document.createElement('a');
+ a.className = 'sig';
+ a.href = res.explorer; a.target = '_blank'; a.rel = 'noopener';
+ a.textContent = `↗ ${short(res.signature)}`;
+ card.appendChild(a);
+ log.scrollTop = log.scrollHeight;
+ },
+ fail(message) {
+ card.className = 'pay fail';
+ card.querySelector('.label').textContent = message || 'Payment failed';
+ log.scrollTop = log.scrollHeight;
+ },
+ };
+ }
+
+ async function executeSendSol(action) {
+ const card = paymentCard(action.usd, action.to);
+ try {
+ const headers = { 'content-type': 'application/json' };
+ if (sendToken) headers['x-avatar-token'] = sendToken;
+ const r = await fetch('/api/agent/send-sol', {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({ usd: Number(action.usd), to: action.to || undefined }),
+ });
+ const data = await r.json().catch(() => ({}));
+ if (!r.ok || !data.ok) throw new Error(data.error_description || data.message || `send failed (${r.status})`);
+ card.ok(data);
+ avatarSpeak(`Done — I just sent ${fmtSol(data.sol)} SOL, about a dollar, to your wallet.`);
+ avatarGesture('celebrate');
+ refreshWallet();
+ } catch (err) {
+ card.fail(err.message);
+ toast(err.message);
+ avatarSpeak('Hmm, that payment didn’t go through.');
+ }
+ }
+
+ async function runActions(actions) {
+ for (const a of actions || []) {
+ if (a?.type === 'sendSol' && a.usd != null) await executeSendSol(a);
+ else if (a?.type === 'playAnimation' && a.name) avatarGesture(a.name);
+ }
+ }
+
+ async function ask(message) {
+ if (busy || !message.trim()) return;
+ busy = true;
+ sendBtn.disabled = true;
+ input.value = '';
+ addMsg(message, 'user');
+ history.push({ role: 'user', content: message });
+
+ const bot = addMsg('', 'bot');
+ bot.innerHTML = '<span class="cursor">▋</span>';
+ let reply = '';
+ try {
+ const body = { message, context: {}, history: history.slice(-18) };
+ if (params.get('provider')) body.provider = params.get('provider');
+ if (params.get('model')) body.model = params.get('model');
+ if (params.get('agentId')) body.agentId = params.get('agentId');
+
+ const r = await fetch('/api/chat', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ if (!r.ok || !r.body) throw new Error(`chat ${r.status}`);
+
+ const reader = r.body.getReader();
+ const dec = new TextDecoder();
+ let buf = '';
+ let actions = [];
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += dec.decode(value, { stream: true });
+ const lines = buf.split('\n');
+ buf = lines.pop();
+ for (const line of lines) {
+ if (!line.startsWith('data: ')) continue;
+ let evt;
+ try { evt = JSON.parse(line.slice(6)); } catch { continue; }
+ if (evt.type === 'chunk') {
+ reply += evt.text;
+ bot.textContent = reply;
+ log.scrollTop = log.scrollHeight;
+ } else if (evt.type === 'done') {
+ reply = (evt.reply || reply).trim();
+ bot.textContent = reply || '…';
+ actions = evt.actions || [];
+ } else if (evt.type === 'error') {
+ throw new Error(evt.message || 'chat error');
+ }
+ }
+ }
+ if (reply) {
+ history.push({ role: 'assistant', content: reply });
+ avatarSpeak(reply);
+ }
+ await runActions(actions);
+ } catch (err) {
+ bot.textContent = 'I had trouble reaching my brain. Try again in a moment.';
+ toast(err.message || 'chat failed');
+ } finally {
+ busy = false;
+ sendBtn.disabled = false;
+ input.focus();
+ }
+ }
+
+ el('composer').addEventListener('submit', (e) => { e.preventDefault(); ask(input.value); });
+
+ // Suggestion chips (the middle one is the autonomous-payment demo).
+ const chips = [
+ { label: 'What can you do?', send: 'What can you do?' },
+ { label: '💸 Send me $1 of SOL', send: 'Send me $1 of SOL' },
+ { label: 'Wave 👋', send: 'wave at me' },
+ ];
+ const chipsBox = el('chips');
+ for (const c of chips) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.className = 'chip';
+ b.textContent = c.label;
+ b.addEventListener('click', () => ask(c.send));
+ chipsBox.appendChild(b);
+ }
+
+ // ── Boot ──────────────────────────────────────────────────────
+ refreshWallet();
+ setInterval(refreshWallet, 20000);
+ input.focus();
+ </script>
+ </body>
+</html>
diff --git a/scripts/gen-avatar-wallet.mjs b/scripts/gen-avatar-wallet.mjs
new file mode 100644
index 000000000..e1fb65f50
--- /dev/null
+++ b/scripts/gen-avatar-wallet.mjs
@@ -0,0 +1,69 @@
+#!/usr/bin/env node
+// Generate the avatar's custodial Solana wallet for the avatar-wallet-chat
+// widget. Writes the secret to .env (AVATAR_WALLET_SECRET) so it never prints
+// to your terminal, and shows the public address you need to fund.
+//
+// node scripts/gen-avatar-wallet.mjs
+//
+// Then fund the printed address with a few dollars of SOL and (for the real
+// mainnet demo) make sure your deployment has the same AVATAR_WALLET_SECRET.
+
+import { readFileSync, writeFileSync, existsSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { Keypair } from '@solana/web3.js';
+import bs58 from 'bs58';
+
+const bs58encode = bs58.default ? bs58.default.encode : bs58.encode;
+const ENV_PATH = resolve(process.cwd(), '.env');
+
+function readEnv() {
+ if (!existsSync(ENV_PATH)) return '';
+ return readFileSync(ENV_PATH, 'utf8');
+}
+
+function hasVar(contents, name) {
+ return new RegExp(`^${name}=`, 'm').test(contents);
+}
+
+function upsert(contents, name, value) {
+ if (hasVar(contents, name)) return contents; // never clobber existing values
+ const sep = contents && !contents.endsWith('\n') ? '\n' : '';
+ return `${contents}${sep}${name}=${value}\n`;
+}
+
+const existing = readEnv();
+if (hasVar(existing, 'AVATAR_WALLET_SECRET')) {
+ console.error('✗ AVATAR_WALLET_SECRET already exists in .env — refusing to overwrite.');
+ console.error(' Remove it first if you really want a new wallet.');
+ process.exit(1);
+}
+
+const kp = Keypair.generate();
+const address = kp.publicKey.toBase58();
+const secret = bs58encode(kp.secretKey);
+
+let next = upsert(existing, 'AVATAR_WALLET_SECRET', secret);
+next = upsert(next, 'AVATAR_NETWORK', 'mainnet');
+next = upsert(next, 'AVATAR_MAX_SEND_USD', '2');
+writeFileSync(ENV_PATH, next, { mode: 0o600 });
+
+console.log('');
+console.log(' ✓ Avatar wallet created. Secret written to .env (AVATAR_WALLET_SECRET).');
+console.log('');
+console.log(' Public address (fund this):');
+console.log(` ${address}`);
+console.log('');
+console.log(' Explorer:');
+console.log(` https://solscan.io/account/${address}`);
+console.log('');
+console.log(' Next steps:');
+console.log(' 1. Send ~$3 of SOL to the address above (mainnet).');
+console.log(' 2. Set the SAME env vars on your deployment:');
+console.log(' AVATAR_WALLET_SECRET, AVATAR_NETWORK=mainnet, AVATAR_MAX_SEND_USD=2');
+console.log(' Optional: AVATAR_DEFAULT_RECIPIENT=<your address> (the "send me" target)');
+console.log(' Optional: AVATAR_DEMO_TOKEN=<secret> (then load the widget with ?token=<secret>)');
+console.log(' 3. Open /avatar-wallet-chat and say: "send me $1 of SOL".');
+console.log('');
+console.log(' Tip: try it on devnet first — set AVATAR_NETWORK=devnet and run');
+console.log(' node scripts/verify-send-sol.mjs (free, proves the on-chain path).');
+console.log('');
diff --git a/scripts/verify-send-sol.mjs b/scripts/verify-send-sol.mjs
new file mode 100644
index 000000000..48f7c4279
--- /dev/null
+++ b/scripts/verify-send-sol.mjs
@@ -0,0 +1,125 @@
+#!/usr/bin/env node
+// Verifies the avatar's money-movement path.
+//
+// Phase 1 (offline, deterministic): builds + signs the EXACT transfer the
+// /api/agent/send-sol endpoint submits and proves it is cryptographically
+// valid — signature verifies, correct SystemProgram.transfer (from/to/
+// lamports) and memo instruction. No network, never flaky.
+//
+// Phase 2 (on-chain, best-effort): airdrops devnet SOL and does a real
+// transfer via sendSol(). If the public faucet is dry/rate-limited it is
+// SKIPPED (not failed) — Phase 1 already proves the code path.
+//
+// node scripts/verify-send-sol.mjs
+//
+// Exits non-zero only if Phase 1 fails.
+
+import { Keypair, LAMPORTS_PER_SOL, SystemProgram, PublicKey } from '@solana/web3.js';
+import {
+ getConnection,
+ getSolBalance,
+ sendSol,
+ buildSignedSolTransfer,
+ explorerTxUrl,
+} from '../api/_lib/avatar-wallet.js';
+
+const SYSTEM_PROGRAM = SystemProgram.programId.toBase58();
+const MEMO_PROGRAM = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';
+const DEVNET = process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+function assert(cond, msg) {
+ if (!cond) throw new Error(msg);
+}
+
+// ── Phase 1: offline build + sign + verify ──────────────────────────────────
+function phaseOffline() {
+ console.log('▸ Phase 1 — offline build/sign/verify (deterministic)\n');
+ const from = Keypair.generate();
+ const to = Keypair.generate();
+ const lamports = Math.round(0.0067 * LAMPORTS_PER_SOL); // ~$1 of SOL @ ~$150
+ const memo = 'three.ws avatar · $1.00 SOL';
+ // A recent blockhash is just a 32-byte base58 value for signing purposes.
+ const blockhash = Keypair.generate().publicKey.toBase58();
+
+ const tx = buildSignedSolTransfer({ fromKeypair: from, to: to.publicKey, lamports, memo, blockhash });
+
+ assert(tx.verifySignatures() === true, 'signature does not verify');
+ assert(tx.feePayer.equals(from.publicKey), 'fee payer is not the sender');
+ assert(tx.instructions.length === 2, `expected 2 instructions, got ${tx.instructions.length}`);
+
+ const [transferIx, memoIx] = tx.instructions;
+ assert(transferIx.programId.toBase58() === SYSTEM_PROGRAM, 'first ix is not the System Program');
+ assert(transferIx.keys[0].pubkey.equals(from.publicKey), 'transfer source mismatch');
+ assert(transferIx.keys[1].pubkey.equals(to.publicKey), 'transfer destination mismatch');
+ // SystemProgram transfer encodes: u32 instruction index (2) + u64 lamports (LE).
+ const encodedLamports = transferIx.data.readBigUInt64LE(4);
+ assert(encodedLamports === BigInt(lamports), `encoded lamports ${encodedLamports} !== ${lamports}`);
+
+ assert(memoIx.programId.toBase58() === MEMO_PROGRAM, 'second ix is not the Memo Program');
+ assert(memoIx.data.toString('utf8') === memo, 'memo payload mismatch');
+
+ console.log(` ✓ signature verifies (ed25519)`);
+ console.log(` ✓ SystemProgram.transfer ${from.publicKey.toBase58().slice(0, 6)}… → ${to.publicKey.toBase58().slice(0, 6)}… for ${encodedLamports} lamports`);
+ console.log(` ✓ memo instruction = "${memo}"`);
+ console.log(` ✓ serializes to ${tx.serialize().length} bytes (submittable)\n`);
+}
+
+// ── Phase 2: best-effort real devnet send ───────────────────────────────────
+async function phaseOnchain() {
+ console.log('▸ Phase 2 — real devnet transfer (best-effort)\n');
+ const connection = getConnection(DEVNET);
+ const sender = Keypair.generate();
+ const recipient = Keypair.generate();
+
+ let funded = false;
+ for (let attempt = 1; attempt <= 2 && !funded; attempt++) {
+ try {
+ const sig = await connection.requestAirdrop(sender.publicKey, LAMPORTS_PER_SOL);
+ const bh = await connection.getLatestBlockhash('confirmed');
+ await connection.confirmTransaction({ signature: sig, ...bh }, 'confirmed');
+ funded = true;
+ } catch (err) {
+ if (/429|airdrop limit|faucet has run dry|Internal error/i.test(err.message)) {
+ console.log(' ⓘ devnet faucet unavailable (rate-limited / dry) — SKIPPING on-chain phase.');
+ console.log(' Phase 1 already proved the transfer is correct & submittable.');
+ console.log(' To run live: fund a devnet wallet at https://faucet.solana.com and re-run,');
+ console.log(' or set AVATAR_NETWORK=mainnet on a funded wallet for the real demo.\n');
+ return 'skipped';
+ }
+ console.log(` airdrop attempt ${attempt} failed (${err.message}) — retrying…`);
+ await sleep(2000);
+ }
+ }
+ if (!funded) {
+ console.log(' ⓘ could not fund devnet wallet — SKIPPING on-chain phase.\n');
+ return 'skipped';
+ }
+
+ const lamports = Math.round(0.01 * LAMPORTS_PER_SOL);
+ const signature = await sendSol({
+ connection,
+ fromKeypair: sender,
+ to: recipient.publicKey,
+ lamports,
+ memo: 'three.ws avatar · devnet verify',
+ });
+ const recvBal = await getSolBalance(connection, recipient.publicKey);
+ assert(recvBal.lamports === lamports, `recipient got ${recvBal.lamports}, expected ${lamports}`);
+ console.log(` ✓ confirmed on-chain: ${signature}`);
+ console.log(` ${explorerTxUrl(signature, 'devnet')}`);
+ console.log(` ✓ recipient received exactly ${recvBal.sol} SOL\n`);
+ return 'sent';
+}
+
+(async () => {
+ phaseOffline();
+ const onchain = await phaseOnchain();
+ console.log(onchain === 'sent'
+ ? '✅ Money path verified offline AND on-chain.'
+ : '✅ Money path verified offline (on-chain phase skipped — faucet dry).');
+ process.exit(0);
+})().catch((err) => {
+ console.error('\n✗ verification failed:', err?.message || err);
+ process.exit(1);
+});
diff --git a/vite.config.js b/vite.config.js
index 05d8686f9..d2b199ca6 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -249,6 +249,7 @@ const appConfig = {
'agent-embed': resolve(__dirname, 'pages/agent-embed.html'),
'agent-detail': resolve(__dirname, 'pages/agent-detail.html'),
'avatar-embed': resolve(__dirname, 'pages/avatar-embed.html'),
+ 'avatar-wallet-chat': resolve(__dirname, 'pages/avatar-wallet-chat.html'),
'overlay-control': resolve(__dirname, 'pages/overlay-control.html'),
'mocap-studio': resolve(__dirname, 'pages/mocap-studio.html'),
handle: resolve(__dirname, 'pages/handle.html'),
@@ -538,6 +539,8 @@ const appConfig = {
'/game/': resolve(root, 'pages/game.html'),
'/walk-embed': resolve(root, 'pages/walk-embed.html'),
'/walk-embed/': resolve(root, 'pages/walk-embed.html'),
+ '/avatar-wallet-chat': resolve(root, 'pages/avatar-wallet-chat.html'),
+ '/avatar-wallet-chat/': resolve(root, 'pages/avatar-wallet-chat.html'),
'/pose': resolve(root, 'pages/pose.html'),
'/pose/': resolve(root, 'pages/pose.html'),
'/club': resolve(root, 'pages/club.html'),